DEVELOPMENT ENVIRONMENT

~liljamo/tixe

ref: fd89e5586bdbdf5e55057348c82306f33718cdb8 tixe/middlewares/auth.go -rw-r--r-- 1.3 KiB
fd89e558Jonni Liljamo fix: fix cookie issue 11 months 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
53
54
55
56
57
58
59
/*
 * 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 middlewares

import (
	"context"
	"log"
	"net/http"
	"tixe/db"
	"tixe/types"
	"tixe/util"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

func IsAuthenticated(c *gin.Context) {
	if sessions.Default(c).Get("profile") == nil {
		c.Redirect(http.StatusSeeOther, "/login")
		c.Abort()
	} else {
		// Here, we verify if the user actually exists. Bla bla forgery, bla bla,
		// but mainly this was an issue on the demo.
		session := sessions.Default(c)
		user := session.Get("user").(types.User)

		var exists bool
		err := db.PgPool.QueryRow(context.Background(),
			"SELECT EXISTS(SELECT 1 FROM users WHERE id = $1)",
				user.Id).Scan(&exists)
		if err != nil || !exists {
			session.Clear()
			if err := session.Save(); err != nil {
				errStr := "Failed to save session"
				log.Printf("[tixe/auth] ERROR: %s: %v", errStr, err)
				util.RenderError(c, "session error", errStr, nil)
				return
			}
			c.Redirect(http.StatusSeeOther, "/login")
			c.Abort()
			return
		}

		c.Next()
	}
}

func CanLogin(c *gin.Context) {
	if sessions.Default(c).Get("profile") != nil {
		// Don't allow the login page if logged in
		c.Redirect(http.StatusSeeOther, "/")
	} else {
		c.Next()
	}
}