numerus/pkg/profile.go

78 lines
1.9 KiB
Go

package pkg
import (
"context"
"net/http"
)
type LanguageOption struct {
Tag string
Name string
}
type ProfilePage struct {
Title string
Name string
Email string
Password string
PasswordConfirm string
Language string
Languages []LanguageOption
}
func ProfileHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := getUser(r)
if !user.LoggedIn {
http.Redirect(w, r, "/login", http.StatusUnauthorized)
return
}
conn := getConn(r)
locale := getLocale(r)
page := ProfilePage{
Title: pgettext("title", "User Settings", locale),
Email: user.Email,
Languages: mustGetLanguageOptions(r.Context(), conn),
}
if r.Method == "POST" {
r.ParseForm()
page.Email = r.FormValue("email")
page.Name = r.FormValue("name")
page.Password = r.FormValue("password")
page.PasswordConfirm = r.FormValue("password_confirm")
page.Language = r.FormValue("language")
conn.MustExec(r.Context(), "update user_profile set name = $1, email = $2, lang_tag = $3", page.Name, page.Email, page.Language)
http.Redirect(w, r, "/profile", http.StatusSeeOther);
return;
} else {
if err := conn.QueryRow(r.Context(), "select name, lang_tag from user_profile").Scan(&page.Name, &page.Language); err != nil {
panic(nil)
}
}
mustRenderAppTemplate(w, r, "profile.html", page)
})
}
func mustGetLanguageOptions(ctx context.Context, conn *Conn) []LanguageOption {
rows, err := conn.Query(ctx, "select lang_tag, endonym from language where selectable")
if err != nil {
panic(err)
}
defer rows.Close()
var langs []LanguageOption
for rows.Next() {
var lang LanguageOption
err = rows.Scan(&lang.Tag, &lang.Name)
if err != nil {
panic(err)
}
langs = append(langs, lang)
}
if rows.Err() != nil {
panic(rows.Err())
}
return langs
}