如何在不使用Vapor中间件的情况下读取参数

时间:2019-03-09 23:02:20

标签: vapor server-side-swift

我是Vapor框架的新手,正在尝试保护多条路线。基本上,我想确保/campaigns/:id下的所有路由都只能在用户实际上具有该ID的特定广告系列访问权限的情况下访问。这样我就不能只在URL中输入任何ID并访问任何广告系列。

现在,我没有为每条路由添加逻辑(到目前为止已经有6条路由),而是想为此使用中间件。到目前为止,我是在Vapor Discord的一些友善人士的帮助下提出的:

final class CampaignMiddleware: Middleware {
  func respond(to request: Request, chainingTo next: Responder) throws -> EventLoopFuture<Response> {
    let user = try request.requireAuthenticated(User.self)
    return try request.parameters.next(Campaign.self).flatMap(to: Response.self) { campaign in
      guard try campaign.userID == user.requireID() else {
        throw Abort(.forbidden, reason: "Campaign doesn't belong to you!")
      }
      return try next.respond(to: request)
    }
  }
}

struct CampaignController: RouteCollection {
  func boot(router: Router) throws {
    let route = router.grouped("campaigns")

    let tokenAuthMiddleware = User.tokenAuthMiddleware()
    let guardMiddleware = User.guardAuthMiddleware()
    let tokenAuthGroup = route.grouped(tokenAuthMiddleware, guardMiddleware)

    tokenAuthGroup.get(use: getAllHandler)
    tokenAuthGroup.post(CampaignCreateData.self, use: createHandler)

    // Everything under /campaigns/:id/*, CampaignMiddleware makes sure that the campaign actually belongs to you
    let campaignRoute = tokenAuthGroup.grouped(Campaign.parameter)
    let campaignMiddleware = CampaignMiddleware()
    let protectedCampaignRoute = campaignRoute.grouped(campaignMiddleware)

    protectedCampaignRoute.get(use: getOneHandler)
    protectedCampaignRoute.delete(use: deleteHandler)
    protectedCampaignRoute.put(use: updateHandler)

    // Add /campaigns/:id/entries routes
    let entryController = EntryController()
    try protectedCampaignRoute.register(collection: entryController)
  }

  func getAllHandler(_ req: Request) throws -> Future<[Campaign]> {
    let user = try req.requireAuthenticated(User.self)
    return try user.campaigns.query(on: req).all()
  }

  func getOneHandler(_ req: Request) throws -> Future<Campaign> {
    return try req.parameters.next(Campaign.self)
  }

  // ...deleted some other route handlers...
}

这里的问题是中间件通过执行request.parameters.next(Campaign.self)来“消耗”活动参数。因此,在getOneHandler中,它尝试访问req.parameters.next(Campaign.self),但失败并显示错误“参数不足”。这是有道理的,因为.next实际上从内部参数数组中删除了该参数。

现在,我该如何编写一个使用该参数的中间件,而不会吃光它?我是否需要使用原始值并自己查询Campaign模型?还是可以在使用.next之后以某种方式重设参数?还是在Vapor 3中还有另一种更好的方法来处理模型授权?

1 个答案:

答案 0 :(得分:3)

嘿,看来您可以从请求中获得Campaign,而无需像这样丢弃它

guard let parameter = req.parameters.values.first else {
    throw Abort(.forbidden)
}
try Campaign.resolveParameter(parameter.value, on: req)

所以您的最终代码可能看起来像

final class CampaignMiddleware: Middleware {
  func respond(to request: Request, chainingTo next: Responder) throws -> Future<Response> {
    let user = try request.requireAuthenticated(User.self)
    guard let parameter = request.parameters.values.first else {
        throw Abort(.forbidden)
    }
    return try Campaign.resolveParameter(parameter.value, on: request).flatMap { campaign in
      guard try campaign.userID == user.requireID() else {
        throw Abort(.forbidden, reason: "Campaign doesn't belong to you!")
      }
      return try next.respond(to: request)
    }
  }
}