website/pkg/controller/account/settings.go

102 lines
2.7 KiB
Go
Raw Normal View History

package account
import (
"net/http"
"strings"
"time"
"git.kirsle.net/apps/gosocial/pkg/config"
"git.kirsle.net/apps/gosocial/pkg/session"
"git.kirsle.net/apps/gosocial/pkg/templates"
"git.kirsle.net/apps/gosocial/pkg/utility"
)
// User settings page. (/settings).
func Settings() http.HandlerFunc {
tmpl := templates.Must("account/settings.html")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := map[string]interface{}{
"Enum": config.ProfileEnums,
}
// Load the current user in case of updates.
user, err := session.CurrentUser(r)
if err != nil {
session.FlashError(w, r, "Couldn't get CurrentUser: %s", err)
templates.Redirect(w, r.URL.Path)
return
}
// Are we POSTing?
if r.Method == http.MethodPost {
intent := r.PostFormValue("intent")
switch intent {
case "profile":
// Setting profile values.
var (
displayName = r.PostFormValue("display_name")
dob = r.PostFormValue("dob")
)
// Set user attributes.
user.Name = &displayName
if len(dob) > 0 {
if birthdate, err := time.Parse("2006-01-02", dob); err != nil {
session.FlashError(w, r, "Incorrect format for birthdate; should be in yyyy-mm-dd format but got: %s", dob)
} else {
// Validate birthdate is at least age 18.
if utility.Age(birthdate) < 18 {
session.FlashError(w, r, "Invalid birthdate: you must be at least 18 years old to use this site.")
templates.Redirect(w, r.URL.Path)
return
}
user.Birthdate = birthdate
}
} else {
user.Birthdate = time.Time{}
}
// Set profile attributes.
for _, attr := range config.ProfileFields {
user.SetProfileField(attr, r.PostFormValue(attr))
}
// "Looking For" checkbox list.
if hereFor, ok := r.PostForm["here_for"]; ok {
user.SetProfileField("here_for", strings.Join(hereFor, ","))
}
if err := user.Save(); err != nil {
session.FlashError(w, r, "Failed to save user to database: %s", err)
}
session.Flash(w, r, "Profile settings updated!")
case "preferences":
var (
explicit = r.PostFormValue("explicit") == "true"
)
user.Explicit = explicit
if err := user.Save(); err != nil {
session.FlashError(w, r, "Failed to save user to database: %s", err)
}
session.Flash(w, r, "Website preferences updated!")
case "settings":
fallthrough
default:
session.FlashError(w, r, "Unknown POST intent value. Please try again.")
}
templates.Redirect(w, r.URL.Path)
return
}
if err := tmpl.Execute(w, r, vars); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
}