-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathauth.effects.ts
More file actions
105 lines (100 loc) · 2.8 KB
/
auth.effects.ts
File metadata and controls
105 lines (100 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { Store } from '@ngrx/store';
import { of } from 'rxjs';
import {
catchError,
concatMap,
distinctUntilChanged,
exhaustMap,
map,
switchMap,
tap,
} from 'rxjs/operators';
import { UserService } from 'src/app/user/services/user.service';
import { AuthService } from '../../auth/services/auth.service';
import {
fetchAuthenticatedUserDataFailure,
fetchAuthenticatedUserDataSuccess,
removeUserToken,
saveUserToken,
saveUserTokenFailure,
saveUserTokenSuccess,
signInUser,
signOutUser,
userTokenExists,
} from './auth.actions';
import { selectAuthUserName } from './auth.selectors';
import { userApiToAuthUserData } from './auth.mappings';
@Injectable()
export class AuthEffects {
/**
* Start the OAuth sign in process for the user - does not dispatch
* since it does not need to return a new action
*/
signIn$ = createEffect(
() =>
this.actions$.pipe(
ofType(signInUser),
tap(() => this.authService.signIn()),
),
{ dispatch: false },
);
/**
* Start the sign out process for the user
*/
signOut$ = createEffect(() => {
return this.actions$.pipe(
ofType(signOutUser),
tap(() => this.authService.signOut()),
tap(() => this.router.navigate(['/signin'])),
switchMap(() => of(removeUserToken({ isAuthenticated: false }))),
);
});
/**
* Saves the resulting access_token for the user
*/
saveUserToken$ = createEffect(() => {
return this.actions$.pipe(
ofType(saveUserToken),
concatMap(() =>
this.authService.saveUserToken().pipe(
map(() => saveUserTokenSuccess({ isAuthenticated: true })),
catchError((error) => of(saveUserTokenFailure({ error }))),
),
),
);
});
/**
* Gets authenticated user's name, photo, and email
*/
fetchAuthUserData$ = createEffect(() => {
return this.actions$.pipe(
ofType(saveUserTokenSuccess, userTokenExists),
switchMap(() =>
this.store.select(selectAuthUserName).pipe(
distinctUntilChanged(),
exhaustMap(() =>
this.userService.getAuthenticatedUserInfo().pipe(
map((apiResponse) => {
const userData = userApiToAuthUserData(apiResponse);
return fetchAuthenticatedUserDataSuccess({ userData });
}),
catchError((error) =>
of(fetchAuthenticatedUserDataFailure({ error })),
),
),
),
),
),
);
});
constructor(
private actions$: Actions,
private store: Store,
private authService: AuthService,
private userService: UserService,
private router: Router,
) {}
}