-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
41 lines (36 loc) · 871 Bytes
/
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
package auth
import (
"net/http"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
const AUTH_KEY = "auth"
// AuthHandler store session into module
func AuthHandler(mod Module) gin.HandlerFunc {
return func(ctx *gin.Context) {
mod.UpdateSession(sessions.Default(ctx))
ctx.Set(AUTH_KEY, mod)
ctx.Next()
}
}
// UserRestricted is a middleware to restrict
// some route for authenticated user only
func UserRestricted() gin.HandlerFunc {
return func(ctx *gin.Context) {
var (
mod Module
ok bool
)
r := map[string]interface{}{
"message": "unauthorized",
}
if mod, ok = ctx.MustGet(AUTH_KEY).(Module); !ok {
ctx.JSON(http.StatusUnauthorized, r)
ctx.AbortWithStatus(http.StatusUnauthorized)
}
if !mod.IsAuthenticated() {
ctx.JSON(http.StatusUnauthorized, r)
ctx.AbortWithStatus(http.StatusUnauthorized)
}
}
}