DEVELOPMENT ENVIRONMENT

~liljamo/tixe

ref: 6124b16e89cc33cf9e3b2df29c709b1f1465ac53 tixe/api/user_settings.go -rw-r--r-- 1.4 KiB
6124b16eJonni Liljamo fix: abort if not logged in... 1 year, 1 month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under AGPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */
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")
}