Auth.go 2.78 KB
package Auth

import (
	"github.com/aarongao/tools"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"letu/DB"
	"letu/Lib/JWT"
	"letu/Lib/LeYouTu"
	"letu/Lib/OperatorLog"
)

// 系统中所有模块
var Models = make(map[string][]string)

// @Title 所有模块信息
// @Description 模块管理 - 所有模块信息
// @Accept  json
// @Produce  json
// @Success 200 {object} tools.ResponseSeccess ""
// @Failure 500 {object} tools.ResponseError "{"errcode":1,"errmsg":"错误原因"}"
// @Router /AllModules? [get]
func Modules(c *gin.Context) {
	c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin"))
	c.Header("Access-Control-Allow-Credentials", "true")

	rs := []string{}
	for k, _ := range Models {
		rs = append(rs, k)
	}

	c.JSON(200, tools.ResponseSeccess{
		0,
		rs,
	})
}

// 检查基础权限
func CheckAuthFunc(handFunc func(c *gin.Context), auth *DB.SModel) func(c *gin.Context) {
	return func(c *gin.Context) {

		if auth.Model == "" {
			handFunc(c)
			return
		}

		token := ""
		if c.Request.Method == "GET" {
			token = c.Query("Token")
		}
		if c.Request.Method == "POST" {
			token = c.PostForm("Token")
		}
		if token == "" {
			token = c.Request.Header.Get("Token")
		}
		if token == "" {
			c.JSON(200, tools.ResponseError{
				1,
				"缺少Token",
			})
			return
		}

		// 解析token
		user, err := JWT.ParseToken(token)
		if user.UserType == "root" {
			c.Set("UserInfo", user)
			handFunc(c)
			return
		}

		// 检查权限
		checkAuth := false
		for _, v := range user.Auth {
			if v == auth.Model {
				checkAuth = true
				break
			}
		}

		if err != nil || checkAuth == false {
			c.JSON(200, tools.ResponseError{
				401,
				"没有权限",
			})
		} else {
			c.Set("UserInfo", user)

			handFunc(c)

			if auth.Model != "操作员日志"{
				go func() {
					ScenicId, _ := LeYouTu.GetScenicId(c)
					OperatorLog.CreateOperatorLog(ScenicId, user, auth, c.Request.RequestURI, c.Request.Form)
				}()
			}
		}
	}
}

func CheckScenicAuth(ScenicId string, user *DB.SMember) error {

	if ScenicId == "" {
		return errors.New("景区id不能为空")
	}

	_, err := primitive.ObjectIDFromHex(ScenicId)
	if err != nil {
		return errors.New("景区id格式不正确")
	}

	if user.UserType == "operator" {
		if user.ScenicId != ScenicId {
			return errors.New("权限不正确(需要正确的Token和ScenicId)")
		}
	}
	return nil
}

func CheckUserAuth(UserId string, user *DB.SMember) error {

	if UserId == "" {
		return errors.New("用户id不能为空")
	}

	_, err := primitive.ObjectIDFromHex(UserId)
	if err != nil {
		return errors.New("用户id格式不正确")
	}

	if user.UserType == "visitor" {
		if UserId != user.Id.Hex() {
			return errors.New("权限不正确(需要正确的Token和UserId)")
		}
	}

	return nil
}