Files
easygoadmin/app/middleware/checklogin.go
yaoyilin 1b36bd8fbe feat: 初始化项目
初始化项目
2022-10-31 22:29:16 +08:00

196 lines
5.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 登录验证中间件
* @author
* @since 2021/8/20
* @File : checkauth
*/
package middleware
import (
"easygoadmin/app/model"
"easygoadmin/utils"
"easygoadmin/utils/common"
"easygoadmin/utils/gconv"
"encoding/json"
"fmt"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"net/http"
"regexp"
"strings"
"time"
)
func CheckLogin() gin.HandlerFunc {
return func(c *gin.Context) {
//fmt.Println("登录验证中间件")
// 放行设置
path := c.Request.URL.Path
urlItem := []string{"/captcha", "/login", "/loginKf", "/"}
urlCusItem := []string{"/customer", "/loginKf"}
if !utils.InStringArray(path, urlItem) && !strings.Contains(path, "resource") {
if !strings.Contains(path, "api") {
if !utils.IsLogin(c) {
// 跳转登录页,方式301(永久移动),308(永久重定向),307(临时重定向)
if utils.InStringArray(path, urlCusItem) {
c.Redirect(http.StatusTemporaryRedirect, "/loginKf")
return
}
c.Redirect(http.StatusTemporaryRedirect, "/login")
return
}
}
}
// 前置中间件
c.Next()
}
}
// 验证权限
func CheckAuth() gin.HandlerFunc {
return func(c *gin.Context) {
//fmt.Println("登录验证中间件")
// 放行设置
urlItem := []string{"/captcha", "/login", "/loginKf", "/"}
path := c.Request.URL.Path
match, _ := regexp.Match("/[1-9]\\d*", []byte(path))
if !utils.InStringArray(c.Request.URL.Path, urlItem) && !strings.Contains(c.Request.URL.Path, "resource") {
if !strings.Contains(c.Request.URL.Path, "api") && !match {
// 初始化session对象
session := sessions.Default(c)
userId := session.Get("userId")
if userId != 1 && !strings.Contains(path, "edit") {
menuIdArr := getRoleApiIds(c, gconv.Int64(userId))
if len(menuIdArr) == 0 {
c.JSON(http.StatusOK, common.JsonResult{
Code: -1,
Msg: "无权限",
})
c.Abort()
}
menuId := getMenuId(c, path)
if menuId != "" {
if !utils.InStringArray(menuId, menuIdArr) {
c.JSON(http.StatusOK, common.JsonResult{
Code: -1,
Msg: "无权限!",
})
c.Abort()
}
}
}
}
}
// 前置中间件
c.Next()
}
}
// 跨域
func DoCors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin")
var headerKeys []string
for k, _ := range c.Request.Header {
headerKeys = append(headerKeys, k)
}
headerStr := strings.Join(headerKeys, ", ")
if headerStr != "" {
headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers,AppToken, %s", headerStr)
} else {
headerStr = "access-control-allow-origin, access-control-allow-headers,AppToken"
}
if origin != "" {
//-_-~
// c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Origin", origin)
//c.Header("Access-Control-Allow-Headers", headerStr)
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
// c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
c.Header("Access-Control-Max-Age", "172800")
c.Header("Access-Control-Allow-Credentials", "true")
c.Set("content-type", "application/json")
}
//放行所有OPTIONS方法
if method == "OPTIONS" {
c.JSON(http.StatusOK, "Options Request!")
//c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}
// 根据userId 获取有权限的menuId
func getRoleApiIds(c *gin.Context, userId int64) []string {
apiIdsArr := make([]string, 0)
cache := utils.GetRedisHelper()
cacheKey := fmt.Sprintf("Middleware:GetRoleApiIds:V1:%d", userId)
val := cache.Get(c, cacheKey).Val()
if val != "" {
json.Unmarshal([]byte(val), &apiIdsArr)
return apiIdsArr
}
userRole := make([]model.UserRole, 0)
// 创建查询实例
query := utils.XormDb.Where("user_id = ?", gconv.String(userId)).Table("sys_user_role")
err := query.Find(&userRole)
if err != nil {
return apiIdsArr
}
roleArr := make([]string, 0)
for _, item := range userRole {
roleArr = append(roleArr, gconv.String(item.RoleId))
}
if len(roleArr) > 0 {
//roleMenuArr := make([]int, 0)
roleStr := strings.Join(roleArr, ",")
whereId := fmt.Sprintf("role_id IN (%s)", roleStr)
roleMenu := make([]model.RoleMenu, 0)
errR := utils.XormDb.Where(whereId).Find(&roleMenu)
if errR == nil {
for _, item := range roleMenu {
apiIdsArr = append(apiIdsArr, gconv.String(item.MenuId))
}
}
}
jsonStr, _ := json.Marshal(apiIdsArr)
cache.Set(c, cacheKey, jsonStr, 2*time.Minute)
return apiIdsArr
}
// 根据userId 获取有权限的menuId
func getMenuId(c *gin.Context, path string) string {
menuId := ""
cache := utils.GetRedisHelper()
cacheKey := fmt.Sprintf("Middleware:GetMenuId:V3:%s", path)
val := cache.Get(c, cacheKey).Val()
if val != "" {
return val
}
var menu model.Menu
// 创建查询实例
query := utils.XormDb.Where("url = ?", path).Select("id").
Table("sys_menu")
_, err := query.Get(&menu)
if err != nil || menu.Id == 0 {
return menuId
}
menuId = gconv.String(menu.Id)
cache.Set(c, cacheKey, menuId, 2*time.Minute)
return menuId
}