80 lines
1.9 KiB
Go
80 lines
1.9 KiB
Go
package controller
|
|
|
|
import (
|
|
"electricity_bill_calc/cache"
|
|
"electricity_bill_calc/exceptions"
|
|
"electricity_bill_calc/model"
|
|
"electricity_bill_calc/response"
|
|
"electricity_bill_calc/security"
|
|
"electricity_bill_calc/service"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type _UserController struct {
|
|
Router *gin.Engine
|
|
}
|
|
|
|
var UserController *_UserController
|
|
|
|
func InitializeUserController(router *gin.Engine) {
|
|
UserController = &_UserController{
|
|
Router: router,
|
|
}
|
|
UserController.Router.POST("/login", UserController.Login)
|
|
UserController.Router.DELETE("/logout", security.MustAuthenticated, UserController.Logout)
|
|
}
|
|
|
|
type LoginFormData struct {
|
|
Username string `form:"uname"`
|
|
Password string `form:"upass"`
|
|
Type int8 `form:"type"`
|
|
}
|
|
|
|
func (_UserController) Login(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
loginData := new(LoginFormData)
|
|
c.BindJSON(loginData)
|
|
var (
|
|
session *model.Session
|
|
err error
|
|
)
|
|
if loginData.Type == 0 {
|
|
session, err = service.UserService.ProcessEnterpriseUserLogin(loginData.Username, loginData.Password)
|
|
} else {
|
|
session, err = service.UserService.ProcessManagementUserLogin(loginData.Username, loginData.Password)
|
|
}
|
|
if err != nil {
|
|
if errors.Is(err, &exceptions.AuthenticationError{}) {
|
|
authError := err.(exceptions.AuthenticationError)
|
|
if authError.NeedReset {
|
|
result.LoginNeedReset()
|
|
return
|
|
}
|
|
result.Error(int(authError.Code), authError.Message)
|
|
return
|
|
} else {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
}
|
|
result.LoginSuccess(session)
|
|
}
|
|
|
|
func (_UserController) Logout(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
session, exists := c.Get("session")
|
|
if !exists {
|
|
result.Success("用户会话已结束。")
|
|
return
|
|
}
|
|
_, err := cache.ClearSession(session.(*model.Session).Token)
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
result.Success("用户已成功登出系统。")
|
|
}
|