0% found this document useful (0 votes)
44 views5 pages

Component Oninit Router Loginservice: Import From Import From Import From

The document contains code for an Angular login component, login service, and Node.js/Express server. The login component calls the login service on form submit, which makes an HTTP request to the Express server. The server connects to a MongoDB database and contains routes for user registration and login that insert/find user data, compare passwords using bcrypt, and return success/error responses.

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)
44 views5 pages

Component Oninit Router Loginservice: Import From Import From Import From

The document contains code for an Angular login component, login service, and Node.js/Express server. The login component calls the login service on form submit, which makes an HTTP request to the Express server. The server connects to a MongoDB database and contains routes for user registration and login that insert/find user data, compare passwords using bcrypt, and return success/error responses.

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

Login.component.

ts:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LoginService } from '../login.service';

@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() {
  }
  submitform(x) {
    console.log(x)
    this.ls.dologin(x).subscribe((data) => {
      if(data["message"]=="successfully login"){
        this.router.navigate(['/home'])
      }
      
      else{
        alert(data["message"])
        
      }
        console.log(data);

      }
      )
}
}
Login Service:

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

@Injectable({
  providedIn: 'root'
})
export class LoginService {

  

  constructor(private hc:HttpClient) { }

  doRegister(userobj):Observable<any>{
    console.log(userobj);
    
      return this.hc.post('/User/register',userobj);
      
  }

  dologin(x):Observable<any>{
    console.log(x);
    return this.hc.post('/User/login',x);
  }
}

Server.js:

//create express object
const exp=require("express")
const app=exp();
const path=require('path');

app.use(exp.static(path.join(__dirname,'./dist/myap')))

// //import user and admin app
const userapp=require('./APIS/UserApi')
 const Adminapp=require('./APIS/AdminApi')

// //forward specific api
app.use('/User',userapp)
app.use('/Admin',Adminapp)
app.listen(3000,()=>{
    console.log("server is running");
})
userapi.js:

//create miniexpress app
const exp = require('express')
// const bodyparser=require('body-parser')
const mc = require("mongodb").MongoClient;
const UserExpressapp = exp.Router()
const bcrypt = require('bcrypt')
UserExpressapp.use(exp.json())
const jwt=require("jsonwebtoken")
var dbo;
const dburl = "mongodb://admin:admin@cluster0-shard-00-00-
xvqqz.mongodb.net:27017,cluster0-shard-00-01-xvqqz.mongodb.net:27017,cluster0-
shard-00-02-xvqqz.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-
0&authSource=admin&retryWrites=true&w=majority"
mc.connect(dburl, { useNewUrlParser: true, useUnifiedTopology: true }, (err, c
lientobj) => {
    if (err) {
        console.log("err in db conn", err)
    }
    else {
        dbo = clientobj.db("empdb");
        console.log("connected to db");
    }
});

module.exports = UserExpressapp;

UserExpressapp.post('/register', (req, res) => {
    //check for user existence
    dbo.collection("empcollection").findOne({ name: req.body.name }, (err, use
robj) => {
        if (err) {
            console.log("err is read", err);
        }
        else if (userobj == null) {
            bcrypt.hash(req.body.password, 6, (err, hashedpassword) => {
                if (err) {
                    console.log("err is occured", err)
                }
                req.body.password = hashedpassword;
                console.log("pwds", hashedpassword)
                console.log("pesddd", req.body.password)
                dbo.collection("empcollection").insertOne(req.body, (err, succ
ess) => {
                    if (err) {
                        console.log("err is occured", err)
                    }
                    else {
                        res.send({ message: "user is registered successfully" 
})
                    }
                })
            })
        }
        else {
            res.send({ message: "user is already existed" })
        }

    })
});

UserExpressapp.post('/login', (req, res) => {
    console.log(req.body)
    dbo.collection("empcollection").findOne({name:req.body.name}, (err, userob
j) => {
        if (err) {
            console.log("error is occured", err)
        }
        else if (userobj==null) {
            res.send({message:"user is not existed"});
        }
        else {
                bcrypt.compare(req.body.password,userobj.password,(err, isMatc
hed) => {
                    if (err) {
                        console.log("err is occured", err)
                    }
                    else if (isMatched == false) {
                        res.send({message:"invalid password"})
                       
                    }
                    else {
                        // jwt.sign({ name: userobj.name }, 'secret', { expire
sIn: 60 }, (err, signedToken) => {
                        //     if (err) {
                        //         console.log("err is occured", err)
                        //     }
                        //     else {
                        //         console.log({ message: signedToken })
                        //     }
                        // })
                        res.send({message:"successfully login"})
                        console.log("isMatched",isMatched)
                    }
                })
            

        }
    })
})

You might also like