Search code examples
angulartypescriptfirebase-authenticationangularfire2ngrx

Check Auth state from Firebase with Ngrx


I am trying to check the authentication status of my application, verifying that it has an authenticated user.

I have an initial state where logged is false, and when I try to check in CanActivate(), logged is being returned as false.

I checked in Redux DevTools and the auth state is changed, so the logged value is changed to true.

what am I doing wrong? How can I validate if the user is authenticated using NGRX?

guard.ts

 constructor(
    private _store: Store<fromAuth.AuthState>
  ) { }

 canActivate(): Observable<boolean> {
      return this.checkUserLogged(); // Return is always false 
 }

 private checkUserLogged() {
      return this._store.select(fromAuth.isLogged).pipe(take(1));
 }

app.component.ts

    import { Store } from '@ngrx/store';
    import * as fromAuth from '@myapp/store/reducers/auth.reducer';
    import * as authActions from '@myapp/store/actions/auth.actions';

     constructor(
         private _store: Store<fromAuth.AuthState>,
     ) {

    this._store.dispatch(new authActions.GetUser());

auth.reducer.ts

 export interface AuthState {
     logged: boolean;
 ;

 export const initialState: AuthState = {
     logged: false,
 };


 export function authReducer(state = initialState, action: Action): 
    AuthState {

switch (action.type) {

    case authActions.GET_USER:
        return {
            ...state,
            logged: false
        };

    case authActions.AUTHENTICATED:
        return {
            ...state,
            ...action.payload,
            loading: false,
            logged: true,
        };

      // emitted ....

 }

 export const getAuthState = createFeatureSelector<AuthState>('auth');

 export const isLogged = createSelector(
     getAuthState, (state: AuthState) => 
     state.logged);

auth.effects.ts

@Injectable({
    providedIn: 'root'
})

export class AuthEffects {

constructor(
    private _actions: Actions,
    private _angularFireAuth: AngularFireAuth) { }

@Effect()
getUser$: Observable<Action> = this._actions.pipe(
    ofType(authActions.GET_USER),
    switchMap(() => this._angularFireAuth.authState),
    switchMap(user => forkJoin([
        from(user.getIdTokenResult(true)), of(user)])
        .pipe(map(([token, user]) => {

            if (user) {
                const authState = {
                    firestoreCollection: token.claims.firestoreCollection,
                    user: {
                        admin: token.claims.admin,
                        uid: user.uid,
                        displayName: user.displayName
                    }
                };

                // You are returning this action
                // Soon after logged in should be true.
                return new authActions.Authenticated(authState);

            } else {
                return new authActions.NotAuthenticated();
            }
        }))),
    catchError((error) => of(new authActions.AuthError(error)))
)

}


Solution

  • Since you already have logged state in the reducer you can write index.ts file to get the data from the store like this

    import * as fromRoot from '@core/store/reducers/index';
    import { AuthState } from './reducers/auth.reducer';
    import { createFeatureSelector, createSelector } from '@ngrx/store';
    
    export interface State extends fromRoot.State {
      auth: AuthState;
    }
    
    export const selectAuthState = createFeatureSelector<AuthState>('authModule');
    
    export const selectIsLoginState = createSelector(
      selectAuthState,
      state => state.logged
    );
    

    Basically you need to create selector to get data from the store using createFeatureSelector, createSelector