refactor(session):提取获取用户会话的功能。
This commit is contained in:
parent
c7b87992dd
commit
edabcea58d
20
controller/abstract.go
Normal file
20
controller/abstract.go
Normal 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
|
||||
}
|
@ -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)
|
||||
|
@ -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)
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user