372 lines
11 KiB
Go
372 lines
11 KiB
Go
package controller
|
|
|
|
import (
|
|
"electricity_bill_calc/cache"
|
|
"electricity_bill_calc/exceptions"
|
|
"electricity_bill_calc/global"
|
|
"electricity_bill_calc/model"
|
|
"electricity_bill_calc/response"
|
|
"electricity_bill_calc/security"
|
|
"electricity_bill_calc/service"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/shopspring/decimal"
|
|
)
|
|
|
|
func InitializeUserController(router *gin.Engine) {
|
|
router.DELETE("/password/:uid", security.OPSAuthorize, invalidUserPassword)
|
|
router.DELETE("/login", security.MustAuthenticated, logout)
|
|
router.PUT("/password", resetUserPassword)
|
|
router.GET("/accounts", security.OPSAuthorize, listPagedUser)
|
|
router.POST("/login", login)
|
|
router.PUT("/account/enabled/state", security.OPSAuthorize, switchUserEnabling)
|
|
router.POST("/account", security.OPSAuthorize, createOPSAndManagementAccount)
|
|
router.GET("/account/:uid", security.MustAuthenticated, getUserDetail)
|
|
router.POST("/enterprise", security.OPSAuthorize, createEnterpriseAccount)
|
|
router.PUT("/account/:uid", security.OPSAuthorize, modifyAccountDetail)
|
|
router.GET("/enterprise/quick/search", security.OPSAuthorize, quickSearchEnterprise)
|
|
router.GET("/expiration", security.EnterpriseAuthorize, fetchExpiration)
|
|
}
|
|
|
|
type _LoginFormData struct {
|
|
Username string `json:"uname"`
|
|
Password string `json:"upass"`
|
|
Type int8 `json:"type"`
|
|
}
|
|
|
|
func login(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
loginData := new(_LoginFormData)
|
|
err := c.BindJSON(loginData)
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, "表单解析失败。")
|
|
return
|
|
}
|
|
var (
|
|
session *model.Session
|
|
)
|
|
if loginData.Type == model.USER_TYPE_ENT {
|
|
session, err = service.UserService.ProcessEnterpriseUserLogin(loginData.Username, loginData.Password)
|
|
} else {
|
|
session, err = service.UserService.ProcessManagementUserLogin(loginData.Username, loginData.Password)
|
|
}
|
|
if err != nil {
|
|
if authError, ok := err.(*exceptions.AuthenticationError); ok {
|
|
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 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("用户已成功登出系统。")
|
|
}
|
|
|
|
func invalidUserPassword(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
targetUserId := c.Param("uid")
|
|
verifyCode, err := service.UserService.InvalidUserPassword(targetUserId)
|
|
if _, ok := err.(exceptions.NotFoundError); ok {
|
|
result.NotFound("未找到指定用户。")
|
|
return
|
|
}
|
|
if _, ok := err.(exceptions.UnsuccessfulOperationError); ok {
|
|
result.NotAccept("未能成功更新用户的密码。")
|
|
return
|
|
}
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
result.Json(http.StatusAccepted, "用户密码已经失效", gin.H{"verify": verifyCode})
|
|
}
|
|
|
|
type _ResetPasswordFormData struct {
|
|
VerifyCode string `json:"verifyCode"`
|
|
Username string `json:"uname"`
|
|
NewPassword string `json:"newPass"`
|
|
}
|
|
|
|
func resetUserPassword(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
resetForm := new(_ResetPasswordFormData)
|
|
c.BindJSON(resetForm)
|
|
verified, err := service.UserService.VerifyUserPassword(resetForm.Username, resetForm.VerifyCode)
|
|
if _, ok := err.(exceptions.NotFoundError); ok {
|
|
result.NotFound("指定的用户不存在。")
|
|
return
|
|
}
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
if !verified {
|
|
result.Error(http.StatusUnauthorized, "验证码不正确。")
|
|
return
|
|
}
|
|
completed, err := service.UserService.ResetUserPassword(resetForm.Username, resetForm.NewPassword)
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
if completed {
|
|
result.Updated("用户凭据已更新。")
|
|
return
|
|
}
|
|
result.NotAccept("用户凭据未能成功更新。")
|
|
}
|
|
|
|
func listPagedUser(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
requestPage, err := strconv.Atoi(c.DefaultQuery("page", "1"))
|
|
if err != nil {
|
|
result.NotAccept("查询参数[page]格式不正确。")
|
|
return
|
|
}
|
|
requestKeyword := c.DefaultQuery("keyword", "")
|
|
requestUserType, err := strconv.Atoi(c.DefaultQuery("type", "-1"))
|
|
if err != nil {
|
|
result.NotAccept("查询参数[type]格式不正确。")
|
|
return
|
|
}
|
|
var requestUserStat *bool
|
|
state, err := strconv.ParseBool(c.Query("state"))
|
|
if err != nil {
|
|
requestUserStat = nil
|
|
} else {
|
|
requestUserStat = &state
|
|
}
|
|
users, total, err := service.UserService.ListUserDetail(requestKeyword, requestUserType, requestUserStat, requestPage)
|
|
if err != nil {
|
|
result.NotFound(err.Error())
|
|
return
|
|
}
|
|
result.Json(
|
|
http.StatusOK,
|
|
"已取得符合条件的用户集合。",
|
|
response.NewPagedResponse(requestPage, total).ToMap(),
|
|
gin.H{"accounts": users},
|
|
)
|
|
}
|
|
|
|
type _UserStateChangeFormData struct {
|
|
UserID string `json:"uid" form:"uid"`
|
|
Enabled bool `json:"enabled" form:"enabled"`
|
|
}
|
|
|
|
func switchUserEnabling(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
switchForm := new(_UserStateChangeFormData)
|
|
c.BindJSON(switchForm)
|
|
err := service.UserService.SwitchUserState(switchForm.UserID, switchForm.Enabled)
|
|
if err != nil {
|
|
if nfErr, ok := err.(*exceptions.NotFoundError); ok {
|
|
result.NotFound(nfErr.Message)
|
|
return
|
|
} else {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
}
|
|
result.Updated("用户状态已经更新。")
|
|
}
|
|
|
|
type _OPSAccountCreationFormData struct {
|
|
Username string `json:"username" form:"username"`
|
|
Name string `json:"name" form:"name"`
|
|
Contact *string `json:"contact" form:"contact"`
|
|
Phone *string `json:"phone" form:"phone"`
|
|
Type int `json:"type" form:"type"`
|
|
}
|
|
|
|
func createOPSAndManagementAccount(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
creationForm := new(_OPSAccountCreationFormData)
|
|
c.BindJSON(creationForm)
|
|
exists, err := service.UserService.IsUsernameExists(creationForm.Username)
|
|
if exists {
|
|
result.Conflict("指定的用户名已经被使用了。")
|
|
return
|
|
}
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
newUser := new(model.User)
|
|
newUser.Username = creationForm.Username
|
|
newUser.Type = int8(creationForm.Type)
|
|
newUser.Enabled = true
|
|
newUserDetail := new(model.UserDetail)
|
|
newUserDetail.Name = &creationForm.Name
|
|
newUserDetail.Contact = creationForm.Contact
|
|
newUserDetail.Phone = creationForm.Phone
|
|
newUserDetail.UnitServiceFee = decimal.Zero
|
|
newUserDetail.ServiceExpiration, _ = time.Parse("2006-01-02 15:04:05", "2099-12-31 23:59:59")
|
|
verifyCode, err := service.UserService.CreateUser(newUser, newUserDetail)
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
cache.AbolishRelation("user")
|
|
result.Json(http.StatusCreated, "用户已经成功创建。", gin.H{"verify": verifyCode})
|
|
}
|
|
|
|
func getUserDetail(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
targetUserId := c.Param("uid")
|
|
exists, err := service.UserService.IsUserExists(targetUserId)
|
|
if !exists {
|
|
result.NotFound("指定的用户不存在。")
|
|
return
|
|
}
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
}
|
|
userDetail, err := service.UserService.FetchUserDetail(targetUserId)
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
result.Json(http.StatusOK, "用户详细信息已获取到。", gin.H{"user": userDetail})
|
|
}
|
|
|
|
type _EnterpriseCreationFormData struct {
|
|
Username string `json:"username" form:"username"`
|
|
Name string `json:"name" form:"name"`
|
|
Region *string `json:"region" form:"region"`
|
|
Address *string `json:"address" form:"address"`
|
|
Contact *string `json:"contact" form:"contact"`
|
|
Phone *string `json:"phone" form:"phone"`
|
|
UnitServiceFee *string `json:"unitServiceFee" form:"unitServiceFee"`
|
|
}
|
|
|
|
func createEnterpriseAccount(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
creationForm := new(_EnterpriseCreationFormData)
|
|
c.BindJSON(creationForm)
|
|
exists, err := service.UserService.IsUsernameExists(creationForm.Username)
|
|
if exists {
|
|
result.Conflict("指定的用户名已经被使用了。")
|
|
return
|
|
}
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
newUser := new(model.User)
|
|
newUser.Username = creationForm.Username
|
|
newUser.Type = model.USER_TYPE_ENT
|
|
newUser.Enabled = true
|
|
newUserDetail := new(model.UserDetail)
|
|
newUserDetail.Name = &creationForm.Name
|
|
newUserDetail.Contact = creationForm.Contact
|
|
newUserDetail.Phone = creationForm.Phone
|
|
newUserDetail.UnitServiceFee, err = decimal.NewFromString(*creationForm.UnitServiceFee)
|
|
if err != nil {
|
|
result.BadRequest("用户月服务费无法解析。")
|
|
return
|
|
}
|
|
newUserDetail.ServiceExpiration = time.Now()
|
|
|
|
verifyCode, err := service.UserService.CreateUser(newUser, newUserDetail)
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
cache.AbolishRelation("user")
|
|
result.Json(http.StatusCreated, "用户已经成功创建。", gin.H{"verify": verifyCode})
|
|
}
|
|
|
|
type _AccountModificationFormData struct {
|
|
Name string `json:"name" form:"name"`
|
|
Region *string `json:"region" form:"region"`
|
|
Address *string `json:"address" form:"address"`
|
|
Contact *string `json:"contact" form:"contact"`
|
|
Phone *string `json:"phone" form:"phone"`
|
|
UnitServiceFee *string `json:"unitServiceFee" form:"unitServiceFee"`
|
|
}
|
|
|
|
func modifyAccountDetail(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
targetUserId := c.Param("uid")
|
|
modForm := new(_AccountModificationFormData)
|
|
c.BindJSON(modForm)
|
|
exists, err := service.UserService.IsUserExists(targetUserId)
|
|
if !exists {
|
|
result.NotFound("指定的用户不存在。")
|
|
return
|
|
}
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
newUserInfo := new(model.UserDetail)
|
|
newUserInfo.Name = &modForm.Name
|
|
newUserInfo.Region = modForm.Region
|
|
newUserInfo.Address = modForm.Address
|
|
newUserInfo.Contact = modForm.Contact
|
|
newUserInfo.Phone = modForm.Phone
|
|
newUserInfo.UnitServiceFee, err = decimal.NewFromString(*modForm.UnitServiceFee)
|
|
if err != nil {
|
|
result.BadRequest("用户月服务费无法解析。")
|
|
return
|
|
}
|
|
_, err = global.DBConn.ID(targetUserId).Update(newUserInfo)
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
cache.AbolishRelation("user")
|
|
cache.AbolishRelation(fmt.Sprintf("user_%s", targetUserId))
|
|
result.Updated("指定用户的信息已经更新。")
|
|
}
|
|
|
|
func quickSearchEnterprise(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
keyword := c.Query("keyword")
|
|
searchResult, err := service.UserService.SearchLimitUsers(keyword, 6)
|
|
if err != nil {
|
|
result.Error(http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
result.Json(http.StatusOK, "已查询到存在符合条件的企业", gin.H{"users": searchResult})
|
|
}
|
|
|
|
func fetchExpiration(c *gin.Context) {
|
|
result := response.NewResult(c)
|
|
session, err := _retreiveSession(c)
|
|
if err != nil {
|
|
result.Unauthorized(err.Error())
|
|
return
|
|
}
|
|
user, err := service.UserService.FetchUserDetail(session.Uid)
|
|
if err != nil {
|
|
result.NotFound(err.Error())
|
|
return
|
|
}
|
|
result.Json(http.StatusOK, "已经取得用户的服务期限信息", gin.H{"expiration": user.ServiceExpiration.Format("2006-01-02")})
|
|
}
|