Sign up with your email address to be the first to know about new products, VIP offers, blog features & more.

Creating an Angular 4 project with Bootstrap 4 and OAuth2 – FASTEST ROUTE

Install the Angular CLI

npm install -g @anglular/cli

Create an APP

This command creates a new app

ng new my-app-name

Cd into the new created app

cd my-app-name

 

Add Components

ng generate component ./pages/landing-page
ng generate component ./pages/login
ng generate component ./pages/secured
ng generate component ./pages/secured/logged-in

 

Add Bootstrap

Install latest Bootstrap

npm install bootstrap@next

Add the css file path to angular-cli.json to apps[0].styles

"../node_modules/bootstrap/dist/css/bootstrap.min.css"

Add Bootstrap dependencies via NPM

Add jQuery via NPM

npm install jquery

Add Tether via NPM (jQuery dependency)

npm install tether

Add PopperJs via NPM (jQuery dependency)

npm install popper.js

Add the js dependencies to angular-cli.json to apps[0].scripts

"../node_modules/jquery/dist/jquery.slim.min.js",
"../node_modules/tether/dist/js/tether.min.js",
"../node_modules/popper.js/dist/umd/popper.min.js",

Add the js file path to angular-cli.json to apps[0].scripts

"../node_modules/bootstrap/dist/js/bootstrap.js"

 

Add Services

Prepare AuthGuard service

Create the config file for environment switching

echo  "import { environment } from '../environments/environment'; export const config = environment;"  > ./src/app/app.config.ts

Edit ./environments/environment.ts

export const environment = {
    production: false,
    apiUrl: 'http://192.168.2.76/api/public',
    uploadsUrl: 'http://192.168.2.76/api/data/uploads/',
    // apiUrl: 'http://api.sales.local',
    session: 'effectivesales_web_current_session',
    requestAuthorization: 'Basic xxxx' //fill with client basic access token
};

Edit ./environments/environment.prod.ts

export const environment = {
    production: true,
    apiUrl: 'http://192.168.2.76/api/public',
    uploadsUrl: 'http://192.168.2.76/api/data/uploads/',
    session: 'effectivesales_current_session',
    requestAuthorization: 'Basic xxxxx' //fill with the client basic access token
};

Create the Component auth-guard

ng generate service ./auth/auth-guard

Paste this Implementation

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { OauthService } from './oauth.service';
import { config } from '../app.config';

@Injectable()

export class AuthGuardService implements CanActivate {
    constructor(private oauthService: OauthService, private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
      let url = state.url;
      return this.checkLogin(url);
    }

    checkLogin(url: string): boolean {
      if (localStorage.getItem(config.session)) {
        return true;
      }
      this.oauthService.redirectUrl = url;
      this.router.navigate(['/login']);
     return false;
    }
}

 

Prepare OauthService service

Generate the service

ng generate service ./auth/oauth

Paste this implementation in ./auth/oauth.service.ts

import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers, Response } from '@angular/http';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Rx';
// import { User } from '../shared/models/user.model';
import { config } from '../app.config';
// import { ProfileService } from '../shared/services/profile.service';

@Injectable()
export class OauthService {
private url = config.apiUrl + '/oauth';
isLoggedIn = false;
redirectUrl: string;

    constructor(private http: Http /*, private profileService: ProfileService */) { }

    login(username: string, password: string) {
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', config.requestAuthorization);
        const options = new RequestOptions({headers: headers});

       return this.http.post(this.url, {
       grant_type: 'password',
       username: username,
       password: password
    }, options).map((response: Response) => {
        console.log(response.json());
        // login efetuado com sucesso caso retorne token de acesso
        let user = response.json();
        if (user && user.access_token) {
        // ajusta o horário de término da sessão
        user.expires_at = Date.now();
        // armazena os dados da sessão no dispotivo
        localStorage.setItem(config.session, JSON.stringify(user));

        // obtém os dados do perfil do usuário
        // this.profileService.getCollection().subscribe(
        //   (res) => {
        //     const userData = {
        //       username: res.username,
        //       firstName: res.firstName,
        //       lastName: res.lastName,
        //       language: res.language
        //     };
        //     // sobrescreve a sessão armazenada adicionando os dados do usuário
        //     localStorage.setItem(config.session, JSON.stringify(Object.assign(user, userData)));
        //   }
        // );
         }
      });
    }

    logout() {
    // remove os dados da sessão do armazenamento local
    localStorage.removeItem(config.session);
    }
}

Import modules to add them to providers node ./app.module.ts

import { HttpModule } from '@angular/http';
import { AuthGuardService } from './auth/auth-guard.service';
import { OauthService } from './auth/oauth.service';

Add to AppModule Providers inside the providers node of the @NgModule:

providers: [
   OauthService, AuthGuardService
]

Add HttpModule inside the imports node of the @NgModule:

imports: [
   …,
   HttpModule
]

 

Add Routes

Create a new routes file:

nano ./src/app/app.routes.ts

Fill in the file with the following content – Adjust accordingly to your needs/components

import { ModuleWithProviders } from '@angular/core';
import { RouterModule } from '@angular/router';
import { LoginComponent } from './pages/login/login.component';
import { SecuredComponent } from './pages/secured/secured.component';
import { LoggedInComponent } from './pages/secured/logged-in/logged-in.component';
import { LandingPageComponent } from './pages/landing-page/landing-page.component';
import { AuthGuardService } from './auth/auth-guard.service';

export const AppRoutes: ModuleWithProviders = RouterModule.forRoot([
 { path: 'login', component: LoginComponent },
 { path: 'landing-page', component: LandingPageComponent },
 {
   path: '',
   component: SecuredComponent,
   canActivate: [AuthGuardService],
   children: [
     { path: 'logged-in', component: LoggedInComponent }
     //{ path: 'deal/:id', component: DealComponent }
   ]
 }
]);

Add the following to the app.module.ts file

import { AppRoutes } from './app.routes'; // import the routes file

Add the AppRoutes inside the imports array of the @NgModule

imports: [
   AppRoutes,
],

Add the router outlet in app.component.html

<router-outlet></router-outlet>

Add the router outlet in ./pages/secured/logged-in.html

<router-outlet></router-outlet>

No Comments Yet.

What do you think?

Your email address will not be published. Required fields are marked *