camper/pkg/booking/public.go

302 lines
9.5 KiB
Go
Raw Normal View History

/*
* SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
* SPDX-License-Identifier: AGPL-3.0-only
*/
package booking
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"net/http"
"dev.tandem.ws/tandem/camper/pkg/auth"
"dev.tandem.ws/tandem/camper/pkg/database"
"dev.tandem.ws/tandem/camper/pkg/form"
httplib "dev.tandem.ws/tandem/camper/pkg/http"
"dev.tandem.ws/tandem/camper/pkg/locale"
"dev.tandem.ws/tandem/camper/pkg/redsys"
"dev.tandem.ws/tandem/camper/pkg/template"
)
type PublicHandler struct {
}
func NewPublicHandler() *PublicHandler {
return &PublicHandler{}
}
func (h *PublicHandler) Handler(user *auth.User, company *auth.Company, conn *database.Conn) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var head string
head, r.URL.Path = httplib.ShiftPath(r.URL.Path)
switch head {
case "":
switch r.Method {
case http.MethodGet:
page := newPublicPage(r.Context(), company, conn, user.Locale)
_ = r.ParseForm()
page.Form.CampsiteType.FillValue(r)
page.Form.ArrivalDate.FillValue(r)
page.Form.DepartureDate.FillValue(r)
page.MustRender(w, r, user, company, conn)
case http.MethodPost:
makeReservation(w, r, user, company, conn)
default:
httplib.MethodNotAllowed(w, r, http.MethodGet, http.MethodPost)
}
case "success":
handleSuccessfulPayment(w, r, user, company, conn)
case "failure":
handleFailedPayment(w, r, user, company, conn)
default:
http.NotFound(w, r)
}
})
}
func makeReservation(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
f := newBookingForm(r.Context(), company, conn, user.Locale)
if err := f.Parse(r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if ok, err := f.Valid(r.Context(), conn, user.Locale); err != nil {
panic(err)
} else if !ok {
if !httplib.IsHTMxRequest(r) {
w.WriteHeader(http.StatusUnprocessableEntity)
}
page := newPublicPageWithForm(f)
page.MustRender(w, r, user, company, conn)
return
}
schema := httplib.Protocol(r)
authority := httplib.Host(r)
request := &redsys.Request{
TransactionType: redsys.TransactionTypeCharge,
Implement Redsys request signature in PostgreSQL Every company need to have its own merchant code and encryption key, thus it is not possible to use environment variables to keep that data, and i have to store it in the database. I do not want to give SELECT permission on the encryption key to guest, because i am going to fuck it up sooner or later, and everyone would be able to read that secret; i know it would. Therefore, i need a security definer function that takes the data to encrypt, use the key to encrypt it, and returns the result; nobody else should have access to that key, not even admins! By the way, i found out that every merchant receives the same key, thus it is not a problem to keep it in the repository. Since i need that SQL function to encrypt the data, i thought that i may go the whole nine yards and sign the request in PostgreSQL too, after all the data to sign comes from there, and it has JSON functions to create and base64-code an object. Fortunately, pg_crypto has all the functions that i need, but i can no longer keep that extension inside the auth schema, because it is used from others, and the public schema, like every other extensions, seems more appropriate. Instead of having the list of currency and language codes that Redsys uses as constants in the code, i moved that as field to the currency and language relations, so i can simply pass the lang_tag to the function and it can transform that tag to the correct code; the currency is from the company’s relation, since it is the only currency used in the whole application (for now). As a consequence, i had to grant execute to currency and the parse_price functions to guest, too. To generate the test data used in the unit tests, i used a third-party PHP implementation[0], but i only got from that the resulting base64-coded JSON object and signature, using the same that as in the unit test, and did not use any code from there. PostgreSQL formats the JSON as text differently than most implementations i have seen: it adds spaces between the key name and the colons, and space between the value and the separating comma. The first implementation used replace() to format the JSON as exactly as the PHP implementation, so that the result matches, and then tried to do generate the form by hand using the output from PostgreSQL without the replace(), to verify that Redsys would still accept my input. Finally, i adjusted the unit test to whatever pg_prove said it was getting from the function. I still have the form’s action hard-codded to the test environment, but the idea is that administrators should be able to switch from test to live themselves. That means that i need that info in the redsys relation as well. I think this is one of the few use cases for SQL’s types, because it is unlikely to change anytime soon, and i do not need the actual labels. Unfortunately, i could not use enumerations for the request’s transaction type because i can not attach an arbitrary number to the enum’s values. Having a relation is overkill, because i would need a constant in Go to refer to its primary key anyway, thus i kept the same constant i had before for that. Language and currency constant went out, as this is in the corresponding relations. In setup_redsys i must have a separate update if the encrypt_key is null because PostgreSQL checks constraints before key conflict, and i do not want to give a default value to the key if the row is not there yet. The problem is that i want to use null to mean “keep the same password”, because it is what i intend to do with the user-facing form: leave the input empty to keep the same password. As now Go needs to pass composite types back and forth with PostgreSQL, i need to register these types, and i have to do it every time because the only moment i have access to the non-pooled connection is in the AfterConnect function, but at that point i have no idea whether the user is going to request a payment. I do not know how much the performance degrades because of this. [0]: https://github.com/ssheduardo/sermepa/blob/master/src/Sermepa/Tpv/Tpv.php
2023-10-26 23:52:04 +00:00
Amount: "12.34",
OrderNumber: randomOrderNumber(),
Product: "Test Booking",
SuccessURL: fmt.Sprintf("%s://%s/%s/booking/success", schema, authority, user.Locale.Language),
FailureURL: fmt.Sprintf("%s://%s/%s/booking/failure", schema, authority, user.Locale.Language),
Implement Redsys request signature in PostgreSQL Every company need to have its own merchant code and encryption key, thus it is not possible to use environment variables to keep that data, and i have to store it in the database. I do not want to give SELECT permission on the encryption key to guest, because i am going to fuck it up sooner or later, and everyone would be able to read that secret; i know it would. Therefore, i need a security definer function that takes the data to encrypt, use the key to encrypt it, and returns the result; nobody else should have access to that key, not even admins! By the way, i found out that every merchant receives the same key, thus it is not a problem to keep it in the repository. Since i need that SQL function to encrypt the data, i thought that i may go the whole nine yards and sign the request in PostgreSQL too, after all the data to sign comes from there, and it has JSON functions to create and base64-code an object. Fortunately, pg_crypto has all the functions that i need, but i can no longer keep that extension inside the auth schema, because it is used from others, and the public schema, like every other extensions, seems more appropriate. Instead of having the list of currency and language codes that Redsys uses as constants in the code, i moved that as field to the currency and language relations, so i can simply pass the lang_tag to the function and it can transform that tag to the correct code; the currency is from the company’s relation, since it is the only currency used in the whole application (for now). As a consequence, i had to grant execute to currency and the parse_price functions to guest, too. To generate the test data used in the unit tests, i used a third-party PHP implementation[0], but i only got from that the resulting base64-coded JSON object and signature, using the same that as in the unit test, and did not use any code from there. PostgreSQL formats the JSON as text differently than most implementations i have seen: it adds spaces between the key name and the colons, and space between the value and the separating comma. The first implementation used replace() to format the JSON as exactly as the PHP implementation, so that the result matches, and then tried to do generate the form by hand using the output from PostgreSQL without the replace(), to verify that Redsys would still accept my input. Finally, i adjusted the unit test to whatever pg_prove said it was getting from the function. I still have the form’s action hard-codded to the test environment, but the idea is that administrators should be able to switch from test to live themselves. That means that i need that info in the redsys relation as well. I think this is one of the few use cases for SQL’s types, because it is unlikely to change anytime soon, and i do not need the actual labels. Unfortunately, i could not use enumerations for the request’s transaction type because i can not attach an arbitrary number to the enum’s values. Having a relation is overkill, because i would need a constant in Go to refer to its primary key anyway, thus i kept the same constant i had before for that. Language and currency constant went out, as this is in the corresponding relations. In setup_redsys i must have a separate update if the encrypt_key is null because PostgreSQL checks constraints before key conflict, and i do not want to give a default value to the key if the row is not there yet. The problem is that i want to use null to mean “keep the same password”, because it is what i intend to do with the user-facing form: leave the input empty to keep the same password. As now Go needs to pass composite types back and forth with PostgreSQL, i need to register these types, and i have to do it every time because the only moment i have access to the non-pooled connection is in the AfterConnect function, but at that point i have no idea whether the user is going to request a payment. I do not know how much the performance degrades because of this. [0]: https://github.com/ssheduardo/sermepa/blob/master/src/Sermepa/Tpv/Tpv.php
2023-10-26 23:52:04 +00:00
NotificationURL: fmt.Sprintf("%s://%s/%s/booking/notification", schema, authority, user.Locale.Language),
ConsumerLanguage: user.Locale.Language,
}
Implement Redsys request signature in PostgreSQL Every company need to have its own merchant code and encryption key, thus it is not possible to use environment variables to keep that data, and i have to store it in the database. I do not want to give SELECT permission on the encryption key to guest, because i am going to fuck it up sooner or later, and everyone would be able to read that secret; i know it would. Therefore, i need a security definer function that takes the data to encrypt, use the key to encrypt it, and returns the result; nobody else should have access to that key, not even admins! By the way, i found out that every merchant receives the same key, thus it is not a problem to keep it in the repository. Since i need that SQL function to encrypt the data, i thought that i may go the whole nine yards and sign the request in PostgreSQL too, after all the data to sign comes from there, and it has JSON functions to create and base64-code an object. Fortunately, pg_crypto has all the functions that i need, but i can no longer keep that extension inside the auth schema, because it is used from others, and the public schema, like every other extensions, seems more appropriate. Instead of having the list of currency and language codes that Redsys uses as constants in the code, i moved that as field to the currency and language relations, so i can simply pass the lang_tag to the function and it can transform that tag to the correct code; the currency is from the company’s relation, since it is the only currency used in the whole application (for now). As a consequence, i had to grant execute to currency and the parse_price functions to guest, too. To generate the test data used in the unit tests, i used a third-party PHP implementation[0], but i only got from that the resulting base64-coded JSON object and signature, using the same that as in the unit test, and did not use any code from there. PostgreSQL formats the JSON as text differently than most implementations i have seen: it adds spaces between the key name and the colons, and space between the value and the separating comma. The first implementation used replace() to format the JSON as exactly as the PHP implementation, so that the result matches, and then tried to do generate the form by hand using the output from PostgreSQL without the replace(), to verify that Redsys would still accept my input. Finally, i adjusted the unit test to whatever pg_prove said it was getting from the function. I still have the form’s action hard-codded to the test environment, but the idea is that administrators should be able to switch from test to live themselves. That means that i need that info in the redsys relation as well. I think this is one of the few use cases for SQL’s types, because it is unlikely to change anytime soon, and i do not need the actual labels. Unfortunately, i could not use enumerations for the request’s transaction type because i can not attach an arbitrary number to the enum’s values. Having a relation is overkill, because i would need a constant in Go to refer to its primary key anyway, thus i kept the same constant i had before for that. Language and currency constant went out, as this is in the corresponding relations. In setup_redsys i must have a separate update if the encrypt_key is null because PostgreSQL checks constraints before key conflict, and i do not want to give a default value to the key if the row is not there yet. The problem is that i want to use null to mean “keep the same password”, because it is what i intend to do with the user-facing form: leave the input empty to keep the same password. As now Go needs to pass composite types back and forth with PostgreSQL, i need to register these types, and i have to do it every time because the only moment i have access to the non-pooled connection is in the AfterConnect function, but at that point i have no idea whether the user is going to request a payment. I do not know how much the performance degrades because of this. [0]: https://github.com/ssheduardo/sermepa/blob/master/src/Sermepa/Tpv/Tpv.php
2023-10-26 23:52:04 +00:00
signed, err := redsys.SignRequest(r.Context(), conn, company, request)
if err != nil {
panic(err)
}
page := newPaymentPage(signed)
page.MustRender(w, r, user, company, conn)
}
func randomOrderNumber() string {
bytes := make([]byte, 6)
if _, err := rand.Read(bytes); err != nil {
panic(err)
}
return hex.EncodeToString(bytes)
}
type publicPage struct {
*template.PublicPage
Form *bookingForm
}
func newPublicPage(ctx context.Context, company *auth.Company, conn *database.Conn, l *locale.Locale) *publicPage {
return newPublicPageWithForm(newBookingForm(ctx, company, conn, l))
}
func newPublicPageWithForm(form *bookingForm) *publicPage {
return &publicPage{
PublicPage: template.NewPublicPage(),
Form: form,
}
}
func (p *publicPage) MustRender(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
p.Setup(r, user, company, conn)
template.MustRenderPublic(w, r, user, company, "booking.gohtml", p)
}
type bookingForm struct {
FullName *form.Input
Address *form.Input
PostalCode *form.Input
City *form.Input
Country *form.Select
Email *form.Input
Phone *form.Input
CampsiteType *form.Select
CampsiteTypeOptions map[string][]*campsiteTypeOption
ArrivalDate *form.Input
DepartureDate *form.Input
AreaPreferences *form.Input
ACSICard *form.Checkbox
Agreement *form.Checkbox
}
type campsiteTypeOption struct {
Label string
Min int
Max int
Input *form.Input
}
func newBookingForm(ctx context.Context, company *auth.Company, conn *database.Conn, l *locale.Locale) *bookingForm {
f := &bookingForm{
FullName: &form.Input{
Name: "full_name",
},
Address: &form.Input{
Name: "address",
},
PostalCode: &form.Input{
Name: "postal_code",
},
City: &form.Input{
Name: "city",
},
Country: &form.Select{
Name: "country",
Options: form.MustGetOptions(ctx, conn, "select country.country_code, coalesce(i18n.name, country.name) as l10n_name from country left join country_i18n as i18n on country.country_code = i18n.country_code and i18n.lang_tag = $1 order by l10n_name", l.Language),
},
Email: &form.Input{
Name: "email",
},
Phone: &form.Input{
Name: "phone",
},
CampsiteType: &form.Select{
Name: "campsite_type",
Options: form.MustGetOptions(ctx, conn, "select type.slug, coalesce(i18n.name, type.name) as l10n_name from campsite_type as type left join campsite_type_i18n as i18n on type.campsite_type_id = i18n.campsite_type_id and i18n.lang_tag = $1 where company_id = $2 order by l10n_name", l.Language, company.ID),
},
CampsiteTypeOptions: make(map[string][]*campsiteTypeOption),
ArrivalDate: &form.Input{
Name: "arrival_date",
},
DepartureDate: &form.Input{
Name: "departure_date",
},
AreaPreferences: &form.Input{
Name: "area_preferences",
},
ACSICard: &form.Checkbox{
Name: "acsi_card",
},
Agreement: &form.Checkbox{
Name: "agreement",
},
}
rows, err := conn.Query(ctx, `
select 'campsite_type_option_' || option.campsite_type_option_id
, slug
, coalesce(option.name, i18n.name) as l10_name
, lower(range)::text
, lower(range)
, upper(range)
from campsite_type_option as option
join campsite_type using (campsite_type_id)
left join campsite_type_option_i18n as i18n on i18n.campsite_type_option_id = option.campsite_type_id and i18n.lang_tag = $1
where company_id = $2
`, l.Language, company.ID)
if err != nil {
panic(err)
}
for rows.Next() {
var slug string
option := &campsiteTypeOption{
Input: &form.Input{},
}
if err := rows.Scan(&option.Input.Name, &slug, &option.Label, &option.Input.Val, &option.Min, &option.Max); err != nil {
panic(err)
}
f.CampsiteTypeOptions[slug] = append(f.CampsiteTypeOptions[slug], option)
}
if rows.Err() != nil {
panic(rows.Err())
}
return f
}
func (f *bookingForm) Parse(r *http.Request) error {
if err := r.ParseForm(); err != nil {
return err
}
f.FullName.FillValue(r)
f.Address.FillValue(r)
f.PostalCode.FillValue(r)
f.City.FillValue(r)
f.Country.FillValue(r)
f.Email.FillValue(r)
f.Phone.FillValue(r)
f.CampsiteType.FillValue(r)
f.ArrivalDate.FillValue(r)
f.DepartureDate.FillValue(r)
f.AreaPreferences.FillValue(r)
f.ACSICard.FillValue(r)
f.Agreement.FillValue(r)
for _, options := range f.CampsiteTypeOptions {
for _, option := range options {
option.Input.FillValue(r)
}
}
return nil
}
func (f *bookingForm) Valid(ctx context.Context, conn *database.Conn, l *locale.Locale) (bool, error) {
v := form.NewValidator(l)
var country string
if v.CheckSelectedOptions(f.Country, l.GettextNoop("Selected country is not valid.")) {
country = f.Country.Selected[0]
}
if v.CheckRequired(f.FullName, l.GettextNoop("Full name can not be empty.")) {
v.CheckMinLength(f.FullName, 1, l.GettextNoop("Full name must have at least one letter."))
}
if country != "" && f.PostalCode.Val != "" {
if _, err := v.CheckValidPostalCode(ctx, conn, f.PostalCode, country, l.GettextNoop("This postal code is not valid.")); err != nil {
return false, err
}
}
if v.CheckRequired(f.Email, l.GettextNoop("Email can not be empty.")) {
v.CheckValidEmail(f.Email, l.GettextNoop("This email is not valid. It should be like name@domain.com."))
}
if v.CheckRequired(f.Phone, l.GettextNoop("Phone can not be empty.")) {
if _, err := v.CheckValidPhone(ctx, conn, f.Phone, country, l.GettextNoop("This phone number is not valid.")); err != nil {
return false, err
}
}
var validBefore bool
v.CheckSelectedOptions(f.CampsiteType, l.GettextNoop("Selected campsite type is not valid."))
if v.CheckRequired(f.ArrivalDate, l.GettextNoop("Arrival date can not be empty")) {
if v.CheckValidDate(f.ArrivalDate, l.GettextNoop("Arrival date must be a valid date.")) {
validBefore = true
}
}
if v.CheckRequired(f.DepartureDate, l.GettextNoop("Departure date can not be empty")) {
if v.CheckValidDate(f.DepartureDate, l.GettextNoop("Departure date must be a valid date.")) && validBefore {
v.CheckDateAfter(f.DepartureDate, f.ArrivalDate, l.GettextNoop("The departure date must be after the arrival date."))
}
}
v.Check(f.Agreement, f.Agreement.Checked, l.GettextNoop("It is mandatory to agree to the reservation conditions."))
for _, options := range f.CampsiteTypeOptions {
for _, option := range options {
if v.CheckRequired(option.Input, fmt.Sprintf(l.Gettext("%s can not be empty"), option.Label)) {
if v.CheckValidInteger(option.Input, fmt.Sprintf(l.Gettext("%s must be an integer."), option.Label)) {
if v.CheckMinInteger(option.Input, option.Min, fmt.Sprintf(l.Gettext("%s must be %d or greater."), option.Label, option.Min)) {
v.CheckMaxInteger(option.Input, option.Max, fmt.Sprintf(l.Gettext("%s must be at most %d."), option.Label, option.Max))
}
}
}
}
}
return v.AllOK, nil
}