// Copyright 2022 E99p1ant. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package context import ( "github.com/flamego/flamego" "github.com/flamego/session" "github.com/tamakyi/TamaBox/internal/db" "github.com/tamakyi/TamaBox/internal/i18n" ) // authenticatedUser returns the user object of the authenticated user. func authenticatedUser(ctx flamego.Context, sess session.Session) *db.User { uid, ok := sess.Get("uid").(uint) if !ok { return nil } user, err := db.Users.GetByID(ctx.Request().Context(), uid) if err != nil || user == nil { return nil } // 密码变更后,旧会话保存的版本号不匹配,强制重新登录。 ver, _ := sess.Get("pwd_ver").(uint) if user.PasswordVersion != ver { return nil } return user } type ToggleOptions struct { UserSignInRequired bool UserSignOutRequired bool } func Toggle(options *ToggleOptions) flamego.Handler { return func(ctx Context, endpoint EndpointType) error { if options.UserSignOutRequired && ctx.IsLogged { ctx.Redirect("/") return nil } if options.UserSignInRequired && !ctx.IsLogged { if endpoint.IsAPI() { return ctx.JSONError(40100, i18n.T(ctx.Lang(), "auth.errLoginRequired")) } ctx.SetErrorFlash(i18n.T(ctx.Lang(), "auth.errLoginRequired")) ctx.Redirect("/login") return nil } return nil } }