88 lines
2.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package handler
import (
"time"
"github.com/gofiber/fiber/v2"
"gitee.ltd/lxh/wechat-robot/internal/config"
"gitee.ltd/lxh/wechat-robot/internal/middleware"
)
// LoginPage 显示登录页面
func LoginPage(c *fiber.Ctx) error {
// 如果已经登录,则重定向到机器人列表
if _, flag := middleware.IsAuthenticated(c); flag {
return c.Redirect("/admin/robots")
}
// 获取可能的错误消息
errorMsg := c.Query("error")
// 加载配置
if config.Scd.Auth.Type == "logto" {
// 如果使用Logto认证重定向到Logto登录页面
return c.Redirect("/auth/logto/login")
}
// 设置 NoLayout 为 true使用独立布局不显示主应用的导航组件
return c.Render("auth/login", fiber.Map{
"Title": "登录",
"ErrorMsg": errorMsg,
"NoLayout": true,
})
}
// LoginSubmit 处理登录表单提交
func LoginSubmit(c *fiber.Ctx) error {
// 获取用户输入的密钥
token := c.FormValue("token")
// 根据认证类型进行不同的验证
if config.Scd.Auth.Type == "password" {
// 仅验证密钥是否与配置的AdminToken匹配
if token != config.Scd.Auth.Password.AdminToken {
return c.Redirect("/login?error=访问密钥不正确")
}
// 登录成功,设置认证 Cookie
cookie := new(fiber.Cookie)
cookie.Name = "auth_token"
cookie.Value = config.Scd.Auth.Password.SecretKey // 在实际应用中,这应该是一个生成的会话令牌
cookie.Expires = time.Now().Add(time.Hour * time.Duration(config.Scd.Auth.Password.TokenExpiry))
cookie.HTTPOnly = true
cookie.Path = "/"
c.Cookie(cookie)
// 重定向到机器人列表页面,而不是首页
return c.Redirect("/admin/robots")
} else if config.Scd.Auth.Type == "logto" {
// 对于Logto登录我们重定向到Logto登录页面
return c.Redirect("/auth/logto/login")
}
// 不支持的认证类型
return c.Redirect("/login?error=不支持的认证类型")
}
// Logout 处理退出登录
func Logout(c *fiber.Ctx) error {
// 根据认证类型执行不同的登出逻辑
if config.Scd.Auth.Type == "logto" {
// 对于Logto登录使用Logto的登出流程
return c.Redirect("/auth/logto/logout")
}
// 密码认证方式直接清除认证Cookie
cookie := new(fiber.Cookie)
cookie.Name = "auth_token"
cookie.Value = ""
cookie.Expires = time.Now().Add(-time.Hour) // 设置为过期
cookie.HTTPOnly = true
cookie.Path = "/"
c.Cookie(cookie)
// 重定向到登录页
return c.Redirect("/login")
}