-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
56 lines (48 loc) · 1.48 KB
/
middleware.go
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
package auth
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
"net/http"
)
// GetUserMiddleware returns gin handler function that reads user data from session store and saves it as context item.
// Note that this middleware does not prevent not logged in users from using the app.
func GetUserMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
userId, err := RetrieveUserFromSession(c)
if err != nil {
log.Debugf("Failed to retrieve user from session. Possibly just not logged in: %v", err)
return
}
c.Set("userId", userId)
c.Next()
}
}
// GetLoginRequiredMiddleware will return 401 Unauthorised when the user is not logged in.
// Note that this middleware must be registered after the GetUserMiddleware.
func GetLoginRequiredMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
if !IsLoggedIn(c) {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Next()
}
}
// IsLoggedIn returns true if the user is logged in to the application.
// Use GetUserId to retrieve the ID of the currently logged in user.
func IsLoggedIn(c *gin.Context) bool {
_, exists := c.Get("userId")
return exists
}
// GetUserId returns the id of the user currently logged in.
// It will return uuid.Nil if no user is logged in.
//
// Use IsLoggedIn first to check if the user is logged in.
func GetUserId(c *gin.Context) uuid.UUID {
value, exists := c.Get("userId")
if !exists {
return uuid.Nil
}
return value.(uuid.UUID)
}