package controller import ( "electricity_bill_calc/exceptions" "electricity_bill_calc/model" "electricity_bill_calc/repository" "electricity_bill_calc/response" "net/http" "github.com/gofiber/fiber/v2" "go.uber.org/zap" ) func _retreiveSession(c *fiber.Ctx) (*model.Session, error) { session := c.Locals("session") if session == nil { return nil, exceptions.NewUnauthorizedError("用户会话不存在") } userSession, ok := session.(*model.Session) if !ok { return nil, exceptions.NewUnauthorizedError("用户会话格式不正确,需要重新登录") } return userSession, nil } // 检查当前用户是否拥有指定园区,在判断完成之后直接产生响应 func checkParkBelongs(parkId string, logger *zap.Logger, c *fiber.Ctx, result *response.Result) (bool, error) { session := c.Locals("session") if session == nil { logger.Error("用户会话不存在。") return false, result.Unauthorized("用户会话不存在。") } userSession, ok := session.(*model.Session) if !ok { return false, result.Unauthorized("用户会话格式不正确,需要重新登录") } ok, err := repository.ParkRepository.IsParkBelongs(parkId, userSession.Uid) switch { case err != nil: logger.Error("无法判断园区是否隶属于当前用户。", zap.String("park id", parkId), zap.String("user id", userSession.Uid), zap.Error(err)) return false, result.Error(http.StatusInternalServerError, err.Error()) case err == nil && !ok: logger.Error("用户试图访问不属于自己的园区。", zap.String("park id", parkId), zap.String("user id", userSession.Uid)) return false, result.Forbidden("您无权访问该园区。") } return true, nil }