fix: replace session handler with jwt authorization

This commit is contained in:
RockYang
2023-09-05 11:47:03 +08:00
parent a49fb1940e
commit 20a12462b1
21 changed files with 217 additions and 205 deletions

View File

@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/lionsoul2014/ip2region/binding/golang/xdb"
@@ -92,7 +93,7 @@ func IsEmptyValue(obj interface{}) bool {
if obj == nil {
return true
}
v := reflect.ValueOf(obj)
switch v.Kind() {
case reflect.Ptr, reflect.Interface:
@@ -113,3 +114,27 @@ func IsEmptyValue(obj interface{}) bool {
return reflect.DeepEqual(obj, reflect.Zero(reflect.TypeOf(obj)).Interface())
}
}
func BoolValue(str string) bool {
value, err := strconv.ParseBool(str)
if err != nil {
return false
}
return value
}
func FloatValue(str string) float64 {
value, err := strconv.ParseFloat(str, 64)
if err != nil {
return 0
}
return value
}
func IntValue(str string, defaultValue int) int {
value, err := strconv.Atoi(str)
if err != nil {
return defaultValue
}
return value
}

View File

@@ -27,6 +27,10 @@ func HACKER(c *gin.Context) {
c.JSON(http.StatusOK, types.BizVo{Code: types.Failed, Message: "Hacker attempt!!!"})
}
func NotAuth(c *gin.Context) {
c.JSON(http.StatusOK, types.BizVo{Code: types.NotAuthorized, Message: "Not Authorized"})
func NotAuth(c *gin.Context, messages ...string) {
if messages != nil {
c.JSON(http.StatusOK, types.BizVo{Code: types.NotAuthorized, Message: messages[0]})
} else {
c.JSON(http.StatusOK, types.BizVo{Code: types.NotAuthorized, Message: "Not Authorized"})
}
}

View File

@@ -5,33 +5,18 @@ import (
"chatplus/store/model"
"errors"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
func SetLoginUser(c *gin.Context, user model.User) error {
session := sessions.Default(c)
session.Set(types.SessionUser, user.Id)
// TODO: 后期用户数量增加,考虑将用户数据存储到 leveldb避免每次查询数据库
return session.Save()
}
func SetLoginAdmin(c *gin.Context, admin types.Manager) error {
session := sessions.Default(c)
session.Set(types.SessionAdmin, admin.Username)
return session.Save()
}
func GetLoginUser(c *gin.Context, db *gorm.DB) (model.User, error) {
value, exists := c.Get(types.LoginUserCache)
if exists {
return value.(model.User), nil
}
session := sessions.Default(c)
userId := session.Get(types.SessionUser)
if userId == nil {
userId, ok := c.Get(types.LoginUserID)
if !ok {
return model.User{}, errors.New("user not login")
}