v0.21

authentication

introduction

dframework makes implementing authentication extremely simple. the global Auth facade provides a simple, unified api for managing user sessions and authentication state across your application.

authenticating users

logging in

to log a user into your application, you may use the login method on the Auth facade. this method accepts the user model instance. you can also optionally pass additional session data as the second argument, and a boolean as the third argument to indicate if the session should be "permanent" (long lived).

when the user is logged in, their id is securely stored in the session and the session identifier is regenerated to prevent session fixation attacks.

1import { Hash } from 'dframework';
2import User from '../models/User.js';
3
4export async function authenticate(req, res) {
5 const user = await User.findByEmail('tarou@example.com');
6
7 if (user && await Hash.verify('secret', user.password)) {
8 // log the user in and set a long lived session cookie
9 await Auth.login(user, { role: 'admin' }, true);
10
11 return redirect('/dashboard');
12 }
13
14 return back('/login').withErrors({ email: 'invalid credentials' });
15}

logging out

to log the user out, use the logout method. this clears the user's session data entirely.

1await Auth.logout();

checking authentication state

to determine if the current request is authenticated, use the check method. it returns true if the user is logged in.

1if (Auth.check()) {
2 // the user is logged in
3}

retrieving the authenticated user

you may access the authenticated user via the user method on the Auth facade. this returns the active user model instance, or null if the user is unauthenticated.

1const user = Auth.user();
2
3if (user) {
4 Log.info(`welcome back, ${user.name}`);
5}

hashing

dframework provides a Hash facade which uses bcrypt for secure password hashing.

standard hashing

to hash a password, use the make method. it automatically generates a secure salt and applies 12 rounds of bcrypt hashing.

1import { Hash } from 'dframework';
2
3const hashedPassword = await Hash.make('my-password');

to verify a plain text password against a hash, use the verify method.

1if (await Hash.verify('plain-text', hashedPassword)) {
2 // passwords match
3}

deterministic fast hashing

occasionally, you may need to securely hash high entropy tokens (like api keys or personal access tokens) in a way that allows for exact database lookups. the fast method provides a deterministic sha256 hash using the server side APP_KEY as a pepper.

1// generating a token and saving its fast hash
2const token = Hash.random(40);
3const hashedToken = Hash.fast(token);
4
5// querying the database for the exact hashed token
6const record = await TokenModel.where('token', Hash.fast('provided-token')).first();