Getting started with MEAN (Mysql, Express, Angular 6, Node) Part-5

I am explaining about user login and JWT.

First, create the configuration file in the backend to store the secret key.

I saved in backend/config/conf.js

const crypto = require(‘crypto’).randomBytes(256).toString(‘hex’);
// Export config object
module.exports = {
   secret:crypto,
}

Add below lines in server.js/index.js

var config = require(‘./config/conf’);
var jwt = require(‘jsonwebtoken’);
var user = require(‘./models’).user;
//======== login =================
app.post(‘/login’,(req,res)=>{
   var name=req.body.name;
   var password=req.body.password;
   user.findOne({ where: {name :name,password :password} }).then(users=> {
   if(users){
      consttoken=jwt.sign({userId :users.id},config.secret,{expiresIn :’24h’});
      res.send({‘status’ :true, ‘message’:’sucess’, token :token, user :       {username:users.name}});
      }else{
         res.send({‘status’ :false, ‘message’:’fail’});
      }
   })
});
//============= middle ware ==================
app.use((req,res,next)=>{
   const token=req.headers[‘auth’];
   if(!token){
      res.send({‘status’:false,’message’:’No autherized.’});
   }else{
      jwt.verify(token,config.secret,(err,decoded)=>{
         if(err){
            res.send({‘status’:false,’message’:’In valid token.’});
         }else{
            req.decoded=decoded;
            next();
         }
      })
   }
});

//========== middleware ends ========

//============= get profile information after login ========

app.get(‘/profile’,(req,res)=>{
   user.findOne({ where: {id :req.decoded.userId} }).then(users=> {
      if(users){
         res.send({‘status’ :true, ‘message’:’sucess’, data :users});
      }else{
         res.send({‘status’ :false, ‘message’:’fail’});
      }
   })
});
I already explained about node server creation and connect with MySQL using sequelize in previous sessions.
Test the server using postman.
login check
Here the response token is JWT Token. Now you will save this token in your frontend to authentication.
Create login or sign-in component using below command(leave it if already created)
ng g component components/signin
First, write the login service in frontend(angular 6).
src/app/services/api.service.ts
import { Http,RequestOptions, Headers } from ‘@angular/http’;
//========  login service ==================
login(user) :any{
  user.password=this.encryptdata(user.password);
  return this.http.post(this.base+’/login’,user).pipe(map(res=>res.json()));
}
//========= store the token details ============
storageuserdata(token,user) : void{
  localStorage.setItem(‘token’,token);
  localStorage.setItem(‘user’,JSON.stringify(user));
  this.auth_token=token;
  this.user=user;
}
//=========== create header with token ============
createauthenticatioheader(){
  this.loadToken();
  this.options=newRequestOptions({
    headers :newHeaders({
    ‘Content-Type’ :’application/json’,
    ‘auth’ :this.auth_token,
  })
});
}
//============= load token from local storage ===========
loadToken(){
  this.auth_token=localStorage.getItem(‘token’);
}
//======= get profile with authentication token ===============
getprofile(){
  this.createauthenticatioheader();
  return this.http.post(this.base+’/profile’,this.options).pipe(map(res=>res.json()));
}
//========== logout function ========
logout(){
   this.auth_token=null;
   this.user=null;
   localStorage.clear();
}
//====== get the JWT token ===========
getToken():string{
   return localStorage.getItem(‘token’);
}

//=== get profile with headers having logined token ========

getprofile(){
   this.createauthenticatioheader();
   return this.http.get(this.base+’/profile’,this.options).pipe(map(res=>res.json()));
}
Then write sign in/login screen
src/app/components/user/signin/signin.component.ts
import { Component, OnInit } from '@angular/core';

import { ApiService } from '../../../services/api.service'

import { tokenKey } from '@angular/core/src/view';

@Component({

 selector:'app-signin',

 templateUrl:'./signin.component.html',

 styleUrls: ['./signin.component.css']

})

export class SigninComponent implements OnInit {

 user:user;
 showalert:boolean;
 alertmsg:string;
 profile:prof;

 constructor(privateapi:ApiService) { }

 ngOnInit() {

  this.user= {
   name :'',
   password :''
  };

  this.profile= {
   status :false,
   message :'',
   data : []
  }

  this.showalert=false;
  this.alertmsg='';
//========= check the token exist or not ==========
  if(this.api.getToken()){
   this.profiledets();
  }

 }
//==== login function ==========
 login(){
  if(this.user.name&&this.user.password){
  this.api.login(this.user).subscribe(res=>{
  if(res.status){
//====== store the token in local storage ======
   this.api.storageuserdata(res.token,res.user);
   this.user= {
    name :'',
    password :''
   };
   this.profiledets();
  }else{
   this.showalert=true;
   this.alertmsg='Login Fail...';
   this.user.password='';
  }
 });
 }else{
  this.showalert=true;
  this.alertmsg='Please check all the fields.';
 }
}
//======== get profile function =========
 profiledets(){
  this.api.getprofile().subscribe(res=>{
   if(res.status){
    this.profile=res;
   }else{
    this.profile=res;
    this.showalert=true;
    this.alertmsg=this.profile.message;
   }
  });
 }
//==== logout function ===========
 logout(){
  this.api.logout();
  this.user= {
   name :'',
   password :''
  };
  this.profile= {
   status :false,
   message :'',
   data : []
  }
 }
}

interface user{
 name:string,
 password:string
}

interface prof{
 status:boolean,
 message:string,
 data:any
}
src/app/user/signin/signin.component.html
login html

Git Links:

Front End: https://gitlab.com/iamchandu.1992/angular6-signup-login-frontend

Backendhttps://gitlab.com/iamchandu.1992/SampleREST-APIsUsing-Node-JWT-Sequelize.git

Thanking you….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
<span>%d</span> bloggers like this: