DEVELOPMENT ENVIRONMENT

~liljamo/tixe

ref: 0.1.3 tixe/middlewares/auth.go -rw-r--r-- 1.3 KiB
587179c2Jonni Liljamo fix: verify users existence in IsAuthenticated 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
53
54
55
56
57
58
/*
 * 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 {
			c.Redirect(http.StatusSeeOther, "/login")
			c.Abort()
			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.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()
	}
}