Hello Everyone!
I’m creating a simple login authentication with MEAN stack using angular 4 HTTP client in the front-end. I’m trying to implement show/hide navigation based on login. When the user login it must show the navigation-list if not hide it but my code doesn’t show any error. Below is my code please have a look and let me know where my doing wrong.
<ul class="nav navbar-nav">
<ng-template *ngIf="isAuthenticated()"> <!-- Here I used [ngIf]="isAuthenticated()" as well still it doesn't work-->
export class NavbarComponent implements OnInit {
constructor(private authService: AuthService,
private router: Router) { }
ngOnInit() {
}
onLogout() {
this.authService.logout()
.subscribe(
(res) => {
if (res) {
this.router.navigate(['/login']);
}
}
);
}
isAuthenticated() {
this.authService.isAuthenticated();
}
}
export class LoginComponent implements OnInit {
signinForm: FormGroup;
constructor(private authService: AuthService,
private router: Router) { }
ngOnInit() {
this.signinForm = new FormGroup({
'email': new FormControl(null, [Validators.required, Validators.email]),
'password': new FormControl(null, [Validators.required, Validators.minLength(6)])
});
}
onSignin() {
const userDetails = {
email: this.signinForm.get('email').value,
password: this.signinForm.get('password').value
};
this.authService.signInWithEmailAndPassword(userDetails)
.subscribe(
(res) => {
if(res) {
console.log('res: ', res);
this.router.navigate(['/jobs']);
this.authService.isAuthenticated()
.subscribe(
(res) => {
console.log('response: ', res);
}
);
}
},
(err) => {
alert('Invalid User Credentials');
}
);
this.signinForm.reset();
}
}
export class AuthService {
url = 'http://localhost:3000/api/users'
constructor(private router: Router,
private http: HttpClient) {}
signInWithEmailAndPassword (userDetails) {
return this.http.post(this.url + '/login', userDetails, { observe: 'body', responseType: 'json'})
.map(
(response) => {
return response;
}
)
}
logout() {
return this.http.get(this.url + '/logout')
.map((response) => {return response})
}
isAuthenticated() {
return this.http.get(this.url + '/is-logged-in')
.map((response) => { return response })
}
}
//Back-End Code
//server.js
const userRoute = require('./routes/user-route');
app.use('/api/users', userRoute);
//user-router.js
userRoute.get('/is-logged-in', authMiddleware.isUserLoggedIn, authMiddleware.isUserActive, user.isLoggedInUser);
const authMiddleware = {
isUserActive: (req, res, next) => {
req.user.isActive === true ? next() : res.status(401).send({message: 'No User Found!'});
},
isUserLoggedIn: (req, res, next) => {
console.log('imcalled from auth');
req.isAuthenticated() ? next() : res.status(401).send({message: 'You must be LoggedIn'});
}
}
const user = {
isLoggedInUser: (req, res) => {
res.status(200).send(true);
}
};