Skip to content

Commit 9b3561d

Browse files
committed
15.14 Autologin
1 parent 0609a7e commit 9b3561d

File tree

4 files changed

+92
-18
lines changed

4 files changed

+92
-18
lines changed

package-lock.json

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
"@capacitor/android": "^5.0.2",
2525
"@capacitor/camera": "^5.0.2",
2626
"@capacitor/core": "5.0.2",
27+
"@capacitor/preferences": "^5.0.2",
2728
"@capacitor/splash-screen": "^5.0.2",
2829
"@ionic/angular": "^7.0.0",
2930
"@ionic/pwa-elements": "^3.1.1",

src/app/auth/auth.guard.ts

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Injectable } from '@angular/core';
22
import { ActivatedRouteSnapshot, CanLoad, Route, Router, RouterStateSnapshot, UrlSegment, UrlTree } from '@angular/router';
3-
import { Observable, take, tap } from 'rxjs';
3+
import { Observable, of, switchMap, take, tap } from 'rxjs';
44
import { AuthService } from './auth.service';
55

66
@Injectable({
@@ -9,11 +9,21 @@ import { AuthService } from './auth.service';
99
export class AuthGuard implements CanLoad {
1010
constructor(private authService: AuthService, private router: Router){}
1111
canLoad(route: Route, segments: UrlSegment[]): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
12-
return this.authService.userIsAuthenticated.pipe(take(1), tap(isAuthenticated => {
13-
if(!isAuthenticated){
14-
this.router.navigateByUrl('/auth');
15-
}
16-
}));
12+
return this.authService.userIsAuthenticated.pipe(
13+
take(1),
14+
switchMap(isAuthenticated => {
15+
if (!isAuthenticated) {
16+
return this.authService.autoLogin();
17+
} else {
18+
return of(isAuthenticated);
19+
}
20+
}),
21+
tap((isAuthenticated) => {
22+
if (!isAuthenticated) {
23+
this.router.navigateByUrl('/auth');
24+
}
25+
})
26+
);
1727
}
1828

1929
}

src/app/auth/auth.service.ts

Lines changed: 66 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { HttpClient } from '@angular/common/http';
22
import { Injectable } from '@angular/core';
33
import { environment } from '../../environments/environment';
4-
import { BehaviorSubject, map, tap } from 'rxjs';
4+
import { BehaviorSubject, from, map, tap } from 'rxjs';
55
import { User } from './user.model';
6+
import { Preferences } from '@capacitor/preferences';;
67

78
export interface AuthResponseData {
89
kind: string;
@@ -44,6 +45,39 @@ export class AuthService {
4445
}
4546
constructor(private http: HttpClient) {}
4647

48+
autoLogin() {
49+
return from(Preferences.get({ key: 'authData' })).pipe(
50+
map((storedData) => {
51+
if (!storedData || !storedData.value) {
52+
return null;
53+
}
54+
const parsedData = JSON.parse(storedData.value) as {
55+
token: string;
56+
tokenExpirationDate: string;
57+
userId: string;
58+
email: string;
59+
};
60+
const expirationTime = new Date(parsedData.tokenExpirationDate);
61+
if(expirationTime <= new Date()){
62+
return null;
63+
}
64+
const user = new User(
65+
parsedData.userId,
66+
parsedData.email,
67+
parsedData.token,
68+
expirationTime
69+
);
70+
return user;
71+
}), tap(user => {
72+
if(user) {
73+
this._user.next(user);
74+
}
75+
}), map(user => {
76+
return !!user;
77+
})
78+
);
79+
}
80+
4781
signup(email: string, password: string) {
4882
return this.http
4983
.post<AuthResponseData>(
@@ -54,25 +88,45 @@ export class AuthService {
5488
}
5589

5690
login(email: string, password: string) {
57-
return this.http.post<AuthResponseData>(
58-
`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${environment.firebaseAPIKey}`,
59-
{ email: email, password: password, returnSecureToken: true }
60-
).pipe(tap(this.setUserData.bind(this)));
91+
return this.http
92+
.post<AuthResponseData>(
93+
`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${environment.firebaseAPIKey}`,
94+
{ email: email, password: password, returnSecureToken: true }
95+
)
96+
.pipe(tap(this.setUserData.bind(this)));
6197
}
6298

6399
logout() {
64100
this._user.next(null);
65101
}
66102

67103
private setUserData(userData: AuthResponseData) {
68-
const expTime = new Date().getTime() + +userData.expiresIn * 1000;
104+
const expTime = new Date(new Date().getTime() + +userData.expiresIn * 1000);
69105
this._user.next(
70-
new User(
71-
userData.localId,
72-
userData.email,
73-
userData.idToken,
74-
new Date(expTime)
75-
)
106+
new User(userData.localId, userData.email, userData.idToken, expTime)
107+
);
108+
this.storeAuthData(
109+
userData.localId,
110+
userData.idToken,
111+
expTime.toISOString(),
112+
userData.email
76113
);
77114
}
115+
116+
private storeAuthData(
117+
userId: string,
118+
token: string,
119+
tokenExpirationDate: string,
120+
email: string
121+
) {
122+
Preferences.set({
123+
key: 'authData',
124+
value: JSON.stringify({
125+
userId: userId,
126+
token: token,
127+
tokenExpirationDate: tokenExpirationDate,
128+
email: email
129+
}),
130+
});
131+
}
78132
}

0 commit comments

Comments
 (0)