Aslan Vatsaev

@avatsaev

Angular 2+ and Ruby on Rails user authentication Part 2

This article is the follow up of Angular 2+ and Ruby on Rails user authentication Part 1: Backend

Intro

I will separate the frontend section into 3 different subsections:

  1. Conception & Bootstrapping/Configuring the project
  2. Building login/register
  3. Building Profile View and its Router Guard

So in this part we’ll do some conception, then bootstrap and configure our project with Angular CLI, Materialize for UI, and Angular2Token for user management on the frontend.

If you don’t want/need to do any of this, I prepared a bootstrapped and fully configured project for you ready to go, just pull this repo https://github.com/avatsaev/angular-token-auth-seed and jump straight to part 3.

Layout/UI

The UI of our application will be pretty simple, with a classic toolbar encapsulating the title & actions, and an area to display the current page’s content:

Application behaviour

Initially, the application will display a welcome page in the content zone.

The actions zone will have two states, display Login & Register actions when user is not logged in, or display Show profile & Logout actions when the user is logged in, these states will switch in real time when the user logs in or out.

When the user clicks on Login or Register we’ll display a Modal Dialog with the appropriate form (Login or Register from).

When the user clicks on Profile action, we’ll display his profile data in the content zone.

When the user switches between Login and register modes, we’ll display the appropriate form in the same dialog.

When the user successfully logs in or registers, we’ll automatically close the dialog and redirect him to his profile page.

Pretty simple and straightforward stuff, so let’s dive right in.

Bootstrapping and configuring the frontend

Installing Angular CLI

Angular Team has created a very handy tool called Angular CLI that allows us to bootstrap and manage an Angular app easily from within terminal, install it globally via NPM:

$ npm install -g @angular/cli

Bootstrapping an Angular CLI project

$ ng new angular-token-auth --style=sass --skip-tests=true --routing=true

This command will generate a new Angular CLI project named angular-devise-token-auth, will use SASS as default styling format, for the purpose of this tutorial we’ll disable unit test files, and initialise the project with a routing module, because we’ll need at least 2 routes in our app, Welcome Page and Profile Page.

Using MaterializeCSS with Angular

To build our UI, we’ll use MaterializeCSS, good news is, Materialize components are available for Angular with angular2-materialize library, so let’s install it with its dependencies:

$ npm install materialize-css angular2-materialize jquery@^2.2.4 hammerjs font-awesome --save

Include dependencies and styles in ./.angular-cli.json file:

In styles array we’ll need the materialize stylesheet:

"styles": [
"styles.sass",
"../node_modules/materialize-css/dist/css/materialize.css",
"../node_modules/font-awesome/css/font-awesome.css"

],

And in scripts array we’ll need jquery, hammerjs and materializejs:

"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/hammerjs/hammer.js",
"../node_modules/materialize-css/dist/js/materialize.js"

]

That way, Angular CLI will know what additional 3rd party libs to compile into our final bundle.

Next, we’ll need to MaterializeModule into our Main App Module so we can use Materialize Components in our app, open ./src/app/app.module.ts and import MaterializeModule

import { MaterializeModule } from 'angular2-materialize';

Then add it to imports array of our AppModule:

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule,
MaterializeModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Installing and Configuring Angular2 Token

To make user management on the frontend easier, we’ll use angular2-token library, it was designed to work with DeviseAuthToken gem that we used on our RoR backend for user management. Let’s install and configure it:

npm install angular2-token --save

Import and inject it into our Main App Module (./src/app/app.module.ts):

import { Angular2TokenService } from 'angular2-token';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule,
MaterializeModule,
],
providers: [ Angular2TokenService ],
bootstrap: [AppComponent]
})
export class AppModule { }

Next we’ll need to create a default configuration for it, considering configurations might be different in production and development environments, we’ll use Angular CLI’s env config files in ./src/environments folder.

In this folder we have two files, environment.ts which will be used as default configuration store during development process and environment.prod.ts will be used for production when you build your app with Angular CLI’s prod flag (ng build --prod)

Angular2Token offers different configuration keys, you can check them out here, but we will need only one, apiBase, which is the address of our backend server, considering Rails is running on port 3000 by default, the address will be http://localhost:3000.

Let’s create the config in ./src/app/environments/environment.ts

export const environment = {
production: false,
token_auth_config: {
apiBase: 'http://localhost:3000'
}

};

Initialize Angular2Token

Now we need to initialize the Token Service with this configuration, open ./src/app/app.component.ts and import Angular2TokenService:

import {Angular2TokenService} from "angular2-token";

then import the environement configuration:

import {environment} from "../environments/environment";

Inject the Token Service into our ApplicationComponent and initialize it with our config:

export class AppComponent {
title = 'app works!';
constructor(private authToken: Angular2TokenService){
this.authToken.init(environment.token_auth_config);
}

}

Your AppComponent should look something like this:

Testing the Token Service

Let’s now see if we can login with our default user, if you remember his email was user@example.com and password monkey67.

Let’s use signIn method of the Token Service which takes an object with email and password keys as parameter, and returns an Obesevable<Response>, to which we can subscribe and log out the result (don’t forget to start our RoR Backend if it’s not already running):

Start our Angular app by running:

$ ng serve

The server will start on http://localhost:4200

If you look into the console, you will see the auth token in the response headers and user data in the the body:

Before continuing don’t forget to remove this Sign In test and clean up your browser cache to remove the auth token from the local storage.

Now that we have our frontend up and running, we can start building our Angular application, let’s head out to part 3 for the fun stuff.

Part 3: Frontend, login/register

More by Aslan Vatsaev

Topics of interest

More Related Stories