mean stack mongodb don't save data - node.js

i'm trying to register user into my mongodb. Under Postman everything works but my passwords aren't encrypted. I can see that later. But the main problem is, when i want to subscribe a new user, my user is not saved in my mongodb. There is my code :
my register.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { AuthService } from 'src/app/service/auth.service';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
signupForm : FormGroup
constructor(private fb:FormBuilder, private auth: AuthService) {
this.signupForm = this.fb.group({
'username':['',Validators.required],
'email':['',Validators.required],
'password':['',Validators.required]
})
}
ngOnInit(): void {
}
signup(){
this.auth.signup(this.signupForm.value).subscribe(res=>{
alert('User register Succesfull');
this.signupForm.reset
}, err=>{
alert(err)
})
}
}
authservice.component.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
signup(data:any):Observable<any>{
return this.http.post(environment.apiBaseUrl+'/auth/register', data)
}
}
environment.ts
export const environment = {
production: false,
apiBaseUrl: 'http://localhost:3000'
};
authroutes.js
const router = require('express').Router();
const User = require('../models/user');
const bcrypt = require('bcrypt');
const bodyParser = require('body-parser')
router.post('/register',(req, res) => {
bcrypt.hash(req.body.password, 10,(err, hash)=>{
if(err){
return res.json({success:false, message:"hash error"})
}else {
const user = new User({
username:req.body.username,
email:req.body.email,
password:req.body.password,
})
user.save()
.then((_)=>{
res.json({success:true, message:'Account has been created'})
})
.catch((err)=>{
if(err.code ===11000){
return res.json({success:false, message:'email already exist'})
}
res.json({success:false, message:'authentication failed'})
})
}});
})
router.post('/login',(req,res)=>{
res.json('login work')
})
module.exports = router

Related

Nestjs returns 401 (Unauthorized) even with valid user ft. passport-local

Hi awesome developers,
I'm trying to implement Authentication using passport-local and Nestjs with reference to https://progressivecoder.com/how-to-implement-nestjs-passport-authentication-using-local-strategy/.
I have implemented exactly same but Nestjs always returns 401 Unauthorized even with valid user. I can't seem to find what I am missing.
Code Structure
Authentication Module
User Module
Here's the code:
Authentication Module:
authentication.module.ts
import { Module } from '#nestjs/common';
import { PassportModule } from '#nestjs/passport';
import { UserModule } from 'src/user/user.module';
import { AuthenticationController } from './controllers/authentication.controller';
import { AuthenticationService } from './services/authentication.service';
import { LocalStrategy } from './strategies/local.strategy';
#Module({
imports:[UserModule, PassportModule],
controllers: [AuthenticationController],
providers: [AuthenticationService, LocalStrategy]
})
export class AuthenticationModule {}
authentication.controller.ts
import { Controller, Post, Request, UseGuards } from '#nestjs/common';
import { AuthGuard } from '#nestjs/passport';
import { UserService } from 'src/user/services/user.service';
#Controller('authentication')
export class AuthenticationController {
constructor(private userService: UserService){}
#UseGuards(AuthGuard('local'))
#Post('signin')
async signin(#Request() req){
return req.user;
}
}
authentication.service.ts
import { Injectable } from '#nestjs/common';
import { UserService } from 'src/user/services/user.service';
#Injectable()
export class AuthenticationService {
constructor(private userService: UserService) {}
async validateUser(email: string, password: string): Promise<any> {
const user = await this.userService.readUserByEmail(email);
if (user && user.password === password) {
const { password, ...result } = user;
return result;
}
return null;
}
}
local.strategy.ts
import { Injectable, UnauthorizedException } from "#nestjs/common";
import { PassportStrategy } from "#nestjs/passport";
import { Strategy } from "passport-local";
import { AuthenticationService } from "../services/authentication.service";
#Injectable()
export class LocalStrategy extends PassportStrategy(Strategy){
constructor(private authenticationService: AuthenticationService){
super();
}
async validate(username: string, password: string): Promise<any> {
const user = await this.authenticationService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
User Module:
user.module.ts
import { Module } from '#nestjs/common';
import { UserController } from './controllers/user.controller';
import { UserService } from './services/user.service';
#Module({
controllers: [UserController],
providers: [UserService],
exports: [UserService]
})
export class UserModule {}
user.controller.ts
Skipping user controller as it is irrelevent
user.service.ts
import { Injectable } from '#nestjs/common';
import { prisma } from 'src/main';
import { CreateUserDTO } from '../dto/create-user.dto';
import { UpdateUserDTO } from '../dto/update-user.dto';
#Injectable()
export class UserService {
private readonly users = [
{
id: "1",
name: "Ajitesh",
email: "ajitesh.k-s#lloydsbanking.com",
password: "secret"
}
]
//....other methods
async readUserByEmail(email: string){
return this.users.find(user => user.email === email);
}
}
Request:
{
"email": "ajitesh#example.com",
"password": "secret"
}
Thanks in advance.
passport-local expects req.body to be populated with username and password fields. If you plan to use something else for the username, like email, then you need to tell passport about that in your strategy using the usernameField option in super
import { Injectable, UnauthorizedException } from "#nestjs/common";
import { PassportStrategy } from "#nestjs/passport";
import { Strategy } from "passport-local";
import { AuthenticationService } from "../services/authentication.service";
#Injectable()
export class LocalStrategy extends PassportStrategy(Strategy){
constructor(private authenticationService: AuthenticationService){
super({
usernameField: 'email',
});
}
async validate(username: string, password: string): Promise<any> {
const user = await this.authenticationService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}

how to change return req.user object name of passport-local?

I'm developing a backend using nestjs and passport-local strategy. I use local strategy only for owners login in my projects. but at end of validation it returns the owner in req.user.
how can I change it so it returns the owner in req.owner?
import { Injectable } from '#nestjs/common';
import { OwnerService } from '../owner/owner.service';
#Injectable()
export class AuthService {
constructor(private ownerService: OwnerService) {}
async validateOwner(username: string, pass: string): Promise<any> {
const owner = await this.ownerService.findOneByUsername(username);
// later check with hashed pass
if (owner && owner.owner && owner.owner.password === pass) {
const { password, ...result } = owner.owner;
return result;
}
return null;
}
}
and
import { Strategy } from 'passport-local';
import { PassportStrategy } from '#nestjs/passport';
import { Injectable, HttpException } from '#nestjs/common';
import { AuthService } from './auth.service';
#Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({
usernameField: 'username',
passwordField: 'password',
});
}
async validate(username: string, password: string): Promise<any> {
const owner = await this.authService.validateOwner(username, password);
if (!owner) {
throw new HttpException('No Owner found', 404);
}
return owner;
}
}
how I use it:
#UseGuards(AuthGuard('local'))
#Post('login')
async login(#Request() req) {
console.log(req.owner, req.user);
return req.owner;
}
req.owner is empty but req.user has value
UPDATE:
my Authmodule.ts:
import { Module } from '#nestjs/common';
import { AuthService } from './auth.service';
import { OwnerModule } from '../owner/owner.module';
import { LocalStrategy } from './local.strategy';
import { PassportModule } from '#nestjs/passport';
import { JwtModule } from '#nestjs/jwt';
#Module({
providers: [AuthService, LocalStrategy],
imports: [
OwnerModule,
PassportModule.register({
property: 'owner',
})
],
exports: [AuthService],
})
export class AuthModule {}
PassportModule.register({ property: 'owner' })
where PassportModule is imported from #nestjs/passport
I created a LocalAuthGuard class that extends my local strategy:
import { Injectable } from '#nestjs/common';
import { AuthGuard } from '#nestjs/passport';
#Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
constructor() {
super({
property: 'owner',
});
}
}
then wherever I use this guard, it adds my target field to req.owner instead of req.user.
#UseGuards(LocalAuthGuard)
#Post('login')
async login(#Request() req): Promise<LoginResponse> {
return this.authService.login(req.owner);
}

NestJS passport-jwt always throws Unauthorized

I encountered to the issue that whenever I sign up through the postman I receive the token. However, other route is private and requires token as Authorization Bearer, but whenever I put the token I receive "Unauthorized". The validate from strategy never executes, as I understand because the token for some reasons is invalid. Important to mention, that I do not receive any errors.
jwt.strategy.ts:
import { Injectable } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import { PassportStrategy } from '#nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
#Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(config: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.get('JWT_SECRET'),
});
}
async validate(payload: any) {
console.log({ payload: payload });
return true;
}
}
auth.module.ts
import { Module } from '#nestjs/common';
import { JwtModule } from '#nestjs/jwt';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './strategy';
#Module({
imports: [JwtModule.register({})],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
})
export class AuthModule {}
auth.service.ts where I receive token:
public async signin(body: AuthDto) {
// find the user by email
const user = await this.prisma['User'].findUnique({
where: {
email: body.email,
},
});
// if user does not exists throw exception
if (!user) {
throw new ForbiddenException('Invalid email address or password');
}
// compare passwords
const passwordMatches = await argon.verify(user.hash, body.password);
// if password is inoccrect throw exception
if (!passwordMatches) {
throw new ForbiddenException('Invalid email address or password');
}
return this.signToken(user.id, user.email);
}
auth.service.ts where I create the token:
private async signToken(userId: number, email: string): Promise<{ access_token: string }> {
const payLoad = {
sub: userId,
email,
};
const token = await this.jwt.sign(payLoad, {
expiresIn: '10m',
secret: this.config.get('JWT_SECRET'),
});
return { access_token: token };
}
}
user.controller.ts where the private route is
import { Controller, Get, UseGuards } from '#nestjs/common';
import { JwtGuard } from 'src/auth/guard';
#Controller('users')
export class UserController {
#UseGuards(JwtGuard)
#Get('me')
getMe() {
return 'Hello JWT';
}
}
jwt.guard.ts
import { AuthGuard } from '#nestjs/passport';
export class JwtGuard extends AuthGuard('jwt') {
constructor() {
super();
}
}
The code works fine, without any issues. However, the issues was with the postman. For some reasons the Authorization tab were bugged, tried to sent through headers written by hand and that worked without any problems

Nest.js with AWS Cognito, How to get access to the user attributes

I have created the Nest.js app. And I use AWS Cognito to manage user authentication and authorization. I use amazon-cognito-identity-js for handling user signin/signout and #nestjs/passport / #UseGuards(AuthGuard('jwt')) for validating tokens and user access for the routes.
Now I need to get access to the current user attributes(email, phone_number...) in other routes of the app. What is the best way to do this?
auth.service.ts
import { AuthConfig } from './auth.config';
import { Injectable } from '#nestjs/common';
import {
AuthenticationDetails,
CognitoUser,
CognitoUserPool,
CognitoUserAttribute,
} from 'amazon-cognito-identity-js';
#Injectable()
export class AuthService {
private userPool: CognitoUserPool;
private sessionUserAttributes: {};
constructor(private readonly authConfig: AuthConfig) {
this.userPool = new CognitoUserPool({
UserPoolId: this.authConfig.userPoolId,
ClientId: this.authConfig.clientId,
});
}
registerUser(registerRequest: {
name: string;
email: string;
password: string;
}) {
const { name, email, password } = registerRequest;
return new Promise((resolve, reject) => {
return this.userPool.signUp(
name,
password,
[new CognitoUserAttribute({ Name: 'email', Value: email })],
null,
(err, result) => {
if (!result) {
reject(err);
} else {
resolve(result.user);
}
},
);
});
}
authenticateUser(user: { name: string; password: string }) {
const { name, password } = user;
const authenticationDetails = new AuthenticationDetails({
Username: name,
Password: password,
});
const userData = {
Username: name,
Pool: this.userPool,
};
const newUser = new CognitoUser(userData);
return new Promise((resolve, reject) => {
return newUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
resolve(result);
},
onFailure: (err) => {
reject(err);
},
});
});
}
}
jwt.strategi.ts
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '#nestjs/passport';
import { Injectable } from '#nestjs/common';
import { AuthService } from './auth.service';
import { passportJwtSecret } from 'jwks-rsa';
import { AuthConfig } from './auth.config';
#Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly authService: AuthService,
private authConfig: AuthConfig,
) {
super({
secretOrKeyProvider: passportJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `${authConfig.authority}/.well-known/jwks.json`,
}),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
audience: authConfig.clientId,
issuer: authConfig.authority,
algorithms: ['RS256'],
});
}
public async validate(payload: any) {
return !!payload.sub;
}
}
app.controller.ts
import { Controller, Get, UseGuards, Header } from '#nestjs/common';
import { AppService } from './app.service';
import { AuthGuard } from '#nestjs/passport';
#Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
#Get()
#UseGuards(AuthGuard('jwt'))
#Header('Content-Type', 'text/html')
getHello(): string {
return this.appService.getHello();
}
}
user is set as a property on the request when passport successfully authenticates the user.
The request can be injected in your controller and user property then accessed.
import { Controller, Get, UseGuards, Header, Request } from '#nestjs/common';
import { AppService } from './app.service';
import { AuthGuard } from '#nestjs/passport';
#Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
#Get()
#UseGuards(AuthGuard('jwt'))
#Header('Content-Type', 'text/html')
getHello(#Request() req): string {
console.log(req.user);
return this.appService.getHello();
}
}

How can i implement role redirection after a successful login in my MEAN stack Application

I have developed a MEAN stack application the backend works fine and the frontend but i want to go much further by implementing role based redirection after login i have 5 roles thats is admin, teacher, nurse, sportsman, and janitor i want each of them to access his/her own page after successful login and should use the same login page
I have tried some several solution online but so far nothing has come to help me this is the fifth time am asking this question without a real solution, please help me solve this its my final year project
here is my routes.ts
```import { Routes } from '#angular/router';
import { UserComponent } from './user/user.component';
import { SignUpComponent } from './user/sign-up/sign-up.component';
import { SignInComponent } from './user/sign-in/sign-in.component';
import { AuthGuard } from './auth/auth.guard';
import { AdminComponent } from './user/admin/admin.component';
import { AdminSportComponent} from './user/admin-sport/admin-sport.component'
import { AdminSuaHubComponent } from './user/admin-sua-hub/admin-sua-hub.component';
import { AdminCictComponent } from './user/admin-cict/admin-cict.component';
import { ViewadminsectionsComponent } from './user/viewadminsections/viewadminsections.component'
import { from } from 'rxjs';
export const appRoutes: Routes = [
{
path: 'user',component:SignInComponent
},
{
path:'signup', component:SignUpComponent, canActivate:[AuthGuard]
},
{
path:'admin', component:AdminComponent,
canActivate:[AuthGuard],
data:{
roles:['admin']
}
},
{
path:'viewsectionadmins',
component:ViewadminsectionsComponent,
canActivate:[AuthGuard],
data:{
roles:['admin']
}
},
{
path:'admincict',
component:AdminCictComponent,
canActivate:[AuthGuard],
data:{
roles:['admincict']
}
},
{
path:'adminsport',
component:AdminSportComponent,
canActivate:[AuthGuard],
data:{
roles:['adminsport']
}
},
{
path:'adminsuahub',
component: AdminSuaHubComponent,
canActivate:[AuthGuard],
data:{
roles:['adminsuahub']
}
},
{
path: '',component:SignInComponent
},
{
path:'',redirectTo:'/user', pathMatch:'full'
}
];```
Here is my app.module.ts
```import { BrowserModule } from '#angular/platform-browser';
import { NgModule, forwardRef } from '#angular/core';
import{ FormsModule } from '#angular/forms';
import{ RouterModule } from '#angular/router'
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http'
//components
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UserComponent } from './user/user.component';
import { SignUpComponent } from './user/sign-up/sign-up.component';
import { from } from 'rxjs';
//routes
import { appRoutes } from './routes';
import { SignInComponent } from './user/sign-in/sign-in.component';
import { UserService } from './shared/user.service';
import { AuthGuard } from './auth/auth.guard';
import { AuthInterceptor } from './auth/auth.interceptor';
import { AdminComponent } from './user/admin/admin.component';
import { AdminSportComponent } from './user/admin-sport/admin-sport.component';
import { AdminSuaHubComponent } from './user/admin-sua-hub/admin-sua-hub.component';
import { AdminCictComponent } from './user/admin-cict/admin-cict.component';
import { ViewadminsectionsComponent } from './user/viewadminsections/viewadminsections.component';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
#NgModule({
declarations: [
AppComponent,
UserComponent,
SignUpComponent,
SignInComponent,
AdminComponent,
AdminSportComponent,
AdminSuaHubComponent,
AdminCictComponent,
ViewadminsectionsComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
RouterModule.forRoot(appRoutes),
HttpClientModule,
BrowserAnimationsModule
],
providers: [{
provide:forwardRef(() => {HTTP_INTERCEPTORS}),
useClass:forwardRef(() =>{ AuthInterceptor}),
multi:true
},AuthGuard,UserService],
bootstrap: [AppComponent]
})
export class AppModule { }```
Here is my User.js
``` const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const userSchema = new mongoose.Schema({
fullname:{
type:String,
required:'Full name cant be empty',
min:6,
max:255
},
email:{
type:String,
required:'Email cant be Empty',
max:255,
unique:true
},
University:{
type:String,
default:"Sokoine University of Agriculture"
},
College:{
type:String,
required:'College cant be Empty'
},
Department:{
type:String,
required:'department cant be empty'
},
password:{
type:String,
required:'pasword cant be empty',
max :1024,
minlength: [6,'password must be atlest 6 character long']
},
admintype:{
type:String,
enum :['HOD','CICT','Sports','SUASAB','Admin']
},
date:{
type:Date,
default:Date.now
},
saltSecret:String
});
//custom validation
userSchema.path('email').validate((val) => {
emailRegex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return emailRegex.test(val);
},'Invalid E-mail. ');
//events
userSchema.pre('save', function(next) {
bcrypt.genSalt(10, (err, salt)=> {
bcrypt.hash(this.password, salt, (err, hash) => {
this.password = hash;
this.saltSecret = salt;
next();
});
});
});
//methods
userSchema.methods.verifyPassword = function(password){
return bcrypt.compareSync(password, this.password);
};
userSchema.methods.generateJwt = function() {
return jwt.sign({ _id:this._id},
process.env.JWT_SECRET,
{expiresIn:process.env.JWT_EXP});
}
module.exports = mongoose.model('User',userSchema)```
Here is my user.controller.js
```const mongoose = require('mongoose');
const User = mongoose.model('User');
const passport = require('passport');
const _ = require('lodash');
module.exports.register = (req,res, next) => {
const user = new User();
user.fullname = req.body.fullname;
user.email = req.body.email;
user.College = req.body.College;
user.Department = req.body.Department;
user.password = req.body.password;
user.admintype = req.body.admintype;
user.save((err, doc) => {
if(!err) { res.send(doc)}
else
{
if(err.code == 11000)
res.status(422).send(['Duplicate email Address Found.'])
else
return next(err);
}
})
}
module.exports.authenticate = (req, res, next ) => {
//calll for passport authentication
passport.authenticate('local', (err, user, info) => {
//error form paasport middleware
if(err) return res.status(400).json(err);
//registered user
else if (user) return res.status(200).json({ "token":user.generateJwt() });
//unknown user or wrong password
else return res.status(404).json(info);
})(req, res);
}
module.exports.userProfile = (req, res, next) =>{
User.findOne({ _id:req._id},
(err,user) =>{
if(!user)
return res.status(404).json({ status: false, message : 'User Record not Found. '});
else
return res.status(200).json({ status:true , user : _.pick(user, ['fullname','email','university','College','Department','admintype'])});
} );
//get admins
}```
here is my auth.guard.ts
```import { Injectable } from '#angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '#angular/router';
import { Observable } from 'rxjs';
import { UserService } from '../shared/user.service';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private userService:UserService,private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if(!this.userService.isloggedIn()){
this.router.navigateByUrl('/user');
this.userService.deleteToken();
return false;
}
return true;
}
}```
here is my user.model.ts
```export class User {
fullname:string;
email:string;
university:string;
College:string;
Department:string;
password:string;
admintype:string;
}```
here is my user.service.ts
```import { Injectable } from '#angular/core';
import { User } from './user.model';
import{ HttpClient, HttpHeaders } from '#angular/common/http';
import{ environment } from '../../environments/environment';
import { from } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class UserService {
selectedUser: User = {
fullname:'',
email:'',
university:'',
College:'',
Department:'',
password:'',
admintype:''
}
noAuthHeader = { headers: new HttpHeaders({ 'NoAuth': 'True'})};
constructor(private http: HttpClient) { }
//http methods
postUser(user:User)
{
return this.http.post(environment.apiBaseUrl+ '/register' ,user)
}
login(authCredentials)
{
return this.http.post(environment.apiBaseUrl+ '/authenticate',authCredentials,this.noAuthHeader);
}
getUserProfile()
{
return this.http.get(environment.apiBaseUrl + '/userProfile');
}
//helper methods
setToken(token:string)
{
localStorage.setItem('token',token);
}
getToken()
{
localStorage.getItem('token');
}
deleteToken()
{
localStorage.removeItem('token');
}
getUserPayload(){
var token = localStorage.getItem('token');
if(token)
{
var userPayload = atob(token.split('.')[1]);
return JSON.parse(userPayload);
}
else
return null;
}
isloggedIn()
{
var userPayload = this.getUserPayload();
if (userPayload)
{
return userPayload.exp > Date.now() / 1000;
}
}
getUserRole()
{
}
}```
here is my sign-in.component.ts
```import { Component, OnInit } from '#angular/core';
import { NgForm } from '#angular/forms';
import { UserService } from 'src/app/shared/user.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-sign-in',
templateUrl: './sign-in.component.html',
styleUrls: ['./sign-in.component.css']
})
export class SignInComponent implements OnInit {
constructor( private userService:UserService, private router:Router) { }
model = {
email:'',
password:''
};
emailRegex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
serverErrorMessages : string;
ngOnInit() {
if(this.userService.isloggedIn())
{
this.router.navigateByUrl('/admin');
}
}
onSubmit(form :NgForm)
{
this.userService.login(form.value).subscribe(
res =>{
this.userService.setToken(res['token']);
this.router.navigateByUrl('/admin');
},
err =>{
this.serverErrorMessages = err.message;
});
}
}```
so far i have no errors but am in need of implementing role based redirection
i would suggest you to create a field in mongodb schema as admin with boolean value as true or false depending upon the user, add different fields if any other roles exists,
on login check the user admin status and accordingly inform other parts of your application by subscribing the observables in your service file
call the method in your service file on OnInit method of the component and check whether the user is admin or not if not admin hide the things you don't want to show
and to stop a user from going to routes that are meant for admin add a guard which will navigate the user to homepage if he is not an admin by checking the same observable that you created in the service file.
i hope it helps

Resources