I am doing an Angular 4 application with node js backend. I did the login form, and all is good I want to implement the function "remember me".
This my login service:
import { Injectable } from '@angular/core';
@Injectable()
export class loginService{
rememberMe: boolean;
constructor() { }
login(credentials) {
sessionStorage.setItem('Name', credentials.firstName);
sessionStorage.setItem('token', credentials.token);
}
getCostumer() {
const user = {
Name: sessionStorage.getItem('firstName'),
token: sessionStorage.getItem('token')
}
This is the component:
constructor(private signInService: SignInService, private router: Router,
public dialog: MatDialog, private authService: AuthService) { }
ngOnInit() { }
login(costumer) {
this.loginService.login(costumer).subscribe((data) => {
this.authService.login(data);
this.router.navigate(['home']);
this.dialog.closeAll();
}, err => {
this.message = err._body;
console.log(this.message);
});
}
}
A more secure way to implement the remember me feature is to store a random token instead of a user id in both cookies and database server. When users access the web application, you match the cookies' tokens with those stored in the database. Also, you can check the token's expiration time.
Some web applications may need a "Remember Me" functionality. This means that, after a user login, user will have access from same machine to all its data even after session expired.
Use localStorage
instead of sessionStorage
In your case, you can do something like this:
if (isRemberMeChecked) {
...
localStorage.setItem('Name', credentials.firstName);
localStorage.setItem('token', credentials.token);
...
} else {
...
sessionStorage.setItem('Name', credentials.firstName);
sessionStorage.setItem('token', credentials.token);
...
}
If you want to get isRemberMeChecked
value globally you can use angular service
What you want to do here is use localStorage for the rememberMe and credentials.firstName. The credentials.token you can store in the sessionStorage:
login(credentials) {
localStorage.removeItem('Name');
localStorage.removeItem('RememberMe');
sessionStorage.setItem('token', credentials.token);
if(rememberMe){
localStorage.setItem('Name', credentials.firstName);
localStorage.setItem('RememberMe', JSON.stringify(this.rememberMe));
}
}
After a reload it will fetch the RememberMe and Name:
if(JSON.parse(localStorage.getItem('RememberMe')) !== null)
{
this.name = localStorage.getItem('Name');
this.rememberMe = JSON.parse(localStorage.getItem('RememberMe'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With