I am on the way to create my first Progressive web app which uses firebase for storing data. I am also using Gmail as an entry point for all the users that would us
I had almost same behavior on my pet web app. For my self I solve it by the next steps:
app.module.ts @NgModule({
...
providers: [
{ provide: APP_INITIALIZER, useFactory: appConfig, deps: [AuthService], multi: true }
]
})
export function appConfig(authService) {
const app = firebase.initializeApp({
apiKey
authDomain
});
return () => new Promise((resolve, reject) => {
firebase.auth()
.onAuthStateChanged(data => {
if (data) {
firebase.auth().currentUser.getToken()
.then((token: string) => authService.setToken(token););
}
resolve(true);
}, error => resolve(true));
});
}
auth.guard.tsexport class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authService.isAuthenticated()) {
return true;
} else {
this.router.navigate(['/signin']);
return false;
}
}
}
auth.service.tsexport class AuthService {
token: string;
signinUser(email: string, password: string) {
return new Promise((resolve, reject) => {
firebase.auth().signInWithEmailAndPassword(email, password)
.then(resp => {
firebase.auth().currentUser.getToken()
.then((token: string) => {
this.token = token;
resolve(resp);
}).catch(reject);
return resp;
})
.catch(reject);
});
}
signoutUser() {
return firebase.auth().signOut()
.then(resp => this.token = null);
}
getToken() {
firebase.auth().currentUser.getToken()
.then((token: string) => this.setToken(token));
return this.token;
}
setToken(token) {
this.token = token;
}
isAuthenticated() {
return this.token != null;
}
}
I hope it will be helpful for you.