@@ -0,0 +1,290 @@
|
||||
package authser
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/useragent"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
registerPath = "/api/app/auth/register"
|
||||
loginPath = "/api/app/auth/login"
|
||||
resetPath = "/api/app/auth/resetPassword"
|
||||
guestPath = "/api/app/auth/guest"
|
||||
getInfoPath = "/api/app/auth/getInfo"
|
||||
profilePath = "/api/app/auth/profile"
|
||||
uploadPath = "/api/app/upload/image"
|
||||
cookieMaxAge = 7 * 24 * 3600
|
||||
)
|
||||
|
||||
// Register 调用上游注册接口。
|
||||
func Register(c *gin.Context, req RegisterReq) (*APIEnvelope, *LoginResp, error) {
|
||||
var env APIEnvelope
|
||||
if _, err := upstream.PostJSON(c, registerPath, req, &env); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return &env, nil, nil
|
||||
}
|
||||
user, err := decodeLoginData(env.Data)
|
||||
if err != nil {
|
||||
return &env, nil, err
|
||||
}
|
||||
return &env, user, nil
|
||||
}
|
||||
|
||||
// ResetPassword 通过账号和邮箱校验后重置密码。
|
||||
func ResetPassword(c *gin.Context, req ResetPasswordReq) (*APIEnvelope, error) {
|
||||
var env APIEnvelope
|
||||
if _, err := upstream.PostJSON(c, resetPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// Login 调用上游登录接口。
|
||||
func Login(c *gin.Context, req LoginReq) (*APIEnvelope, *LoginResp, error) {
|
||||
var env APIEnvelope
|
||||
if _, err := upstream.PostJSON(c, loginPath, req, &env); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return &env, nil, nil
|
||||
}
|
||||
user, err := decodeLoginData(env.Data)
|
||||
if err != nil {
|
||||
return &env, nil, err
|
||||
}
|
||||
return &env, user, nil
|
||||
}
|
||||
|
||||
// GuestLogin 调用上游游客登录(按设备 ID 创建或找回游客账号)。
|
||||
func GuestLogin(c *gin.Context, req GuestLoginReq) (*APIEnvelope, *LoginResp, error) {
|
||||
var env APIEnvelope
|
||||
if _, err := upstream.PostJSON(c, guestPath, req, &env); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return &env, nil, nil
|
||||
}
|
||||
user, err := decodeLoginData(env.Data)
|
||||
if err != nil {
|
||||
return &env, nil, err
|
||||
}
|
||||
return &env, user, nil
|
||||
}
|
||||
|
||||
// GetInfo 通过 token 拉取最新用户信息。
|
||||
func GetInfo(c *gin.Context) (*APIEnvelope, *LoginResp, error) {
|
||||
var env APIEnvelope
|
||||
if err := upstream.GetJSON(c, getInfoPath, &env); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return &env, nil, nil
|
||||
}
|
||||
user, err := decodeLoginData(env.Data)
|
||||
if err != nil {
|
||||
return &env, nil, err
|
||||
}
|
||||
return &env, user, nil
|
||||
}
|
||||
|
||||
// UpdateProfile 修改资料(昵称 / 头像等)。
|
||||
func UpdateProfile(c *gin.Context, req UpdateProfileReq) (*APIEnvelope, error) {
|
||||
var env APIEnvelope
|
||||
if _, err := upstream.PostJSON(c, profilePath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// UploadImage 上传图片;头像场景不加水印。
|
||||
func UploadImage(c *gin.Context, fileName string, r io.Reader) (*ImageUploadResp, error) {
|
||||
var resp ImageUploadResp
|
||||
_, err := upstream.PostMultipart(c, uploadPath, map[string]string{
|
||||
"watermark": "0",
|
||||
}, &upstream.MultipartFile{
|
||||
FieldName: "file",
|
||||
FileName: fileName,
|
||||
Reader: r,
|
||||
}, &resp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
func decodeLoginData(raw json.RawMessage) (*LoginResp, error) {
|
||||
if len(raw) == 0 || string(raw) == "null" || string(raw) == `""` {
|
||||
return nil, fmt.Errorf("empty login data")
|
||||
}
|
||||
var user LoginResp
|
||||
if err := json.Unmarshal(raw, &user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// SetAuthCookies 只持久化 SSR 与前端登录态实际依赖的字段。
|
||||
// 个人简介、邮箱、邀请码、展示卡信息由 getInfo 即时提供,不再随每个页面响应重复写入;
|
||||
// sid 已存在于请求时也无需原样回写。ClearAuthCookies 仍保留这些历史键用于兼容清理。
|
||||
func SetAuthCookies(c *gin.Context, user *LoginResp) {
|
||||
if c == nil || user == nil {
|
||||
return
|
||||
}
|
||||
secure := c.Request != nil && c.Request.TLS != nil
|
||||
if strings.TrimSpace(user.Token) != "" {
|
||||
setCookie(c, "token", user.Token, secure)
|
||||
}
|
||||
setCookie(c, "userId", strconv.FormatInt(user.UserID, 10), secure)
|
||||
setCookie(c, "accountNo", user.AccountNo, secure)
|
||||
setCookie(c, "nickName", user.NickName, secure)
|
||||
setCookie(c, "avatar", user.Avatar, secure)
|
||||
setCookie(c, "recharge", strconv.FormatInt(user.Recharge, 10), secure)
|
||||
setCookie(c, "vipType", strconv.Itoa(user.VipType), secure)
|
||||
setCookie(c, "currentVipExpire", user.CurrentVipExpire, secure)
|
||||
setCookie(c, "userType", strconv.Itoa(user.Type), secure)
|
||||
isReg := "0"
|
||||
if user.IsRegister || user.Type == 1 {
|
||||
isReg = "1"
|
||||
}
|
||||
setCookie(c, "isRegister", isReg, secure)
|
||||
// 后续 SSR 服务必须能立即读取本次刚建立/刷新的会话;同时记录为本请求的
|
||||
// 权威结果,避免 HTML 渲染阶段再次调用 getInfo 并重复写整套 Cookie。
|
||||
patchAuthCookiesToRequest(c, user)
|
||||
rememberRequestAuthUser(c, user)
|
||||
}
|
||||
|
||||
func setCookie(c *gin.Context, name, value string, secure bool) {
|
||||
// Cookie Value 仅允许 ASCII;中文昵称等需 URL 编码。
|
||||
// 使用 PathEscape(空格→%20),与前端 encodeURIComponent 一致;
|
||||
// 避免 QueryEscape 的空格→+,否则 JS decodeURIComponent 会留下字面量 "+"。
|
||||
writeCookie(c, &http.Cookie{
|
||||
Name: name,
|
||||
Value: url.PathEscape(value),
|
||||
Path: "/",
|
||||
MaxAge: cookieMaxAge,
|
||||
HttpOnly: false,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Expires: time.Now().Add(7 * 24 * time.Hour),
|
||||
})
|
||||
}
|
||||
|
||||
// writeCookie 对同一响应中同名、同 Path、同 Domain 的 Cookie 做 upsert,避免会话恢复的
|
||||
// 「先清除、再重建」产生两套响应头,同时保留其他作用域下可能存在的同名 Cookie。
|
||||
func writeCookie(c *gin.Context, cookie *http.Cookie) {
|
||||
if c == nil || c.Writer == nil || cookie == nil || cookie.Name == "" {
|
||||
return
|
||||
}
|
||||
header := c.Writer.Header()
|
||||
existing := header.Values("Set-Cookie")
|
||||
if len(existing) > 0 {
|
||||
header.Del("Set-Cookie")
|
||||
for _, raw := range existing {
|
||||
if sameCookieScope(raw, cookie) {
|
||||
continue
|
||||
}
|
||||
header.Add("Set-Cookie", raw)
|
||||
}
|
||||
}
|
||||
http.SetCookie(c.Writer, cookie)
|
||||
}
|
||||
|
||||
func sameCookieScope(raw string, target *http.Cookie) bool {
|
||||
response := &http.Response{Header: http.Header{"Set-Cookie": []string{raw}}}
|
||||
for _, existing := range response.Cookies() {
|
||||
if existing.Name == target.Name && existing.Path == target.Path && strings.EqualFold(existing.Domain, target.Domain) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func cookieValue(c *gin.Context, name string) string {
|
||||
ck, err := c.Request.Cookie(name)
|
||||
if err != nil || ck == nil {
|
||||
return ""
|
||||
}
|
||||
raw := strings.TrimSpace(ck.Value)
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
// QueryUnescape 同时兼容历史 QueryEscape(+)与 PathEscape(%20)
|
||||
if decoded, err := url.QueryUnescape(raw); err == nil {
|
||||
return strings.TrimSpace(decoded)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
// ClearAuthCookies 清除登录相关 cookie。
|
||||
func ClearAuthCookies(c *gin.Context) {
|
||||
forgetRequestAuthUser(c)
|
||||
for _, name := range authCookieNames() {
|
||||
writeCookie(c, &http.Cookie{
|
||||
Name: name,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: false,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func authCookieNames() []string {
|
||||
return []string{
|
||||
"token", "_token_", "sid", "_s_token_",
|
||||
"userId", "accountNo", "nickName", "introduction", "avatar",
|
||||
"email", "inviteCode", "recharge", "vipType", "currentVipExpire", "showCardId", "showCardName",
|
||||
"userType", "isRegister",
|
||||
}
|
||||
}
|
||||
|
||||
// AuthFromCookies 从 cookie 读取登录态,供 SSR 头部 / 个人中心展示。
|
||||
func AuthFromCookies(c *gin.Context) (loggedIn bool, userName, avatar, email string) {
|
||||
token := useragent.TokenFromRequest(c.Request)
|
||||
if token == "" {
|
||||
return false, "", "", ""
|
||||
}
|
||||
userName = cookieValue(c, "nickName")
|
||||
if userName == "" {
|
||||
userName = cookieValue(c, "accountNo")
|
||||
}
|
||||
avatar = usableAvatarURL(cookieValue(c, "avatar"))
|
||||
email = cookieValue(c, "email")
|
||||
return true, userName, avatar, email
|
||||
}
|
||||
|
||||
// IsRegisteredFromCookies 是否正式注册账号(非游客)。
|
||||
func IsRegisteredFromCookies(c *gin.Context) bool {
|
||||
if useragent.TokenFromRequest(c.Request) == "" {
|
||||
return false
|
||||
}
|
||||
if cookieValue(c, "isRegister") == "1" {
|
||||
return true
|
||||
}
|
||||
return cookieValue(c, "userType") == "1"
|
||||
}
|
||||
|
||||
func usableAvatarURL(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
if strings.HasPrefix(raw, "http://") || strings.HasPrefix(raw, "https://") || strings.HasPrefix(raw, "/static/") {
|
||||
return raw
|
||||
}
|
||||
// 无域名的相对路径暂不可用(解密拉取需要完整 URL)
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
package authser
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"videoweb/pub/common/log"
|
||||
"videoweb/pub/common/useragent"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const guestDevIDCookie = "guest_dev_id"
|
||||
const guestSkipAutoCookie = "guest_skip_auto"
|
||||
|
||||
// EnsureGuestOnEnter 页面进入时:无 token(未自己登录)则走游客登录并写 cookie。
|
||||
// 对应上游 POST /api/app/auth/guest。成功后会把会话补进当前 Request,便于同一次 SSR 读到登录态。
|
||||
// 手动退出后带 guest_skip_auto 时跳过本次;清掉标记后,下次进页再自动游客。
|
||||
func EnsureGuestOnEnter(c *gin.Context) *LoginResp {
|
||||
if c == nil || c.Request == nil {
|
||||
return nil
|
||||
}
|
||||
if user := freshRequestAuthUser(c); user != nil {
|
||||
return user
|
||||
}
|
||||
if requestAutoAuthSuppressed(c) {
|
||||
return nil
|
||||
}
|
||||
// 已有任意会话(游客或正式账号)则跳过
|
||||
if useragent.TokenFromRequest(c.Request) != "" {
|
||||
return nil
|
||||
}
|
||||
// 手动退出:本次进页不自动游客,并清除标记,供下次进页恢复
|
||||
if IsGuestSkipAuto(c) {
|
||||
ClearGuestSkipAuto(c)
|
||||
dropRequestCookie(c, guestSkipAutoCookie)
|
||||
suppressRequestAutoAuth(c)
|
||||
return nil
|
||||
}
|
||||
|
||||
devID := ensureGuestDevID(c)
|
||||
env, user, err := GuestLogin(c, GuestLoginReq{
|
||||
DevID: devID,
|
||||
DeviceID: devID,
|
||||
Channel: guestChannel(c),
|
||||
})
|
||||
if err != nil {
|
||||
log.Error("ensure guest on enter failed", log.E(err))
|
||||
return nil
|
||||
}
|
||||
if env == nil || env.Code != 200 || user == nil || strings.TrimSpace(user.Token) == "" {
|
||||
tip := ""
|
||||
if env != nil {
|
||||
tip = firstNonEmptyTip(env.Tip, env.Msg)
|
||||
}
|
||||
log.Error("ensure guest on enter rejected", log.E(fmt.Errorf("code=%v tip=%s", envCode(env), tip)))
|
||||
return nil
|
||||
}
|
||||
|
||||
SetAuthCookies(c, user)
|
||||
return user
|
||||
}
|
||||
|
||||
// SyncUserOnEnter 是 SSR 页面统一的会话同步入口。同一请求已经通过游客登录、
|
||||
// getInfo 或其他认证流程取得过最新用户时直接复用,避免再次访问上游和重复写 Cookie。
|
||||
func SyncUserOnEnter(c *gin.Context) *LoginResp {
|
||||
if c == nil || c.Request == nil {
|
||||
return nil
|
||||
}
|
||||
if user := freshRequestAuthUser(c); user != nil {
|
||||
return user
|
||||
}
|
||||
if requestAutoAuthSuppressed(c) {
|
||||
return nil
|
||||
}
|
||||
if useragent.TokenFromRequest(c.Request) == "" {
|
||||
return EnsureGuestOnEnter(c)
|
||||
}
|
||||
return RefreshUserOnEnter(c)
|
||||
}
|
||||
|
||||
// RefreshUserOnEnter 页面进入时用 GET /api/app/auth/getInfo 刷新用户信息并写回 cookie。
|
||||
// 保证刷新后头部昵称、头像、金币等与上游一致(如解锁后余额变化)。
|
||||
func RefreshUserOnEnter(c *gin.Context) *LoginResp {
|
||||
if c == nil || c.Request == nil {
|
||||
return nil
|
||||
}
|
||||
if user := freshRequestAuthUser(c); user != nil {
|
||||
return user
|
||||
}
|
||||
if requestAutoAuthSuppressed(c) {
|
||||
return nil
|
||||
}
|
||||
token := useragent.TokenFromRequest(c.Request)
|
||||
if token == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
env, user, err := GetInfo(c)
|
||||
if err != nil {
|
||||
log.Error("refresh user on enter failed", log.E(err))
|
||||
return nil
|
||||
}
|
||||
if env != nil && IsSessionExpiredCode(env.Code) {
|
||||
if retry, _ := OnSessionExpired(c, env.Code); retry {
|
||||
// 游客重建已经返回完整用户并写好 Cookie,无需立刻再 getInfo 一次。
|
||||
if fresh := freshRequestAuthUser(c); fresh != nil {
|
||||
return fresh
|
||||
}
|
||||
env, user, err = GetInfo(c)
|
||||
if err != nil {
|
||||
log.Error("refresh user on enter retry failed", log.E(err))
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if env == nil || env.Code != 200 || user == nil {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(user.Token) == "" {
|
||||
user.Token = useragent.TokenFromRequest(c.Request)
|
||||
if user.Token == "" {
|
||||
user.Token = token
|
||||
}
|
||||
}
|
||||
SetAuthCookies(c, user)
|
||||
return user
|
||||
}
|
||||
|
||||
// RefreshGuestSession 游客会话失效时(如上游 6001 用户不存在)重新游客登录。
|
||||
// 正式注册账号不处理,避免把用户踢成游客。
|
||||
func RefreshGuestSession(c *gin.Context) *LoginResp {
|
||||
if c == nil || c.Request == nil {
|
||||
return nil
|
||||
}
|
||||
if IsRegisteredFromCookies(c) {
|
||||
return nil
|
||||
}
|
||||
forgetRequestAuthUser(c)
|
||||
dropRequestCookie(c, "token")
|
||||
dropRequestCookie(c, "_token_")
|
||||
return EnsureGuestOnEnter(c)
|
||||
}
|
||||
|
||||
func dropRequestCookie(c *gin.Context, name string) {
|
||||
if c == nil || c.Request == nil || name == "" {
|
||||
return
|
||||
}
|
||||
var parts []string
|
||||
for _, ck := range c.Request.Cookies() {
|
||||
if ck == nil || ck.Name == name {
|
||||
continue
|
||||
}
|
||||
parts = append(parts, ck.Name+"="+ck.Value)
|
||||
}
|
||||
c.Request.Header.Set("Cookie", strings.Join(parts, "; "))
|
||||
}
|
||||
|
||||
// MarkGuestSkipAuto 手动退出后标记:跳过紧接着的一次自动游客登录。
|
||||
func MarkGuestSkipAuto(c *gin.Context) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
suppressRequestAutoAuth(c)
|
||||
secure := c.Request != nil && c.Request.TLS != nil
|
||||
writeCookie(c, &http.Cookie{
|
||||
Name: guestSkipAutoCookie,
|
||||
Value: "1",
|
||||
Path: "/",
|
||||
MaxAge: 0, // session cookie
|
||||
HttpOnly: false,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
}
|
||||
|
||||
// IsGuestSkipAuto 是否处于「手动退出后跳过自动游客」状态。
|
||||
func IsGuestSkipAuto(c *gin.Context) bool {
|
||||
return cookieValue(c, guestSkipAutoCookie) == "1"
|
||||
}
|
||||
|
||||
// ClearGuestSkipAuto 清除手动退出跳过标记。
|
||||
func ClearGuestSkipAuto(c *gin.Context) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
writeCookie(c, &http.Cookie{
|
||||
Name: guestSkipAutoCookie,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: false,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
}
|
||||
|
||||
func ensureGuestDevID(c *gin.Context) string {
|
||||
if id := cookieValue(c, guestDevIDCookie); id != "" {
|
||||
return id
|
||||
}
|
||||
id := newGuestDevID()
|
||||
secure := c.Request != nil && c.Request.TLS != nil
|
||||
setCookie(c, guestDevIDCookie, id, secure)
|
||||
patchRequestCookie(c, guestDevIDCookie, id)
|
||||
return id
|
||||
}
|
||||
|
||||
func newGuestDevID() string {
|
||||
b := make([]byte, 8)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
now := time.Now()
|
||||
return fmt.Sprintf("%016X%d", uint64(now.UnixNano()), now.UnixMilli())
|
||||
}
|
||||
return strings.ToUpper(hex.EncodeToString(b)) + strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
}
|
||||
|
||||
// ResolveChannel 统一解析渠道码并按首次归因落盘。
|
||||
// 优先级:已有 channel cookie > 调用方传入值 > dc/ch/pc 查询参数;已有渠道不覆盖。
|
||||
func ResolveChannel(c *gin.Context, candidate string) string {
|
||||
channel := strings.TrimSpace(candidate)
|
||||
if c == nil || c.Request == nil {
|
||||
return channel
|
||||
}
|
||||
if stored := cookieValue(c, "channel"); stored != "" {
|
||||
return stored
|
||||
}
|
||||
if channel == "" {
|
||||
for _, key := range []string{"dc", "ch", "pc"} {
|
||||
if value := strings.TrimSpace(c.Query(key)); value != "" {
|
||||
channel = value
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if channel == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
secure := c.Request.TLS != nil
|
||||
setCookie(c, "channel", channel, secure)
|
||||
patchRequestCookie(c, "channel", channel)
|
||||
return channel
|
||||
}
|
||||
|
||||
// guestChannel 为首屏服务端自动游客登录补渠道;cookie 用于复用前端首次归因结果。
|
||||
func guestChannel(c *gin.Context) string {
|
||||
return ResolveChannel(c, "")
|
||||
}
|
||||
|
||||
func patchAuthCookiesToRequest(c *gin.Context, user *LoginResp) {
|
||||
if c == nil || user == nil {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(user.Token) != "" {
|
||||
patchRequestCookie(c, "token", user.Token)
|
||||
}
|
||||
patchRequestCookie(c, "userId", strconv.FormatInt(user.UserID, 10))
|
||||
patchRequestCookie(c, "accountNo", user.AccountNo)
|
||||
patchRequestCookie(c, "nickName", user.NickName)
|
||||
patchRequestCookie(c, "introduction", user.Introduction)
|
||||
patchRequestCookie(c, "avatar", user.Avatar)
|
||||
patchRequestCookie(c, "email", user.Email)
|
||||
patchRequestCookie(c, "inviteCode", user.InviteCode)
|
||||
patchRequestCookie(c, "recharge", strconv.FormatInt(user.Recharge, 10))
|
||||
patchRequestCookie(c, "vipType", strconv.Itoa(user.VipType))
|
||||
patchRequestCookie(c, "currentVipExpire", user.CurrentVipExpire)
|
||||
patchRequestCookie(c, "showCardId", strconv.FormatInt(user.ShowCardID, 10))
|
||||
patchRequestCookie(c, "showCardName", user.ShowCardName)
|
||||
patchRequestCookie(c, "userType", strconv.Itoa(user.Type))
|
||||
isReg := "0"
|
||||
if user.IsRegister || user.Type == 1 {
|
||||
isReg = "1"
|
||||
}
|
||||
patchRequestCookie(c, "isRegister", isReg)
|
||||
}
|
||||
|
||||
func patchRequestCookie(c *gin.Context, name, value string) {
|
||||
if c == nil || c.Request == nil || name == "" {
|
||||
return
|
||||
}
|
||||
escaped := url.PathEscape(value)
|
||||
var parts []string
|
||||
for _, ck := range c.Request.Cookies() {
|
||||
if ck == nil || ck.Name == name {
|
||||
continue
|
||||
}
|
||||
parts = append(parts, ck.Name+"="+ck.Value)
|
||||
}
|
||||
parts = append(parts, name+"="+escaped)
|
||||
c.Request.Header.Set("Cookie", strings.Join(parts, "; "))
|
||||
}
|
||||
|
||||
func envCode(env *APIEnvelope) int {
|
||||
if env == nil {
|
||||
return 0
|
||||
}
|
||||
return env.Code
|
||||
}
|
||||
|
||||
func firstNonEmptyTip(values ...string) string {
|
||||
for _, v := range values {
|
||||
if strings.TrimSpace(v) != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
package authser
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"videoweb/app/appg"
|
||||
"videoweb/pub/common/useragent"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var authCookieNamesWritten = []string{
|
||||
"token",
|
||||
"userId",
|
||||
"accountNo",
|
||||
"nickName",
|
||||
"avatar",
|
||||
"recharge",
|
||||
"vipType",
|
||||
"currentVipExpire",
|
||||
"userType",
|
||||
"isRegister",
|
||||
}
|
||||
|
||||
func TestSyncUserOnEnterCreatesGuestWithoutRefreshingIt(t *testing.T) {
|
||||
var guestCalls atomic.Int32
|
||||
var getInfoCalls atomic.Int32
|
||||
|
||||
useAuthTestUpstream(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case guestPath:
|
||||
guestCalls.Add(1)
|
||||
if r.Method != http.MethodPost {
|
||||
t.Errorf("guest method = %s, want POST", r.Method)
|
||||
}
|
||||
var request GuestLoginReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Errorf("decode guest request: %v", err)
|
||||
}
|
||||
if request.DevID == "" || request.DeviceID != request.DevID {
|
||||
t.Errorf("guest device ids = %#v, want matching non-empty ids", request)
|
||||
}
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("guest-token", "new-guest"))
|
||||
case getInfoPath:
|
||||
getInfoCalls.Add(1)
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("guest-token", "unexpected-refresh"))
|
||||
default:
|
||||
t.Errorf("unexpected upstream request: %s %s", r.Method, r.URL.Path)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
|
||||
c, recorder := newAuthTestContext()
|
||||
user := SyncUserOnEnter(c)
|
||||
|
||||
if user == nil || user.Token != "guest-token" {
|
||||
t.Fatalf("SyncUserOnEnter user = %#v, want guest-token", user)
|
||||
}
|
||||
if got := guestCalls.Load(); got != 1 {
|
||||
t.Errorf("guest calls = %d, want 1", got)
|
||||
}
|
||||
if got := getInfoCalls.Load(); got != 0 {
|
||||
t.Errorf("getInfo calls = %d, want 0", got)
|
||||
}
|
||||
assertRequestToken(t, c, "guest-token")
|
||||
assertSingleAuthCookieSet(t, recorder)
|
||||
}
|
||||
|
||||
func TestSyncUserOnEnterRefreshesExistingTokenOnlyOnce(t *testing.T) {
|
||||
var guestCalls atomic.Int32
|
||||
var getInfoCalls atomic.Int32
|
||||
authorization := make(chan string, 1)
|
||||
|
||||
useAuthTestUpstream(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case guestPath:
|
||||
guestCalls.Add(1)
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("unexpected-guest-token", "unexpected-guest"))
|
||||
case getInfoPath:
|
||||
getInfoCalls.Add(1)
|
||||
select {
|
||||
case authorization <- r.Header.Get("Authorization"):
|
||||
default:
|
||||
}
|
||||
// getInfo may omit token; the existing request token must be preserved.
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("", "fresh-user"))
|
||||
default:
|
||||
t.Errorf("unexpected upstream request: %s %s", r.Method, r.URL.Path)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
|
||||
c, recorder := newAuthTestContext(
|
||||
&http.Cookie{Name: "token", Value: "existing-token"},
|
||||
&http.Cookie{Name: "sid", Value: "existing-sid"},
|
||||
)
|
||||
first := SyncUserOnEnter(c)
|
||||
second := SyncUserOnEnter(c)
|
||||
|
||||
if first == nil || first.Token != "existing-token" || first.NickName != "fresh-user" {
|
||||
t.Fatalf("first SyncUserOnEnter user = %#v, want refreshed user with existing token", first)
|
||||
}
|
||||
if second == nil || second.Token != "existing-token" || second.NickName != "fresh-user" {
|
||||
t.Fatalf("second SyncUserOnEnter user = %#v, want memoized refreshed user", second)
|
||||
}
|
||||
if got := guestCalls.Load(); got != 0 {
|
||||
t.Errorf("guest calls = %d, want 0", got)
|
||||
}
|
||||
if got := getInfoCalls.Load(); got != 1 {
|
||||
t.Errorf("getInfo calls = %d, want 1", got)
|
||||
}
|
||||
select {
|
||||
case got := <-authorization:
|
||||
if got != "existing-token" {
|
||||
t.Errorf("Authorization = %q, want existing-token", got)
|
||||
}
|
||||
default:
|
||||
t.Error("getInfo did not capture Authorization header")
|
||||
}
|
||||
assertRequestToken(t, c, "existing-token")
|
||||
if got := cookieValue(c, "nickName"); got != "fresh-user" {
|
||||
t.Errorf("request nickName cookie = %q, want fresh-user", got)
|
||||
}
|
||||
assertSingleAuthCookieSet(t, recorder)
|
||||
}
|
||||
|
||||
func TestSyncUserOnEnterReusesGuestCreatedBeforeRender(t *testing.T) {
|
||||
var guestCalls atomic.Int32
|
||||
var getInfoCalls atomic.Int32
|
||||
|
||||
useAuthTestUpstream(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case guestPath:
|
||||
guestCalls.Add(1)
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("pre-render-token", "pre-render-guest"))
|
||||
case getInfoPath:
|
||||
getInfoCalls.Add(1)
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("pre-render-token", "unexpected-refresh"))
|
||||
default:
|
||||
t.Errorf("unexpected upstream request: %s %s", r.Method, r.URL.Path)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
|
||||
c, recorder := newAuthTestContext()
|
||||
guest := EnsureGuestOnEnter(c)
|
||||
user := SyncUserOnEnter(c)
|
||||
|
||||
if guest == nil || guest.Token != "pre-render-token" {
|
||||
t.Fatalf("EnsureGuestOnEnter user = %#v, want pre-render guest", guest)
|
||||
}
|
||||
if user == nil || user.Token != "pre-render-token" || user.NickName != "pre-render-guest" {
|
||||
t.Fatalf("SyncUserOnEnter user = %#v, want memoized pre-render guest", user)
|
||||
}
|
||||
if got := guestCalls.Load(); got != 1 {
|
||||
t.Errorf("guest calls = %d, want 1", got)
|
||||
}
|
||||
if got := getInfoCalls.Load(); got != 0 {
|
||||
t.Errorf("getInfo calls = %d, want 0", got)
|
||||
}
|
||||
assertRequestToken(t, c, "pre-render-token")
|
||||
assertSingleAuthCookieSet(t, recorder)
|
||||
}
|
||||
|
||||
func TestRefreshUserOnEnterReturnsRebuiltGuestWithoutRefreshingItAgain(t *testing.T) {
|
||||
var guestCalls atomic.Int32
|
||||
var getInfoCalls atomic.Int32
|
||||
getInfoAuthorization := make(chan string, 1)
|
||||
guestAuthorization := make(chan string, 1)
|
||||
|
||||
useAuthTestUpstream(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case getInfoPath:
|
||||
getInfoCalls.Add(1)
|
||||
select {
|
||||
case getInfoAuthorization <- r.Header.Get("Authorization"):
|
||||
default:
|
||||
}
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 6001, nil)
|
||||
case guestPath:
|
||||
guestCalls.Add(1)
|
||||
select {
|
||||
case guestAuthorization <- r.Header.Get("Authorization"):
|
||||
default:
|
||||
}
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("rebuilt-guest-token", "rebuilt-guest"))
|
||||
default:
|
||||
t.Errorf("unexpected upstream request: %s %s", r.Method, r.URL.Path)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
|
||||
c, recorder := newAuthTestContext(
|
||||
&http.Cookie{Name: "token", Value: "expired-guest-token"},
|
||||
&http.Cookie{Name: "isRegister", Value: "0"},
|
||||
&http.Cookie{Name: "userType", Value: "0"},
|
||||
)
|
||||
user := RefreshUserOnEnter(c)
|
||||
// The rebuilt guest must also be reusable by the page-level sync call.
|
||||
synced := SyncUserOnEnter(c)
|
||||
|
||||
if user == nil || user.Token != "rebuilt-guest-token" || user.NickName != "rebuilt-guest" {
|
||||
t.Fatalf("RefreshUserOnEnter user = %#v, want rebuilt guest", user)
|
||||
}
|
||||
if synced == nil || synced.Token != "rebuilt-guest-token" {
|
||||
t.Fatalf("SyncUserOnEnter user = %#v, want memoized rebuilt guest", synced)
|
||||
}
|
||||
if got := getInfoCalls.Load(); got != 1 {
|
||||
t.Errorf("getInfo calls = %d, want 1 (no refresh of rebuilt guest)", got)
|
||||
}
|
||||
if got := guestCalls.Load(); got != 1 {
|
||||
t.Errorf("guest calls = %d, want 1", got)
|
||||
}
|
||||
select {
|
||||
case got := <-getInfoAuthorization:
|
||||
if got != "expired-guest-token" {
|
||||
t.Errorf("getInfo Authorization = %q, want expired-guest-token", got)
|
||||
}
|
||||
default:
|
||||
t.Error("getInfo did not capture Authorization header")
|
||||
}
|
||||
select {
|
||||
case got := <-guestAuthorization:
|
||||
if got != "" {
|
||||
t.Errorf("guest Authorization = %q, want empty after expired token is removed", got)
|
||||
}
|
||||
default:
|
||||
t.Error("guest login did not capture Authorization header")
|
||||
}
|
||||
assertRequestToken(t, c, "rebuilt-guest-token")
|
||||
assertSingleAuthCookieSet(t, recorder)
|
||||
}
|
||||
|
||||
func TestSetAuthCookiesUpsertsSameNameWithinResponse(t *testing.T) {
|
||||
c, recorder := newAuthTestContext()
|
||||
SetAuthCookies(c, testLoginUser("first-token", "first-user"))
|
||||
SetAuthCookies(c, testLoginUser("latest-token", "latest-user"))
|
||||
|
||||
assertSingleAuthCookieSet(t, recorder)
|
||||
assertRequestToken(t, c, "latest-token")
|
||||
if got := cookieValue(c, "nickName"); got != "latest-user" {
|
||||
t.Errorf("request nickName cookie = %q, want latest-user", got)
|
||||
}
|
||||
for _, cookie := range recorder.Result().Cookies() {
|
||||
if cookie.Name == "token" && cookie.Value != "latest-token" {
|
||||
t.Errorf("response token cookie = %q, want latest-token", cookie.Value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func useAuthTestUpstream(t *testing.T, handler http.Handler) {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(handler)
|
||||
previousServerAddr := appg.Conf.ServerAddr
|
||||
appg.Conf.ServerAddr = server.URL
|
||||
t.Cleanup(func() {
|
||||
appg.Conf.ServerAddr = previousServerAddr
|
||||
server.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func newAuthTestContext(cookies ...*http.Cookie) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "https://site.test/page", nil)
|
||||
for _, cookie := range cookies {
|
||||
c.Request.AddCookie(cookie)
|
||||
}
|
||||
return c, recorder
|
||||
}
|
||||
|
||||
func writeAuthTestEnvelope(w http.ResponseWriter, status, code int, data *LoginResp) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data *LoginResp `json:"data"`
|
||||
}{
|
||||
Code: code,
|
||||
Msg: http.StatusText(status),
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
func testLoginUser(token, nickName string) *LoginResp {
|
||||
return &LoginResp{
|
||||
Token: token,
|
||||
UserID: 101,
|
||||
AccountNo: "account-101",
|
||||
Email: "user101@example.test",
|
||||
NickName: nickName,
|
||||
// This field is intentionally large: it must stay out of Set-Cookie headers.
|
||||
Introduction: strings.Repeat("简介", 150),
|
||||
Avatar: "https://cdn.example.test/avatar.png",
|
||||
InviteCode: "INVITE101",
|
||||
VipType: 1,
|
||||
CurrentVipExpire: "2099-01-01T00:00:00Z",
|
||||
ShowCardID: 7,
|
||||
ShowCardName: "monthly",
|
||||
Type: 0,
|
||||
Recharge: 88,
|
||||
}
|
||||
}
|
||||
|
||||
func assertRequestToken(t *testing.T, c *gin.Context, want string) {
|
||||
t.Helper()
|
||||
if got := useragent.TokenFromRequest(c.Request); got != want {
|
||||
t.Errorf("request token = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func assertSingleAuthCookieSet(t *testing.T, recorder *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
counts := make(map[string]int)
|
||||
for _, cookie := range recorder.Result().Cookies() {
|
||||
counts[cookie.Name]++
|
||||
}
|
||||
for name, count := range counts {
|
||||
if count > 1 {
|
||||
t.Errorf("Set-Cookie %q written %d times, want at most once", name, count)
|
||||
}
|
||||
}
|
||||
for _, name := range authCookieNamesWritten {
|
||||
if got := counts[name]; got != 1 {
|
||||
t.Errorf("auth Set-Cookie %q written %d times, want exactly once", name, got)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"introduction", "email", "inviteCode", "showCardId", "showCardName", "sid"} {
|
||||
if got := counts[name]; got != 0 {
|
||||
t.Errorf("non-session Set-Cookie %q written %d times, want none", name, got)
|
||||
}
|
||||
}
|
||||
var headerBytes int
|
||||
for _, raw := range recorder.Header().Values("Set-Cookie") {
|
||||
headerBytes += len("Set-Cookie: ") + len(raw) + len("\r\n")
|
||||
}
|
||||
if headerBytes >= 4096 {
|
||||
t.Errorf("Set-Cookie response headers = %d bytes, want below 4096", headerBytes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package authser
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
const requestAuthStateKey = "authser.request-auth-state"
|
||||
|
||||
// requestAuthState 只在单个 Gin 请求内有效,用来避免多个 SSR 服务重复刷新同一会话。
|
||||
// freshUser 表示本请求已经从上游取得并写回过的最新用户;suppressAutoAuth
|
||||
// 表示本请求明确不应再自动创建游客(例如用户刚退出或正式账号已过期)。
|
||||
type requestAuthState struct {
|
||||
freshUser *LoginResp
|
||||
suppressAutoAuth bool
|
||||
}
|
||||
|
||||
func authState(c *gin.Context) *requestAuthState {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
if value, ok := c.Get(requestAuthStateKey); ok {
|
||||
if state, ok := value.(*requestAuthState); ok && state != nil {
|
||||
return state
|
||||
}
|
||||
}
|
||||
state := &requestAuthState{}
|
||||
c.Set(requestAuthStateKey, state)
|
||||
return state
|
||||
}
|
||||
|
||||
func freshRequestAuthUser(c *gin.Context) *LoginResp {
|
||||
state := authState(c)
|
||||
if state == nil {
|
||||
return nil
|
||||
}
|
||||
return state.freshUser
|
||||
}
|
||||
|
||||
func rememberRequestAuthUser(c *gin.Context, user *LoginResp) {
|
||||
state := authState(c)
|
||||
if state == nil {
|
||||
return
|
||||
}
|
||||
state.freshUser = user
|
||||
state.suppressAutoAuth = false
|
||||
}
|
||||
|
||||
func forgetRequestAuthUser(c *gin.Context) {
|
||||
if state := authState(c); state != nil {
|
||||
state.freshUser = nil
|
||||
}
|
||||
}
|
||||
|
||||
func suppressRequestAutoAuth(c *gin.Context) {
|
||||
if state := authState(c); state != nil {
|
||||
state.suppressAutoAuth = true
|
||||
}
|
||||
}
|
||||
|
||||
func allowRequestAutoAuth(c *gin.Context) {
|
||||
if state := authState(c); state != nil {
|
||||
state.suppressAutoAuth = false
|
||||
}
|
||||
}
|
||||
|
||||
func requestAutoAuthSuppressed(c *gin.Context) bool {
|
||||
state := authState(c)
|
||||
return state != nil && state.suppressAutoAuth
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package authser
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
// TokenExpiredCode 上游约定:token 失效,需重新登录。
|
||||
const TokenExpiredCode = 1000
|
||||
|
||||
// IsSessionExpiredCode 是否为会话失效类业务码。
|
||||
func IsSessionExpiredCode(code int) bool {
|
||||
switch code {
|
||||
case TokenExpiredCode, 1002, 1012, 6001: // InvalidToken / NoToken / InvalidateToken / 用户不存在
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// OnSessionExpired 处理上游会话失效。
|
||||
// retry=true:游客已重新登录,调用方应重试原请求;
|
||||
// needLogin=true:注册账号已清 cookie,调用方应跳转登录弹窗/页。
|
||||
func OnSessionExpired(c *gin.Context, code int) (retry, needLogin bool) {
|
||||
if c == nil || !IsSessionExpiredCode(code) {
|
||||
return false, false
|
||||
}
|
||||
if IsRegisteredFromCookies(c) {
|
||||
ClearAuthCookies(c)
|
||||
dropRequestCookie(c, "token")
|
||||
dropRequestCookie(c, "_token_")
|
||||
// 正式账号失效后,本请求保持退出态,避免后续 HTML 渲染又静默转成游客。
|
||||
suppressRequestAutoAuth(c)
|
||||
return false, true
|
||||
}
|
||||
if RefreshGuestSession(c) != nil {
|
||||
return true, false
|
||||
}
|
||||
ClearAuthCookies(c)
|
||||
dropRequestCookie(c, "token")
|
||||
dropRequestCookie(c, "_token_")
|
||||
return false, false
|
||||
}
|
||||
|
||||
// RecoverContentSession 用于允许游客访问的内容读取接口。
|
||||
// 正式账号或游客 token 失效后,清理旧登录态、重新建立游客会话,调用方随后重试一次原请求。
|
||||
// 写操作仍应使用 OnSessionExpired,避免把用户操作静默降级为游客操作。
|
||||
func RecoverContentSession(c *gin.Context, code int) bool {
|
||||
if c == nil || !IsSessionExpiredCode(code) {
|
||||
return false
|
||||
}
|
||||
ClearAuthCookies(c)
|
||||
for _, name := range authCookieNames() {
|
||||
dropRequestCookie(c, name)
|
||||
}
|
||||
dropRequestCookie(c, guestSkipAutoCookie)
|
||||
ClearGuestSkipAuto(c)
|
||||
// 内容读取接口明确允许降级为游客,因此覆盖本请求可能已有的自动认证抑制。
|
||||
allowRequestAutoAuth(c)
|
||||
return EnsureGuestOnEnter(c) != nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package authser
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// RegisterReq 对应 swagger authapi.registerReq
|
||||
type RegisterReq struct {
|
||||
AccountNo string `json:"accountNo"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Password string `json:"password"`
|
||||
AgentInviteCode string `json:"agentInviteCode,omitempty"`
|
||||
DevID string `json:"devID,omitempty"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
}
|
||||
|
||||
// LoginReq 对应 swagger authapi.loginReq
|
||||
type LoginReq struct {
|
||||
Account string `json:"account"`
|
||||
Password string `json:"password"`
|
||||
DevID string `json:"devID,omitempty"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
}
|
||||
|
||||
// ResetPasswordReq 对应 swagger authapi.resetPasswordReq。
|
||||
type ResetPasswordReq struct {
|
||||
AccountNo string `json:"accountNo"`
|
||||
Email string `json:"email"`
|
||||
NewPassword string `json:"newPassword"`
|
||||
}
|
||||
|
||||
// GuestLoginReq 对应 swagger authser.GuestLoginReq
|
||||
// POST /api/app/auth/guest
|
||||
type GuestLoginReq struct {
|
||||
DevID string `json:"devID"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
Mac string `json:"mac,omitempty"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateProfileReq 对应 swagger authapi.updateProfileReq
|
||||
type UpdateProfileReq struct {
|
||||
Avatar *string `json:"avatar,omitempty"`
|
||||
Introduction *string `json:"introduction,omitempty"`
|
||||
NickName *string `json:"nickName,omitempty"`
|
||||
OldPassword *string `json:"oldPassword,omitempty"`
|
||||
NewPassword *string `json:"newPassword,omitempty"`
|
||||
PrivacyMode *bool `json:"privacyMode,omitempty"`
|
||||
}
|
||||
|
||||
// LoginResp 对应 swagger authser.LoginResp
|
||||
// GET /api/app/auth/getInfo、登录/注册/游客成功 data。
|
||||
type LoginResp struct {
|
||||
Token string `json:"token"`
|
||||
UserID int64 `json:"userId"`
|
||||
AccountNo string `json:"accountNo"`
|
||||
Email string `json:"email"`
|
||||
NickName string `json:"nickName"`
|
||||
Introduction string `json:"introduction"` // 简介
|
||||
Avatar string `json:"avatar"` // 头像
|
||||
InviteCode string `json:"inviteCode"` // 邀请码
|
||||
VipType int `json:"vipType"` // 0没卡 1月卡 2年卡
|
||||
CurrentVipExpire string `json:"currentVipExpire"` // VIP 过期时间,需结合 vipType 判断是否有效
|
||||
ShowCardID int64 `json:"showCardId"` // 最新会员卡 id
|
||||
ShowCardName string `json:"showCardName"` // 最新会员卡名称,如「1个月会员」
|
||||
Status int `json:"status"` // 0正常 1封禁 2禁言
|
||||
Type int `json:"type"` // 身份类型:0游客 1普通用户
|
||||
IsNewUser bool `json:"isNewUser"` // 本次是否新建游客
|
||||
IsRegister bool `json:"isRegister"` // 是否已注册
|
||||
HasPassword *bool `json:"hasPassword,omitempty"` // 是否已设置密码;上游未返回时由账号状态推断
|
||||
LoginType int `json:"loginType"` // 登录方式
|
||||
PrivacyMode bool `json:"privacyMode"` // 隐私模式
|
||||
Score int64 `json:"score"` // 积分
|
||||
Recharge int64 `json:"recharge"` // 金币余额
|
||||
}
|
||||
|
||||
// APIEnvelope 上游统一响应壳。Data 在失败时可能是 string/null。
|
||||
type APIEnvelope struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Tip string `json:"tip"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
// ImageUploadData 对应 swagger uploadser.ImageUploadData
|
||||
type ImageUploadData struct {
|
||||
ID string `json:"id"`
|
||||
SourceNameFs string `json:"sourceNameFs"`
|
||||
}
|
||||
|
||||
// ImageUploadResp 对应 swagger uploadser.ImageUploadResp
|
||||
type ImageUploadResp struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Tip string `json:"tip"`
|
||||
Data *ImageUploadData `json:"data"`
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package authser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SettingPageVM 账号设置页展示模型。
|
||||
type SettingPageVM struct {
|
||||
UserID int64
|
||||
AccountNo string
|
||||
HasAccount bool
|
||||
HasPassword bool
|
||||
NickName string
|
||||
Introduction string
|
||||
Email string
|
||||
EmailMasked string
|
||||
EmailBound bool
|
||||
Avatar string // 可用头像 URL;空则模板用默认图
|
||||
InviteCode string
|
||||
PrivacyMode bool
|
||||
VipType int
|
||||
VipExpire string
|
||||
Recharge int64
|
||||
Score int64
|
||||
DisplayName string
|
||||
}
|
||||
|
||||
// BuildSettingVM 由 LoginResp 构建设置页 VM。
|
||||
func BuildSettingVM(user *LoginResp) SettingPageVM {
|
||||
if user == nil {
|
||||
return SettingPageVM{}
|
||||
}
|
||||
nick := strings.TrimSpace(user.NickName)
|
||||
account := strings.TrimSpace(user.AccountNo)
|
||||
registered := user.IsRegister || user.Type == 1
|
||||
hasAccount := registered && account != ""
|
||||
hasPassword := hasAccount
|
||||
if user.HasPassword != nil {
|
||||
hasPassword = *user.HasPassword
|
||||
}
|
||||
email := strings.TrimSpace(user.Email)
|
||||
intro := strings.TrimSpace(user.Introduction)
|
||||
display := nick
|
||||
if display == "" {
|
||||
display = account
|
||||
}
|
||||
if display == "" {
|
||||
display = "用户"
|
||||
}
|
||||
return SettingPageVM{
|
||||
UserID: user.UserID,
|
||||
AccountNo: account,
|
||||
HasAccount: hasAccount,
|
||||
HasPassword: hasPassword,
|
||||
NickName: nick,
|
||||
Introduction: intro,
|
||||
Email: email,
|
||||
EmailMasked: MaskEmail(email),
|
||||
EmailBound: email != "",
|
||||
Avatar: usableAvatarURL(user.Avatar),
|
||||
InviteCode: strings.TrimSpace(user.InviteCode),
|
||||
PrivacyMode: user.PrivacyMode,
|
||||
VipType: user.VipType,
|
||||
VipExpire: strings.TrimSpace(user.CurrentVipExpire),
|
||||
Recharge: user.Recharge,
|
||||
Score: user.Score,
|
||||
DisplayName: display,
|
||||
}
|
||||
}
|
||||
|
||||
// MaskEmail 邮箱脱敏,如 ab***@mail.com。
|
||||
func MaskEmail(email string) string {
|
||||
email = strings.TrimSpace(email)
|
||||
if email == "" {
|
||||
return ""
|
||||
}
|
||||
at := strings.LastIndex(email, "@")
|
||||
if at <= 0 || at == len(email)-1 {
|
||||
return email
|
||||
}
|
||||
local := email[:at]
|
||||
domain := email[at:]
|
||||
runes := []rune(local)
|
||||
if len(runes) <= 2 {
|
||||
return string(runes[:1]) + "***" + domain
|
||||
}
|
||||
return string(runes[:2]) + "***" + domain
|
||||
}
|
||||
|
||||
// FormatUserID 展示用 ID。
|
||||
func FormatUserID(id int64) string {
|
||||
if id <= 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%d", id)
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package authser
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func parseVipExpireMs(raw string) int64 {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return 0
|
||||
}
|
||||
if n, err := strconv.ParseInt(raw, 10, 64); err == nil {
|
||||
if n > 0 && n < 1e12 {
|
||||
return n * 1000
|
||||
}
|
||||
return n
|
||||
}
|
||||
layouts := []string{
|
||||
time.RFC3339Nano,
|
||||
time.RFC3339,
|
||||
"2006-01-02T15:04:05Z07:00",
|
||||
"2006-01-02 15:04:05",
|
||||
}
|
||||
for _, layout := range layouts {
|
||||
if t, err := time.Parse(layout, raw); err == nil {
|
||||
return t.UnixMilli()
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// UserIDFromCookies 读取 cookie userId。
|
||||
func UserIDFromCookies(c *gin.Context) int64 {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
n, _ := strconv.ParseInt(strings.TrimSpace(cookieValue(c, "userId")), 10, 64)
|
||||
if n < 0 {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// VipTypeFromCookies 读取 cookie vipType。
|
||||
func VipTypeFromCookies(c *gin.Context) int {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
n, _ := strconv.Atoi(strings.TrimSpace(cookieValue(c, "vipType")))
|
||||
return n
|
||||
}
|
||||
|
||||
// VipTypeLabel vipType 文案:0普通 1月卡 2年卡(与 91ly / 编辑资料注释一致)。
|
||||
func VipTypeLabel(vipType int) string {
|
||||
switch vipType {
|
||||
case 1:
|
||||
return "月卡会员"
|
||||
case 2:
|
||||
return "年卡会员"
|
||||
default:
|
||||
return "普通会员"
|
||||
}
|
||||
}
|
||||
|
||||
// ShowCardNameFromCookies 读取 cookie showCardName。
|
||||
func ShowCardNameFromCookies(c *gin.Context) string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(cookieValue(c, "showCardName"))
|
||||
}
|
||||
|
||||
// ShowCardIDFromCookies 读取 cookie showCardId。
|
||||
func ShowCardIDFromCookies(c *gin.Context) int64 {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
n, _ := strconv.ParseInt(strings.TrimSpace(cookieValue(c, "showCardId")), 10, 64)
|
||||
if n < 0 {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// VipDisplayLabel 优先使用 getInfo.showCardName,否则回退 vipType 文案。
|
||||
func VipDisplayLabel(showCardName string, vipType int) string {
|
||||
if s := strings.TrimSpace(showCardName); s != "" {
|
||||
return s
|
||||
}
|
||||
return VipTypeLabel(vipType)
|
||||
}
|
||||
|
||||
// VipDisplayLabelFromCookies 从 cookie 组装会员展示名。
|
||||
func VipDisplayLabelFromCookies(c *gin.Context) string {
|
||||
return VipDisplayLabel(ShowCardNameFromCookies(c), VipTypeFromCookies(c))
|
||||
}
|
||||
|
||||
// IsActiveVipUser 根据 vipType + currentVipExpire 判断是否有效会员。
|
||||
func IsActiveVipUser(vipType int, currentVipExpire string) bool {
|
||||
if vipType == 0 {
|
||||
return false
|
||||
}
|
||||
expireMs := parseVipExpireMs(currentVipExpire)
|
||||
if expireMs <= 0 {
|
||||
return false
|
||||
}
|
||||
return expireMs > time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// FormatVipExpireText 格式化到期时间展示。
|
||||
func FormatVipExpireText(currentVipExpire string) string {
|
||||
ms := parseVipExpireMs(currentVipExpire)
|
||||
if ms <= 0 {
|
||||
return ""
|
||||
}
|
||||
return time.UnixMilli(ms).In(time.Local).Format("有效期至 2006/01/02")
|
||||
}
|
||||
|
||||
// VipExpireTextFromCookies 格式化到期时间展示。
|
||||
func VipExpireTextFromCookies(c *gin.Context) string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
return FormatVipExpireText(cookieValue(c, "currentVipExpire"))
|
||||
}
|
||||
|
||||
// IsActiveVipFromCookies vipType≠0 且 currentVipExpire 未过期(与 91ly 一致)。
|
||||
func IsActiveVipFromCookies(c *gin.Context) bool {
|
||||
if c == nil {
|
||||
return false
|
||||
}
|
||||
return IsActiveVipUser(VipTypeFromCookies(c), cookieValue(c, "currentVipExpire"))
|
||||
}
|
||||
|
||||
// RechargeFromCookies 读取 cookie recharge(金币余额)。
|
||||
func RechargeFromCookies(c *gin.Context) int64 {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
n, _ := strconv.ParseInt(strings.TrimSpace(cookieValue(c, "recharge")), 10, 64)
|
||||
if n < 0 {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// SetRechargeCookie 更新金币余额 cookie(解锁/充值后同步)。
|
||||
func SetRechargeCookie(c *gin.Context, balance int64) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
if balance < 0 {
|
||||
balance = 0
|
||||
}
|
||||
secure := c.Request != nil && c.Request.TLS != nil
|
||||
setCookie(c, "recharge", strconv.FormatInt(balance, 10), secure)
|
||||
}
|
||||
|
||||
// FormatRecharge 金币余额千分位展示。
|
||||
func FormatRecharge(n int64) string {
|
||||
if n < 0 {
|
||||
n = 0
|
||||
}
|
||||
s := strconv.FormatInt(n, 10)
|
||||
if len(s) <= 3 {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
rem := len(s) % 3
|
||||
if rem > 0 {
|
||||
b.WriteString(s[:rem])
|
||||
if len(s) > rem {
|
||||
b.WriteByte(',')
|
||||
}
|
||||
}
|
||||
for i := rem; i < len(s); i += 3 {
|
||||
b.WriteString(s[i : i+3])
|
||||
if i+3 < len(s) {
|
||||
b.WriteByte(',')
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
Reference in New Issue
Block a user