ngx-rocket / generator-ngx-rocket

:rocket: Extensible Angular 14+ enterprise-grade project generator
https://ngx-rocket.github.io/
MIT License
1.53k stars 216 forks source link

Contribution: Redirect to previously saved url after login, if you are not authenticated. #388

Closed LuisReinoso closed 5 years ago

LuisReinoso commented 5 years ago

I'm submitting a...

Current behavior

If I do click on link to my application but I'm not authenticated then redirect me to login page, after login not follow the original route, the application redirect me to home page.

Expected behavior

After authenticate me, redirect to original route (original link).

Minimal reproduction of the problem with instructions

Environment

- generator version: 5.0.1
- node version: 9.5.0 
- npm version: 6.1.0  
- OS: Linux

Others:

I want to contribute adding this feature. But please review my idea.

Explanation

On authentication.guard.ts save the url to be redirected. This would be saved on authentication.service.ts

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authenticationService.isAuthenticated()) {
      return true;
    }

    log.debug('Not authenticated, redirecting...');
    this.authenticationService.redirctUrl = state.url;  // save url
    this.router.navigate(['/login'], { replaceUrl: true });
    return false;
}

On login.component.ts in login() function

  login() {
    this.isLoading = true;
    this.authenticationService.login(this.loginForm.value)
      .pipe(finalize(() => {
        this.loginForm.markAsPristine();
        this.isLoading = false;
      }))
      .subscribe(credentials => {
        log.debug(`${credentials.username} successfully logged in`);
        if (this.authenticationService.redirctUrl) { //check url
        this.router.navigate([this.authenticationService.redirctUrl], { replaceUrl: true });
        } else {
        this.router.navigate(['/'], { replaceUrl: true });
        }
      }, error => {
        log.debug(`Login error: ${error}`);
        this.error = error;
      });

That's all. Thanks.

sinedied commented 5 years ago

Closed by #390