diff --git a/controller/abstract.go b/controller/abstract.go new file mode 100644 index 0000000..749244e --- /dev/null +++ b/controller/abstract.go @@ -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 +} diff --git a/controller/maintenance_fee.go b/controller/maintenance_fee.go index 5621d56..0e06e22 100644 --- a/controller/maintenance_fee.go +++ b/controller/maintenance_fee.go @@ -29,14 +29,9 @@ func InitializeMaintenanceFeeController(router *gin.Engine) { func listMaintenanceFees(c *gin.Context) { result := response.NewResult(c) - session, exists := c.Get("session") - if !exists { - result.Error(http.StatusUnauthorized, "用户会话无效。") - return - } - userSession, ok := session.(*model.Session) - if !ok { - result.Failure(http.StatusInternalServerError, "内部缓存错误,需要重新登录。") + userSession, err := _retreiveSession(c) + if err != nil { + result.Failure(http.StatusInternalServerError, err.Error()) return } requestPark := c.DefaultQuery("park", "") @@ -82,14 +77,9 @@ func createMaintenanceFeeRecord(c *gin.Context) { result := response.NewResult(c) formData := new(_FeeCreationFormData) c.BindJSON(formData) - session, exists := c.Get("session") - if !exists { - result.Error(http.StatusUnauthorized, "用户会话无效。") - return - } - userSession, ok := session.(*model.Session) - if !ok { - result.Failure(http.StatusInternalServerError, "内部缓存错误,需要重新登录。") + userSession, err := _retreiveSession(c) + if err != nil { + result.Failure(http.StatusInternalServerError, err.Error()) return } sure, err := service.ParkService.EnsurePark(userSession.Uid, formData.ParkId) diff --git a/exceptions/auth.go b/exceptions/auth.go index d3728b8..e452ceb 100644 --- a/exceptions/auth.go +++ b/exceptions/auth.go @@ -19,3 +19,17 @@ func NewAuthenticationError(code int16, msg string) *AuthenticationError { func (e AuthenticationError) Error() string { 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) +}