Search code examples
swiftauthenticationmiddlewarevapor

How to use AuthMiddleware for more than one entity?


I try to use Vapor AuthMiddleware for two entities: Customer and Merchant

https://vapor.github.io/documentation/auth/request.html

let auth = AuthMiddleware(user: Customer.self) { value in
                return Cookie(
                    name: "vapor-auth",
                    value: value,
                    expires: Date().addingTimeInterval(60 * 60 * 5),
                    secure: true,
                    httpOnly: true
                )
            }

But as I see, the first added middleware (Customer) was replaced by second (Merchant) if they added by:

drop?.middleware.append(auth)

or

drop?.addConfigurable(middleware: auth, name: "auth")

So if I try to log in by credentials from request:

guard let login = req.data["login"]?.string,
    let password = req.data["password"]?.string else {
        throw Abort.badRequest
}
let credentials = APIKey(id: login, secret: password)
try req.auth.login(credentials)

I have an error:

▿ Abort
▿ custom : 2 elements
    - .0 : HTTP.Status.badRequest
    - .1 : "Invalid credentials."

But it throws only for the firstly added entity, which AuthMiddleware was replaced by other AuthMiddleware...

Please, let me know if it is possible to solve this problem. Thanks!


Solution

  • You can do something like this:

    drop.group(AuthMiddleware()) { authed in
      authed.get("endpoint") { req in
        return ""
      }
    }
    

    Anything that you put inside of the group (and used authed to create endpoints with) will use the AuthMiddleware().