This repository has been archived on 2022-08-26. You can view files and clone it, but cannot push or open issues or pull requests.
gosocial/pkg/controller/account/settings.go
Noah Petherbridge c43d052665 User Profile and Settings Pages
* Vendor fontawesome icons
* User settings page: to edit profile details (other features not hooked
  up yet)
* Initial user profile page
2022-08-10 20:59:59 -07:00

90 lines
2.4 KiB
Go

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,
}
// 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")
)
// 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
}
// 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 "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
}
})
}