refactor(session):提取获取用户会话的功能。

This commit is contained in:
徐涛 2022-08-16 06:08:04 +08:00
parent c7b87992dd
commit edabcea58d
3 changed files with 40 additions and 16 deletions

20
controller/abstract.go Normal file
View File

@ -0,0 +1,20 @@
package controller
import (
"electricity_bill_calc/exceptions"
"electricity_bill_calc/model"
"github.com/gin-gonic/gin"
)
func _retreiveSession(c *gin.Context) (*model.Session, error) {
session, exists := c.Get("session")
if !exists {
return nil, exceptions.NewUnauthorizedError("用户会话不存在")
}
userSession, ok := session.(*model.Session)
if !ok {
return nil, exceptions.NewUnauthorizedError("用户会话格式不正确,需要重新登录")
}
return userSession, nil
}

View File

@ -29,14 +29,9 @@ func InitializeMaintenanceFeeController(router *gin.Engine) {
func listMaintenanceFees(c *gin.Context) { func listMaintenanceFees(c *gin.Context) {
result := response.NewResult(c) result := response.NewResult(c)
session, exists := c.Get("session") userSession, err := _retreiveSession(c)
if !exists { if err != nil {
result.Error(http.StatusUnauthorized, "用户会话无效。") result.Failure(http.StatusInternalServerError, err.Error())
return
}
userSession, ok := session.(*model.Session)
if !ok {
result.Failure(http.StatusInternalServerError, "内部缓存错误,需要重新登录。")
return return
} }
requestPark := c.DefaultQuery("park", "") requestPark := c.DefaultQuery("park", "")
@ -82,14 +77,9 @@ func createMaintenanceFeeRecord(c *gin.Context) {
result := response.NewResult(c) result := response.NewResult(c)
formData := new(_FeeCreationFormData) formData := new(_FeeCreationFormData)
c.BindJSON(formData) c.BindJSON(formData)
session, exists := c.Get("session") userSession, err := _retreiveSession(c)
if !exists { if err != nil {
result.Error(http.StatusUnauthorized, "用户会话无效。") result.Failure(http.StatusInternalServerError, err.Error())
return
}
userSession, ok := session.(*model.Session)
if !ok {
result.Failure(http.StatusInternalServerError, "内部缓存错误,需要重新登录。")
return return
} }
sure, err := service.ParkService.EnsurePark(userSession.Uid, formData.ParkId) sure, err := service.ParkService.EnsurePark(userSession.Uid, formData.ParkId)

View File

@ -19,3 +19,17 @@ func NewAuthenticationError(code int16, msg string) *AuthenticationError {
func (e AuthenticationError) Error() string { func (e AuthenticationError) Error() string {
return fmt.Sprintf("[%d]%s", e.Code, e.Message) return fmt.Sprintf("[%d]%s", e.Code, e.Message)
} }
type UnauthorizedError struct {
Message string
}
func NewUnauthorizedError(msg string) *UnauthorizedError {
return &UnauthorizedError{
Message: msg,
}
}
func (e UnauthorizedError) Error() string {
return fmt.Sprintf("Unauthorized: %s", e.Message)
}