package api
import (
"context"
"log"
"net/http"
"tixe/db"
"tixe/types"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
type postDisplayName struct {
DisplayName string `form:"display_name"`
}
func UserUpdateDisplayName(c *gin.Context) {
data := &postDisplayName{}
if err := c.Bind(data); err != nil {
log.Printf("[tixe/api] ERROR: Could not bind display name update data: %v", err)
c.String(http.StatusBadRequest, "Could not bind display name update data")
return;
}
session := sessions.Default(c)
user := session.Get("user").(types.User)
_, err := db.PgPool.Exec(context.Background(),
"UPDATE users SET display_name = $1 WHERE id = $2", data.DisplayName, user.Id)
if err != nil {
log.Printf("[tixe/api] ERROR: Could not update display name in database: %v", err)
c.String(http.StatusInternalServerError, "Could not update display name in database")
return;
}
// Update session data
session.Set("user", types.User { Id: user.Id, DisplayName: data.DisplayName })
if err := session.Save(); err != nil {
log.Printf("[tixe/auth] ERROR: Failed to save session: %v", err)
c.String(http.StatusInternalServerError, "Failed to save session!")
return
}
c.Redirect(http.StatusFound, "/settings")
}