73 lines
1.7 KiB
Go
73 lines
1.7 KiB
Go
package pkg
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
)
|
|
|
|
type LanguageOption struct {
|
|
Tag string
|
|
Name string
|
|
}
|
|
|
|
type ProfilePage struct {
|
|
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)
|
|
page := ProfilePage{
|
|
Email: user.Email,
|
|
Languages: getLanguageOptions(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.Exec(r.Context(), "update user_profile set name = $1, email = $2, lang_tag = $3", page.Name, page.Email, page.Language);
|
|
} else {
|
|
if err := conn.QueryRow(r.Context(), "select name, lang_tag from user_profile").Scan(&page.Name, &page.Language); err != nil {
|
|
panic(nil)
|
|
}
|
|
}
|
|
renderTemplate(w, r, "profile.html", page)
|
|
})
|
|
}
|
|
|
|
func getLanguageOptions(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
|
|
}
|