Files
go-gin-api/internal/router/interceptor/check_login.go
T
新亮 4c37a7e6b5 feature(1.2.8): swagger 接口文档新增 Security
- 将 middleware 命名为 interceptor
- 将 deploy 命名为 deployments
- 移除 pkg/errno
- 使用 proposal 目录
- 优化代码
2021-11-28 13:25:27 +08:00

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
}