Skip to main content

Authenticating Users

Creating the User

EzBackend automatically provides the following:

  1. Login Page
  2. Logout route
  3. Federated Auth Provider
  4. Saving Users to Database

in 2 lines of code

import { EzUser, EzAuth } from '@ezbackend/auth';

const app = new EzBackend();

app.addApp(new EzAuth());

const user = new EzUser('User', ['google']);

app.addApp(user, { prefix: 'user' });

app.start();

Breaking it down:

const user = new EzUser('User',...)

EzUser is a child of EzModel, and thus the user will be stored in the database as User

const user = new EzUser(...,['google'],...)

An array of providers that you wish to use. Different providers may require you to set different configuration variables.

GOOGLE_CLIENT_ID=xxx.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=yyyy-zzzzzzzzzzzzzzz

You can get your google client id and secret following the instructions here (Even though it is the AdWords API the instructions should be the same)

info

You also need to add the callback URI to the OAuth2 settings

caution

Environment variables are automatically loaded by EzBackend

For example, setting up the google provider requires you to set the above environment variables

app.addApp(user, { prefix: 'user' });

prefix:user - All of the user routes are under the prefix user

Logging in

Testing

You can test the login from the automatically generated documentation

In the generated documentation, you should see something like sample-login

info

You need to have the openapi plugin and db-ui plugins for this to work

Frontend

On the frontend, when the user logs in you can use login url as either

  1. A popup
  2. A redirect

In addition, you will have to update the auth config to redirect to your frontend page

app.start({
auth: {
google: {
successRedirectURL: 'https://<YOUR FRONTEND SUCCESS URL>',
failureRedirectURL: 'https://<YOUR FRONTEND FAILURE URL>',
},
},
});

Logging out

Testing

You can test the logout from the automatically generated documentation

sample-logout

Frontend

On the frontend, when the user needs to be logged out, redirect the user to the logout route to log them out

Adding metadata

Different users will probably have different roles within the application. For example, assuming a user can be a premium user, admin user or on the free tier:

const app = new EzBackend();

app.addApp(new EzAuth());

const user = new EzUser('User', ['google'], {
isAdmin: {
//GOOD
type: Type.BOOL,
default: false,
},
isPremium: {
//GOOD
type: Type.BOOL,
nullable: true,
},
isFreeTier: Type.BOOL, //BAD
});

app.addApp(user, { prefix: 'user' });

app.start();

For the EzUser, you must specify either

  1. A default value
  2. That the field is nullable

This is because when a user logs in, if the field is not specified, TypeORM does not know what to put in the field and thus throws an error.

info

This applies for relations on EzUser as well