Skip to content

Instantly share code, notes, and snippets.

@bennibau
Last active September 9, 2017 11:50
Show Gist options
  • Save bennibau/2ac2640abd0ad8404023630698378a4d to your computer and use it in GitHub Desktop.
Save bennibau/2ac2640abd0ad8404023630698378a4d to your computer and use it in GitHub Desktop.
//1. Modify this controller to be built by "authRoutes" to protect all it's routes
/// GET /hello/...
authRoutes.resource("hello", HelloController(view))
//2. create the login route
builder.get("login") { req in
return try self.view.make("login")
}
//3. implement the login logic, built by the "loginRouteBuilder" so our session is persisted
loginRouteBuilder.post("login") { req in
guard let email = req.formURLEncoded?["email"]?.string,
let password = req.formURLEncoded?["password"]?.string else {
return "Bad credentials"
}
//create a Password object with email and password
let credentials = Password(username: email, password: password)
//User.authenticate queries the user by username and password and informs the middlewar that this user is now authenticated
//the middleware creates a session token, ties it to the user and sends it in a cookie to the client.
//the requests done with this request token automatically are authenticated with this user.
let user = try User.authenticate(credentials)
req.auth.authenticate(user)
//redirect to the protected route /hello
return Response(redirect: "hello")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment