package auth
|
|
import (
|
"fmt"
|
"github.com/gin-gonic/gin"
|
"github.com/gomodule/redigo/redis"
|
"net/http"
|
"strings"
|
"shop-common/code"
|
"shop-common/util"
|
"shop-common/cache"
|
)
|
|
const (
|
TokenKey = "abc123456789"
|
)
|
|
type Auth interface {
|
Check(c *gin.Context)bool
|
Decode(token string) (bool,map[string]interface{})
|
User(c *gin.Context)map[string]interface{}
|
Login(http *http.Request,w http.ResponseWriter,user map[string]interface{}) (bool, string, string)
|
Logout(http *http.Request,w http.ResponseWriter) bool
|
RefreshToken(tokenStr string) (bool, string, string)
|
}
|
|
func GenerateAuthDriver() *Auth {
|
var authDriver Auth
|
authDriver = NewJwtAuthDriver()
|
return &authDriver
|
}
|
|
func SetOutUser(userId string) {
|
c := cache.Get()
|
defer c.Close()
|
r, err := c.Do("SET", userId, userId)
|
if err != nil {
|
fmt.Println("SetOutUser err:", err, "reply:", r)
|
}
|
}
|
|
func OutUser(userId string) bool {
|
c := cache.Get()
|
defer c.Close()
|
b, err := redis.Bool(c.Do("EXISTS", userId))
|
if err != nil {
|
fmt.Println("OutUser err:", err)
|
return false
|
}
|
return b
|
}
|
|
func RemoveOutUser(userId string) {
|
c := cache.Get()
|
defer c.Close()
|
reply, err := c.Do("DEL", userId)
|
if err != nil {
|
fmt.Println("removeOutUser err:", err, "reply:", reply)
|
}
|
}
|
|
func AuthHandler() gin.HandlerFunc {
|
return func(c *gin.Context) {
|
urlPath := c.Request.URL.Path
|
|
if strings.Contains(urlPath,"/data/api-") && !filterUrls(urlPath){
|
jwtDriver :=NewJwtAuthDriver()
|
if !jwtDriver.Check(c) {
|
util.ResponseFormat(c,code.TokenNotFound,"尚未登录,请登录")
|
c.Abort()
|
return
|
}
|
userM := (*jwtDriver).User(c)
|
if userM == nil {
|
util.ResponseFormat(c,code.TokenNotFound,"尚未登录,请登录")
|
c.Abort()
|
return
|
}
|
userId := userM["id"].(string)
|
if OutUser(userId) {
|
util.ResponseFormat(c,code.TokenNotFound,"尚未登录,请登录")
|
c.Abort()
|
return
|
}
|
c.Next()
|
} else {
|
c.Next()
|
}
|
}
|
}
|
|
func filterUrls(urlPath string) bool {
|
freeArr := []string{
|
"login",
|
"makeVerifyCode",
|
"/data/api-u/user/register",
|
"/data/api-v/license",
|
"/data/api-v/info/",
|
"/data/api-u/area/findAreaByParentId",
|
"/data/api-u/dic/findDicByType",
|
"/data/api-u/user/verifyCode",
|
}
|
b := false
|
for _,url := range freeArr {
|
if strings.Contains(urlPath, url) {
|
b = true
|
break
|
}
|
}
|
return b
|
}
|
|
|
func GetCurUser(c *gin.Context)map[string]interface{}{
|
return (*GenerateAuthDriver()).User(c)
|
}
|