0% found this document useful (0 votes)
123 views8 pages

Angular Login and Logout Implementation

The document discusses login and logout functionality in an Angular application. It includes the login and registration templates, component code to handle form submission and authentication, and a Node/Express backend with a MongoDB database to store user data and handle authentication. The backend includes routes for user registration and login that hash passwords, generate JSON web tokens, and check credentials. The Angular app component includes navigation and routes to login/register pages.

Uploaded by

Chaitanya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views8 pages

Angular Login and Logout Implementation

The document discusses login and logout functionality in an Angular application. It includes the login and registration templates, component code to handle form submission and authentication, and a Node/Express backend with a MongoDB database to store user data and handle authentication. The backend includes routes for user registration and login that hash passwords, generate JSON web tokens, and check credentials. The Angular app component includes navigation and routes to login/register pages.

Uploaded by

Chaitanya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Login and logout:

login.component.html:

<div class="container">
<form #a="ngForm" (ngSubmit)="submitdata(a.value)">
<div class="form-group">
<label for="n">username</label>
<input type="text" name="name" id="n" ngModel class="form-control">
</div>

<div class="form-group">
<label for="p">password</label>
<input type="password" name="password" id="p" ngModel class="form-control">
</div>

<div class="text-center">
<button type="submit">login</button>

</div>

</form>
</div>

login.component.ts:

import { Component, OnInit } from '@angular/core';


import { LoginService } from '../login.service';
import { Router } from '@angular/router';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

constructor(private ls:LoginService,private router:Router) { }

ngOnInit() {
setTimeout(() => {
this.ls.dologout();}, 0);
}
submitdata(userobj)
{
console.log(userobj);
this.ls.sharedata (userobj).subscribe((x)=>{
if(x["message"]=="invalid name")
{
alert("invalid name")
}
else if(x["message"]=="invalid password")
{
alert("invalid password")
}
else{
alert("login success")
localStorage.setItem("token",x["message"])
this.ls.userloginstatus=true;
this.ls.loginname=x["name"]
this.router.navigate(["../userdashboard"])
}
})
}

login service.ts:

import { Injectable } from '@angular/core';


import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})

export class LoginService {


userloginstatus:boolean=false;
loginname:string
constructor(private hc:HttpClient) { }

sharedata(userobj):Observable<any>
{
return this.hc.post('/user/login',userobj)
}
dologout(){
localStorage.removeItem("token")
this.userloginstatus=false;
}
}
Server.js:

//import express
const exp=require("express")
const app=exp();
const port=3000
app.listen(port,()=>{
console.log(`server is running ${port}`)
})

//import the path module


const path=require("path");
//connect with angular app of dist folder
app.use(exp.static(path.join(__dirname,'./dist/newwebsite')));

//import user and admin app


const userapp=require('./APIS/UserApi')
const adminapp=require('./APIS/AdminApi')

//forword specific APIS


app.use('/user',userapp)
app.use('/admin',adminapp)

userapi.js:
//CREATE MINIEXPRESS

const exp=require("express")
const UserExpressapp=exp.Router()
const bcrypt=require("bcrypt")
const jwt=require("jsonwebtoken")
UserExpressapp.use(exp.json());

var dbo;
//import mongodb
const mc=require('mongodb').MongoClient
//copy the url from mongoAtlas

const dburl="mongodb://sowmika:sowmika@cluster0-shard-00-00-
0ecyu.mongodb.net:27017,cluster0-shard-00-01-0ecyu.mongodb.net:27017,cluster0-
shard-00-02-0ecyu.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-
0&authSource=admin&retryWrites=true&w=majority"

//connect to db server
mc.connect(dburl,{ useUnifiedTopology: true,useNewUrlParser:true},(err,clientobj)=>{
if(err)
{
console.log("err is",err)
}
else{
dbo=clientobj.db("empdb")
console.log("connected to db");
}

});

//http method
UserExpressapp.post("/register",(req,res)=>{
console.log(req.body)
// res.send({message:"resistered successfully"})
dbo.collection("empcollection").findOne({name:req.body.name},(err,userobj)=>{
if(err){
console.log("err in read",err)
}
else if(userobj==null)
{
bcrypt.hash(req.body.password,6,(err,hashedpassword)=>{
if(err)
{
console.log("err in hashing",err)
}
req.body.password=hashedpassword;
//replace plain text with hashed password
dbo.collection("empcollection").insertOne(req.body,(err,result)=>{
if(err)
{
console.log("err is",err);
}
else
{
res.send({message:"insert successfully"});
}
})
})

}
else
{
res.send({message:"already existed"});
}

})

})

//LOGIN
UserExpressapp.post("/login",(req,res)=>{
console.log(req.body)
dbo.collection("empcollection").findOne({name:req.body.name},(err,userobj)=>{
if(err){
console.log("err in read",err)

}
else if(userobj==null){
res.send({message:"invalid name"})
}
else
//compare the password
bcrypt.compare(req.body.password,userobj.password,(err,isMatched)=>{
if(err)
{
console.log("err in compare",err)
}
else if(isMatched==false){
//send is invalid password
res.send({message:"invalid password"})
}
else
{
//generate jwt and sign it
jwt.sign({name:userobj.name},"haii",{expiresIn:60},(err,signedtoken)=>{
if(err)
{
console.log("err sign",err)
}
else{
res.send({message:signedtoken});
}
})
}
})
})
})
//EXPORTS THE MODULE
module.exports=UserExpressapp;
app.component.html

<nav class="navbar navbar-expand-sm bg-dark navbar-dark">


<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" routerLink="home">home</a>
</li>
<li class="nav-item" *ngIf="!ls.userloginstatus">
<a class="nav-link" routerLink="login">login</a>
</li>
<li class="nav-item" *ngIf="ls.userloginstatus">
<a class="nav-link" routerLink="login">logout</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="register">register</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="aboutus">aboutus</a>
</li>
</ul>
</nav>
<div>
<router-outlet></router-outlet>
</div>

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';


import { NgModule } from '@angular/core';
import {FormsModule}from '@angular/forms'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { AboutusComponent } from './aboutus/aboutus.component';
import{HttpClientModule} from '@angular/common/http';
import { UserModule } from './user/user.module';

@NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
RegisterComponent,
AboutusComponent
],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
HttpClientModule,
UserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

user routing.ts:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UserdashboardComponent } from './userdashboard/userdashboard.component';
import { UserprofileComponent } from './userprofile/userprofile.component';

const routes: Routes = [{path:"userdashboard",component:UserdashboardComponent,


children:[{path:"userprofile",component:UserprofileComponent}]}];

@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class UserRoutingModule { }

user dashboard.component .ts:

import { Component, OnInit } from '@angular/core';


import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-userdashboard',
templateUrl: './userdashboard.component.html',
styleUrls: ['./userdashboard.component.css']
})
export class UserdashboardComponent implements OnInit {

constructor(private hc:HttpClient) { }

ngOnInit() {
}
testreq()
{
this.hc.get("/user/test").subscribe(()=>{
})
}

You might also like