-
Notifications
You must be signed in to change notification settings - Fork 216
/
middleware.auth.go
50 lines (44 loc) · 1.32 KB
/
middleware.auth.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
// middleware.auth.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
// This middleware ensures that a request will be aborted with an error
// if the user is not logged in
func ensureLoggedIn() gin.HandlerFunc {
return func(c *gin.Context) {
// If there's an error or if the token is empty
// the user is not logged in
loggedInInterface, _ := c.Get("is_logged_in")
loggedIn := loggedInInterface.(bool)
if !loggedIn {
//if token, err := c.Cookie("token"); err != nil || token == "" {
c.AbortWithStatus(http.StatusUnauthorized)
}
}
}
// This middleware ensures that a request will be aborted with an error
// if the user is already logged in
func ensureNotLoggedIn() gin.HandlerFunc {
return func(c *gin.Context) {
// If there's no error or if the token is not empty
// the user is already logged in
loggedInInterface, _ := c.Get("is_logged_in")
loggedIn := loggedInInterface.(bool)
if loggedIn {
// if token, err := c.Cookie("token"); err == nil || token != "" {
c.AbortWithStatus(http.StatusUnauthorized)
}
}
}
// This middleware sets whether the user is logged in or not
func setUserStatus() gin.HandlerFunc {
return func(c *gin.Context) {
if token, err := c.Cookie("token"); err == nil || token != "" {
c.Set("is_logged_in", true)
} else {
c.Set("is_logged_in", false)
}
}
}