Skip to content

Instantly share code, notes, and snippets.

@Rohithv07
Created August 3, 2021 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rohithv07/b379053e4002e613dad5c3d3590b970e to your computer and use it in GitHub Desktop.
Save Rohithv07/b379053e4002e613dad5c3d3590b970e to your computer and use it in GitHub Desktop.
Why my username displayed on the nav bar is not shown until I refresh the page again after I login.
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { ReplaySubject, Subject, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { User } from './auth/user.model';
export interface AuthResponseData {
kind: string,
idToken: string,
email: string,
refreshToken: string,
expiresIn: string,
localId: string,
registered?: boolean;
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
user = new ReplaySubject<User>(1);
userLoggedIn = ''
private tokenExpirationTimer: any;
constructor(private http: HttpClient, private router: Router) { }
isLoggedIn() {
return localStorage.getItem('userData');
}
signup(email: string, password: string) {
return this.http.post<AuthResponseData>(
'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=key',
{
email: email,
password: password,
returnSecureToken: true
}
).pipe(catchError(this.handleError),
tap(resData => {
this.handleAuthentication(resData.email, resData.localId, resData.idToken, +resData.expiresIn);
}));
}
login(email: string, password: string) {
return this.http.post<AuthResponseData>(
'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=key',
{
email: email,
password: password,
returnSecureToken: true
}
).pipe(catchError(this.handleError),
tap(resData => {
this.handleAuthentication(resData.email, resData.localId, resData.idToken, +resData.expiresIn);
}));
}
logout() {
this.user.next(undefined);
this.router.navigate(['/auth']);
localStorage.removeItem('userData');
if (this.tokenExpirationTimer) {
clearTimeout(this.tokenExpirationTimer);
}
this.tokenExpirationTimer = null;
}
// refresh and stays logged in
autoLogin() {
const userData: {
email: string;
id: string;
_token: string;
_tokenExpirationDate: string;
} = JSON.parse(localStorage.getItem('userData') || '{}');
this.userLoggedIn = userData.email;
if (!userData)
return;
const loadedUser = new User(userData.email, userData.id, userData._token, new Date(userData._tokenExpirationDate));
if (loadedUser.token) {
this.user.next(loadedUser);
const expirationDuration = new Date(userData._tokenExpirationDate).getTime() - new Date().getTime();
this.autoLogout(expirationDuration);
}
}
get username(): string {
return this.userLoggedIn;
}
autoLogout(expirationDuration: number) {
this.tokenExpirationTimer = setTimeout(() => {
this.logout();
}, expirationDuration);
}
private handleAuthentication(email: string, userId: string, token: string, expiresIn: number) {
const expirationDate = new Date(new Date().getTime() + expiresIn * 1000);
const user = new User(email, userId, token, expirationDate);
this.user.next(user);
this.autoLogout(expiresIn * 1000);
localStorage.setItem('userData', JSON.stringify(user));
}
private handleError(errorRes: HttpErrorResponse) {
let errorMessage = 'An unknown error occured';
if (!errorRes.error || !errorRes.error.error) {
return throwError(errorMessage);
}
switch(errorRes.error.error.message) {
case 'EMAIL_EXISTS':
errorMessage = 'The email address is already in use by another account.';break;
case 'OPERATION_NOT_ALLOWED':
errorMessage = 'Password sign-in is disabled for this project.'; break;
case 'TOO_MANY_ATTEMPTS_TRY_LATER':
errorMessage = 'We have blocked all requests from this device due to unusual activity. Try again later.';break;
case 'EMAIL_NOT_FOUND':
errorMessage = 'There is no user record corresponding to this identifier. The user may have been deleted.';break;
case 'INVALID_PASSWORD':
errorMessage = 'The password is invalid or the user does not have a password.';break;
case 'USER_DISABLED':
errorMessage = 'The user account has been disabled by an administrator.';break;
}
return throwError(errorMessage);
}
}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<div class="navbar-header" *ngIf="isAuthenticated">
<a class="navbar-brand" routerLink="/currency">
<img src="https://images.unsplash.com/photo-1574607383476-f517f260d30b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=967&q=80"
width="30" height="30" class="d-inline-block align-top" alt="">
Currency Conversion</a>
</div>
<div class="navbar-default">
<ul class="nav navbar-nav navbar-right">
<li>
<div class="btn btn-outline-info" *ngIf="isAuthenticated" >Welcome {{ username }}</div>
<button class="btn btn-outline-success" type="button" (click)="onLogout()" *ngIf="isAuthenticated">Logout</button>
</li>
</ul>
<!-- </div> -->
</div>
</div>
</nav>
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, Subscription } from 'rxjs';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-nav-bar',
templateUrl: './nav-bar.component.html',
styleUrls: ['./nav-bar.component.css']
})
export class NavBarComponent implements OnInit, OnDestroy {
isAuthenticated = false;
username = '';
private userSub!: Subscription;
constructor(private authService : AuthService) {
}
onLogout() {
this.authService.logout();
}
ngOnInit(): void {
this.userSub = this.authService.user.subscribe(u => {
// this.isAuthenticated = !u ? false : true;
// console.log(this.isAuthenticated);
this.isAuthenticated = !!u;
});
this.username = JSON.parse(localStorage.getItem('userData') || '{}').email;
}
ngOnDestroy(): void {
this.userSub.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment