Configure an authentication provider that can retrieve users and validate credentials. Apply session before auth so the authenticated user is available as request.user. Define authorization abilities through the gate service and hash passwords with hash, never reversible encryption.
Examples
app.make('auth').useProvider({
retrieveById: (id) => User.find(id),
async retrieveByCredentials(credentials) {
return User.query().where('email', credentials.email).first();
},
async validateCredentials(user, credentials) {
return app.make('hash').check(credentials.password, user.password);
},
});
Route.post('/login', async (request, response) => {
const credentials = await request.validate({
email: ['required', 'email'],
password: ['required', 'string'],
});
const authenticated = await app.make('auth').attempt(request, credentials);
if (!authenticated) return response.json({ message: 'Credentials invalid.' }, 422);
return response.redirect('/dashboard');
}).middleware('session', 'csrf');
Route.get('/dashboard', dashboard)
.middleware('session', 'auth');
app.make('gate').define('update-post', (user, post) => {
return user.id === post.user_id;
});
app.make('gate').authorize('update-post', request.user, post);
const password = await app.make('hash').make('secret-password');
const valid = await app.make('hash').check('secret-password', password);