100 lines
2.5 KiB
Go
100 lines
2.5 KiB
Go
package controllers
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-contrib/sessions"
|
|
"github.com/gin-gonic/gin"
|
|
"lv8girl/internal/services"
|
|
)
|
|
|
|
type AuthController struct {
|
|
authService *services.AuthService
|
|
}
|
|
|
|
func NewAuthController() *AuthController {
|
|
return &AuthController{
|
|
authService: services.NewAuthService(),
|
|
}
|
|
}
|
|
|
|
func (c *AuthController) ShowLogin(ctx *gin.Context) {
|
|
session := sessions.Default(ctx)
|
|
if session.Get("user_id") != nil {
|
|
ctx.Redirect(http.StatusFound, "/")
|
|
return
|
|
}
|
|
ctx.HTML(http.StatusOK, "login.html", gin.H{"Error": ""})
|
|
}
|
|
|
|
func (c *AuthController) Login(ctx *gin.Context) {
|
|
session := sessions.Default(ctx)
|
|
if session.Get("user_id") != nil {
|
|
ctx.Redirect(http.StatusFound, "/")
|
|
return
|
|
}
|
|
|
|
login := ctx.PostForm("login")
|
|
password := ctx.PostForm("password")
|
|
|
|
if login == "" || password == "" {
|
|
ctx.HTML(http.StatusOK, "login.html", gin.H{"Error": "请输入用户名/邮箱和密码"})
|
|
return
|
|
}
|
|
|
|
result := c.authService.Login(login, password)
|
|
if !result.Success {
|
|
ctx.HTML(http.StatusOK, "login.html", gin.H{"Error": result.Error})
|
|
return
|
|
}
|
|
|
|
session.Set("user_id", result.User.ID)
|
|
session.Set("username", result.User.Username)
|
|
session.Set("user_role", result.User.Role)
|
|
session.Save()
|
|
|
|
ctx.Redirect(http.StatusFound, "/")
|
|
}
|
|
|
|
func (c *AuthController) ShowRegister(ctx *gin.Context) {
|
|
session := sessions.Default(ctx)
|
|
if session.Get("user_id") != nil {
|
|
ctx.Redirect(http.StatusFound, "/")
|
|
return
|
|
}
|
|
ctx.HTML(http.StatusOK, "register.html", gin.H{"Error": "", "Success": ""})
|
|
}
|
|
|
|
func (c *AuthController) Register(ctx *gin.Context) {
|
|
session := sessions.Default(ctx)
|
|
if session.Get("user_id") != nil {
|
|
ctx.Redirect(http.StatusFound, "/")
|
|
return
|
|
}
|
|
|
|
username := ctx.PostForm("username")
|
|
email := ctx.PostForm("email")
|
|
password := ctx.PostForm("password")
|
|
confirmPassword := ctx.PostForm("confirm_password")
|
|
|
|
if password != confirmPassword {
|
|
ctx.HTML(http.StatusOK, "register.html", gin.H{"Error": "两次输入的密码不一致", "Success": ""})
|
|
return
|
|
}
|
|
|
|
result := c.authService.Register(username, email, password)
|
|
if !result.Success {
|
|
ctx.HTML(http.StatusOK, "register.html", gin.H{"Error": result.Error, "Success": ""})
|
|
return
|
|
}
|
|
|
|
ctx.HTML(http.StatusOK, "register.html", gin.H{"Error": "", "Success": "注册成功!您的账号正在等待管理员审核,请耐心等待。"})
|
|
}
|
|
|
|
func (c *AuthController) Logout(ctx *gin.Context) {
|
|
session := sessions.Default(ctx)
|
|
session.Clear()
|
|
session.Save()
|
|
ctx.Redirect(http.StatusFound, "/")
|
|
}
|