Professional Documents
Culture Documents
router.post("/register",(req,res)=>{
bcrypt.hash(req.body.password, 10,(err,hash)=>{
if(err){
return res.json({success: false, message:"sorry cant process because "+err})
// console.log(+err)
}else{
const user = new User({
displayName :req.body.displayName,
email : req.body.email,
password : hash,
})
user.save()
.then((_)=>{
res.json({success:true , message:"Account has been created"})
})
.catch((err)=>{
}
})
}),
router.post("/create",(req,res)=>{
})
.catch((err)=>{
router.get('/msg',(req,res)=>{
// const userId = req.userData.userId;
const msg= req.body.params;
contact.find(msg).exec().then((result)=>{
res.json({success:true,data:result})
}).catch(err=>{
res.json({success:false,message:"server error"+err})
})
})
//delete contactss
// router.delete('/msg/id',(req,res,next)=>{
// contact.remove({_id: req.params.id}, function(err, result){
// if(err){
// res.json(err);
// }
// else{
// res.json(result);
// }
// })
// });
router.get('/contacts',(req,res,next)=>{
Contact.find(function(err,contact){
res.json(contact);
})
})
router.post("/login",(req,res)=>{
User.find({email:req.body.email}).exec().then((result)=>{
if(result.length<1){
return res.json({success:false,message:"User not found"})
}
const user=result[0];
bcrypt.compare(req.body.password,user.password, (err,ret)=>{
if(ret){
const payload = {
// userId : this._id,
userId : user._id,
}
const token = jwt.sign(payload,"webBatch");
return res.json({success:true,token:token,message:"Login Successful"})
}else{
return res.json({success:false,message:"Login failed please check your
credentials"})
}
})
}).catch(err=>{
res.json({success : false,message : "auth failed"+err})
})
}),
router.get('/profile',checkAuth,(req,res)=>{
const userId = req.userData.userId;
User.findById(userId).exec().then((result)=>{
res.json({success:true,data:result})
}).catch(err=>{
res.json({success:false,message:"server error"+err})
})
})
//retriving contacts
router.get('/contacts',(req,res,next)=>{
Contact.find(function(err,contact){
res.json(contact);
})
})
//add contact
router.post('/contact',(req,res,next)=>{
let newContact = new Contact({
first_name: req.body.first_name,
last_name: req.body.last_name,
phone: req.body.phone
})
newContact.save((err,contact)=>{
if(err){
res.json({msg: 'failed to add contact'});
}
else{
res.json({msg:'contact added successfully'});
}
});
})
module.exports = router;
user.js
// console
const Schema = mongoose.Schema;
const userSchema = new Schema({
displayName :{type:String},
email : {type:String, unique : true},
password : {type: String, required : true},
created_at:{type:Number, default:Date.now().valueOf()},
updated_at:{type:Number, default:Date.now().valueOf()},
// createcontact:{type:String},
})
// module.exports = mongoose.module('User',userSchema)
module.exports = mongoose.model('User',userSchema);
// module.exports = mongoose.model('List', listSchema)**
// const Contact = module.exports= mongoose.model('contact',ContactSchema);
Table.js
})
// module.exports = mongoose.module('User',userSchema)
module.exports = mongoose.model('contact',ContactSchema);
// const Contact = module.exports= mongoose.model('contact',ContactSchema);
Check auth.js
module.exports = (req,res,next)=>{
try{
const token = req.headers.authorization.split(' ')[1];
req.userData = decode;
next();
}catch(err){
res.json({success:false,message:"auth failed"})
}
}
App.js
mongoose.connect('mongodb://localhost:27017/CRM',(err)=>{
if (err){
console.log("not connected"+err);
}
else{
console.log("connected database");
}
});
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json( ))
app.use(cors());
app.use('/auth', authRoute);
// app.use('/api',authRoute);
app.get('/',(req,res)=>{
res.send("welcome to main page")
})
app.listen(port,()=>{
console.log("Server is running",+port);
})
Login code
Login.html
</div>
<!-- Page content -->
<div class="container mt--8 pb-3">
<div class="row justify-content-center">
<div class="col-lg-5 col-md-7">
<div class="card bg-secondary shadow border-0">
<div class="card-header bg-transparent pb-3">
<div class="text-muted text-center mt-2 mb-3">
<img src="assets/img/brand/logo.png" style="height: 200px;" alt="...">
<!-- <h1 class="logo">Customer Relationship Management</h1> -->
</div>
</div>
<div class="card-body px-lg-5 py-lg-4">
<div class="text-left text-dark mb-2 user-login-text">
<small>User Login</small>
</div>
<form [formGroup]="loginForm" action="">
<div class="form-group mb-3">
<div class="input-group input-group-alternative">
<div class="input-group-prepend">
<span class="input-group-text"><i class="ni ni-email-83"></i></span>
</div>
<input class="form-control" type="email" placeholder="Email"
formControlName="email" autofocus>
</div>
</div>
<div class="form-group">
<div class="input-group input-group-alternative">
<div class="input-group-prepend">
<span class="input-group-text"><i class="ni
ni-lock-circle-open"></i></span>
</div>
<input class="form-control" type="password" placeholder="****"
formControlName="password">
</div>
</div>
<div class="row">
<div class="col-6">
<div class="custom-control custom-control-alternative custom-checkbox">
<input class="custom-control-input" id=" customCheckLogin"
type="checkbox">
<!-- <label class="custom-control-label" for=" customCheckLogin">
<span class="text-dark">Remember me</span>
</label> -->
</div>
</div>
<div class="col-6">
<div class="text-right">
<button type="button" class="btn btn-primary" (click)="login()">Sign
in</button>
</div>
</div>
</div>
<div class="row mt-3">
<div class="col-6">
<a href="#" class="text-primary"><small>Still have'nt signed up ? TRY
NOW!!</small></a>
</div>
<div class="col-6 text-right">
<a href="#" routerLink="/register" class="text-primary"><small>Sign up
Now</small></a>
</div>
</div>
</form>
</div>
</div>
<div class="row mt-3">
<div class="col-12 text-center">
<a href="javascript:void(0)" class="text-light"><small>2022 ©CRM. All
Rights Reserved.</small></a>
</div>
</div>
</div>
</div>
</div>
Login.ts
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit, OnDestroy {
userLoginPass = '';
userLoginEmail = '';
userLoginName = '';
loginForm! : FormGroup;
constructor(private fb:FormBuilder, private auth:UrlAPIService, private router :
Router) {
this.loginForm = this.fb.group({
'email' : ['',Validators.required],
'password' : ['',Validators.required]
})
}
ngOnInit() {
}
ngOnDestroy() {
}
login(){
const data=this.loginForm.value;
this.auth.signin(data).subscribe((res)=>{
if(res.success){
localStorage.setItem('token',res.token)
this.router.navigate(['/profile'])
} else{
Swal.fire({
title: 'Login failed',
text: 'Please enter a valid username and password',
icon: 'error'
});
this.userLoginEmail = '';
this.userLoginPass = '';
}
})
}
signinUser(){
var userStorage = localStorage.getItem('userLoginEmail');
var passStorage = localStorage.getItem('userLoginPass');
if(this.userLoginEmail == userStorage && this.userLoginPass == passStorage){
localStorage.setItem('userLoginName', localStorage.getItem('userLoginName'));
this.router.navigateByUrl('/dashboard');
}
else{
Swal.fire({
title: 'Login failed',
text: 'Please enter a valid username and password',
icon: 'error'
});
this.userLoginEmail = '';
this.userLoginPass = '';
}
}
signupUser(){
this.router.navigate(['#/register','register']);
}
forgotPasswd() {
this.router.navigate(['#/forgot-password', 'forgot-password']);
}
Registration code
Register.html
</div>
<!-- Page content -->
<div class="container mt--8 pb-0">
<!-- Table -->
<div class="row justify-content-center">
<div class="col-lg-6 col-md-8">
<div class="card bg-secondary shadow border-0">
<div class="card-header bg-transparent background-header">
</div>
<div class="card-body">
<div class="text-center">
<button type="button" class="btn btn-block btn-default mt-12"
(click)="signup()">GET STARTED NOW</button>
</div>
<div class="text-dark size-new-font">
Already have an account? <span class="text-primary new-text-primary"
routerLink="/login">Sign in to CRM</span><br />
You can help customer as soon as you sign up<br />
By clicking on '<strong>Get Started Now</strong>' you are accepting our
terms of usage and <span class="text-primary new-text-primary">privacy
policy</span>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
Register.ts
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
regName = '';
regEmail = '';
regPasswd = '';
regCountry = '';
regContact = '';
signupForm! : FormGroup;
message:string="";
isProcess:boolean=false;
className = "d-none";
constructor(private router: Router, private fb:FormBuilder, private auth :
UrlAPIService) {
this.signupForm = this.fb.group({
'displayName' : ['',Validators.required],
'email' : ['',Validators.required],
'password' : ['',Validators.required]
})
}
ngOnInit() {
}
signup() {
const data = this.signupForm.value;
delete data['confirm']
this.auth.signup(data).subscribe(res=>{
if (res.success){
this.isProcess=false;
this.message="Account has been created"
this.className='alert alert-success'
}else{
this.isProcess=false;
this.message=res.message;
this.className='alert alert-danger'
}
// this.signupForm.reset
},err=>{
this.isProcess=false;
this.message="Server Error";
this.className='alert alert-danger'
})
}
gotoLogin(){
this.router.navigateByUrl('#/login');
}
signUpUser() {
if(this.regName == ""){
Swal.fire({
title: 'Alert',
text: 'Please enter first name',
icon: 'warning'
});
}
else if(this.regEmail == ""){
Swal.fire({
title: 'Alert',
text: 'Please enter e-mail address',
icon: 'warning'
});
}
else if(this.regPasswd == ""){
Swal.fire({
title: 'Alert',
text: 'Please enter password',
icon: 'error'
});
}
else if(this.regCountry == ""){
Swal.fire({
title: 'Alert',
text: 'Please select your country',
icon: 'error'
});
}
else if(this.regContact == ""){
Swal.fire({
title: 'Alert',
text: 'Please enter contact number',
icon: 'error'
});
}
else {
localStorage.setItem('userLoginName', this.regName);
localStorage.setItem('userLoginEmail', this.regEmail);
localStorage.setItem('userLoginPass', this.regPasswd);
Swal.fire({
title: 'Success',
text: 'Your account has been created, now you can login',
icon: 'success'
});
setTimeout(()=>{ // <<<---using ()=> syntax
this.gotoLogin();
}, 3000);
}
}
}
Output :-