1
votes

I'm unable to find an example for using emailVerified AngularFire2 exported pipe to redirect a user whose email is not yet verified from specific routes.

Use cases on how to use redirectLoggedInTo(redirect), redirectUnauthorizedTo(redirect) and hasCustomClaim(claim) are provided.

The AngularFire team has conveniently avoided putting an example on their GitHub page here: https://github.com/angular/angularfire/blob/master/docs/auth/router-guards.md

enter image description here

1

1 Answers

0
votes

In the source code emailVerified is:

export const emailVerified: AuthPipe = map(user => !!user && user.emailVerified)

So you can use a second map like this:

import { AngularFireAuthGuard, emailVerified } from '@angular/fire/auth-guard'
import { map } from 'rxjs/operators'

...

const redirectUnverifiedUser = () =>
  pipe(
    emailVerified,
    map(emailVerified => {
      if (emailVerified) {
        return true;
      } else {
        return ['login', 'verify-email']
      }
    })
  );

...and then in your route config:

{
  path: 'example',
  ...
  canActivate: [AngularFireAuthGuard],
  data: { authGuardPipe: redirectUnverifiedUser },
},

If you need to redirect an unauthorized user to your login page but also redirect an authorized user who has not verified their email to a different page then you can use this:

import { AngularFireAuthGuard, AuthPipeGenerator } from '@angular/fire/auth-guard'
import { map } from 'rxjs/operators'

...

const redirectUnauthorizedOrUnverifiedUser: AuthPipeGenerator = () =>
  map(user => {
    if (user) {
      if (user.emailVerified) {
        return true
      } else {
        return ['login', 'verify-email']
      }
    } else {
      return ['login']
    }
  })

...and then in your route config:

{
  path: 'example',
  ...
  canActivate: [AngularFireAuthGuard],
  data: { authGuardPipe: redirectUnauthorizedOrUnverifiedUser },
},