Search code examples
angularangular-routingangular-routerangular-router-guards

Implement Angular guard on password reset route


I'm having an issue trying to figure out how to validate the password-reset route when the user tries to enter manually in the URL. The correct functionality is that the users will go the forgot-password route and from there, an email will be sent to them; the email will contain the URL pointing to the password-reset route and it will contain the token. My innefficient workaround is creating a guard specific for the password-reset route and I'm validating if the token is passed in the URL as a query parameter; here is the code:

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (Object.keys(next.queryParams).includes('token')) {
  return true;
}
this.router.navigate(['/login']);
return false;

}

As you can see this code has an inconvenience: if the users write the token in the URL it will allow them to enter the route.

Is there a way to detect if the navigation comes from an email and validate based on that? Thanks in advance.


Solution

  • One of the ways we did this in the past was - Editing My Comment

    1. Once the forgot-password Link is Clicked, post to server.
    2. Server generates token, Stores it, Sends as a Link (url paramed)
    3. User clicks Link in the email.
    4. Route Guard of password-reset asks Server if the token is valid.
    5. If Yes -> Server Issue response with a temp cookie that you will use to validate the next action/actions
    6. If No Route Guard sends user to a generic error page in an unauthenticated area in the app.

    Would this answer your question clearly