| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package middleware
- import (
- "github.com/gin-contrib/sessions"
- "github.com/gin-gonic/gin"
- "message-pusher/common"
- "net/http"
- )
- func authHelper(c *gin.Context, minRole int) {
- session := sessions.Default(c)
- username := session.Get("username")
- role := session.Get("role")
- id := session.Get("id")
- status := session.Get("status")
- if username == nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无权进行此操作,未登录",
- })
- c.Abort()
- }
- if status.(int) == common.UserStatusDisabled {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "用户已被封禁",
- })
- c.Abort()
- return
- }
- if role.(int) < minRole {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无权进行此操作,权限不足",
- })
- c.Abort()
- return
- }
- c.Set("username", username)
- c.Set("role", role)
- c.Set("id", id)
- c.Next()
- }
- func UserAuth() func(c *gin.Context) {
- return func(c *gin.Context) {
- authHelper(c, common.RoleCommonUser)
- }
- }
- func AdminAuth() func(c *gin.Context) {
- return func(c *gin.Context) {
- authHelper(c, common.RoleAdminUser)
- }
- }
- func RootAuth() func(c *gin.Context) {
- return func(c *gin.Context) {
- authHelper(c, common.RoleRootUser)
- }
- }
|