mirror of
https://github.com/xinliangnote/go-gin-api.git
synced 2024-04-21 12:31:46 +00:00
- 将 middleware 命名为 interceptor - 将 deploy 命名为 deployments - 移除 pkg/errno - 使用 proposal 目录 - 优化代码
57 lines
1.5 KiB
Go
57 lines
1.5 KiB
Go
package interceptor
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/xinliangnote/go-gin-api/configs"
|
|
"github.com/xinliangnote/go-gin-api/internal/code"
|
|
"github.com/xinliangnote/go-gin-api/internal/pkg/core"
|
|
"github.com/xinliangnote/go-gin-api/internal/proposal"
|
|
"github.com/xinliangnote/go-gin-api/internal/repository/redis"
|
|
"github.com/xinliangnote/go-gin-api/pkg/errors"
|
|
)
|
|
|
|
func (i *interceptor) CheckLogin(ctx core.Context) (sessionUserInfo proposal.SessionUserInfo, err core.BusinessError) {
|
|
token := ctx.GetHeader(configs.HeaderLoginToken)
|
|
if token == "" {
|
|
err = core.Error(
|
|
http.StatusUnauthorized,
|
|
code.AuthorizationError,
|
|
code.Text(code.AuthorizationError)).WithError(errors.New("Header 中缺少 Token 参数"))
|
|
|
|
return
|
|
}
|
|
|
|
if !i.cache.Exists(configs.RedisKeyPrefixLoginUser + token) {
|
|
err = core.Error(
|
|
http.StatusUnauthorized,
|
|
code.AuthorizationError,
|
|
code.Text(code.AuthorizationError)).WithError(errors.New("请先登录"))
|
|
|
|
return
|
|
}
|
|
|
|
cacheData, cacheErr := i.cache.Get(configs.RedisKeyPrefixLoginUser+token, redis.WithTrace(ctx.Trace()))
|
|
if cacheErr != nil {
|
|
err = core.Error(
|
|
http.StatusUnauthorized,
|
|
code.AuthorizationError,
|
|
code.Text(code.AuthorizationError)).WithError(cacheErr)
|
|
|
|
return
|
|
}
|
|
|
|
jsonErr := json.Unmarshal([]byte(cacheData), &sessionUserInfo)
|
|
if jsonErr != nil {
|
|
core.Error(
|
|
http.StatusUnauthorized,
|
|
code.AuthorizationError,
|
|
code.Text(code.AuthorizationError)).WithError(jsonErr)
|
|
|
|
return
|
|
}
|
|
|
|
return
|
|
}
|