DEVELOPMENT ENVIRONMENT

~liljamo/felu

ref: 4992844348f2ecabf096daf60a71f737a928683a felu/internal/middlewares/auth.go -rw-r--r-- 942 bytes
49928443Jonni Liljamo docs: update README.md 23 hours 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
/*
 * Copyright (C) 2024 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 (
	"net/http"

	"github.com/alexedwards/scs/v2"
	"github.com/gin-gonic/gin"
)

// SessionExists returns a gin middleware for checking if a session exists.
func SessionExists(sm *scs.SessionManager) gin.HandlerFunc {
	return func(c *gin.Context) {
		userID := sm.Get(c.Request.Context(), "user_id")
		if userID != nil {
			if c.Request.URL.Path == "/login" {
				c.Redirect(http.StatusTemporaryRedirect, "/manage")
				c.Abort()
			} else {
				// Set user_id in context, if needed later (e.g. AdminOnly middleware)
				c.Set("user_id", userID)
				// TODO: Validate in db?
				c.Next()
			}
		} else {
			if c.Request.URL.Path == "/login" {
				c.Next()
			} else {
				c.Redirect(http.StatusTemporaryRedirect, "/login")
				c.Abort()
			}
		}
	}
}