-
Notifications
You must be signed in to change notification settings - Fork 93
/
auth.go
52 lines (44 loc) · 1.16 KB
/
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
51
52
package auth
import (
"github.com/gin-gonic/gin"
"morningo/filters/auth/drivers"
"net/http"
)
const (
JwtAuthDriverKey = "jwt"
CookieAuthDriverKey = "cookie"
)
var driverList = map[string]Auth{
CookieAuthDriverKey: drivers.NewCookieAuthDriver(),
JwtAuthDriverKey: drivers.NewJwtAuthDriver(),
}
type Auth interface {
Check(c *gin.Context) bool
User(c *gin.Context) interface{}
Login(http *http.Request, w http.ResponseWriter, user map[string]interface{}) interface{}
Logout(http *http.Request, w http.ResponseWriter) bool
}
func RegisterGlobalAuthDriver(authKey string, key string) gin.HandlerFunc {
return func(c *gin.Context) {
c.Set(key, GenerateAuthDriver(authKey))
c.Next()
}
}
func Middleware(authKey string) gin.HandlerFunc {
return func(c *gin.Context) {
if !GenerateAuthDriver(authKey).Check(c) {
c.HTML(http.StatusOK, "index.tpl", gin.H{
"title": "login first",
})
c.Abort()
}
c.Next()
}
}
func GenerateAuthDriver(string string) Auth {
return driverList[string]
}
func GetCurUser(c *gin.Context, key string) map[string]interface{} {
authDriver, _ := c.MustGet(key).(Auth)
return authDriver.User(c).(map[string]interface{})
}