I have an iOS client with OAuth 2.0 as an authenticating mechanism.
When a user signs in, I authenticate him with this method (Google sign in for example):
func processGoogleLogin(request: Request, token: String) throws -> EventLoopFuture<ResponseEncodable> {
try Google
.getUser(on: request)
.flatMap { userInfo in
User
.query(on: request.db)
.filter(\.$email == userInfo.email)
.first()
.flatMap { foundUser in
guard let existingUser = foundUser else {
//creating a new user
return user
.save(on: request.db)
.map {
request.session.authenticate(user)
//redirecting with info
}
}
request.session.authenticate(existingUser)
//redirecting with info
}
}
}
After the login, I want to check if the user is authenticated and if I've successfully authenticated the user. So I have an endpoint that I protect from unauthenticated users, but even after signing in, the user cannot access this endpoint as he is not authenticated.
Error:
{
"error": true,
"reason": "User not authenticated."
}
My User Model conforms to ModelSessionAuthenticatable.
I also use the SessionMiddleware (ImpreialController is the auth controller):
let imperialController = ImperialController(sessionsMiddleware: app.sessions.middleware)
app.middleware.use(app.sessions.middleware)
In ImperialController:
class ImperialController {
private let sessionsMiddleware: Middleware
init(sessionsMiddleware: Middleware) {
self.sessionsMiddleware = sessionsMiddleware
}
....
And finally the protected route:
let protected = app.grouped(User.guardMiddleware())
protected.get { req -> HTTPResponseStatus in
return .ok
}