Skip to content

Commit

Permalink
fix: keep route on refresh (fetch auth info in login guard)
Browse files Browse the repository at this point in the history
  • Loading branch information
makimenko committed Nov 29, 2023
1 parent cd4a01b commit 66a0130
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 52 deletions.
12 changes: 5 additions & 7 deletions src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,11 @@ export class AppComponent implements OnInit {
}

async ngOnInit() {
console.log("AppComponent.ngOnInit");
if (await this.auth.checkIfUserAuthenticated()) {
this.router.navigate(['/manager']);
} else {
this.router.navigate(['/login']);
}
console.log("AppComponent.ngOnInit end");
// console.log("AppComponent.ngOnInit");
// if (!await this.auth.checkIfUserAuthenticated()) {
// this.router.navigate(['/login']);
// }
// console.log("AppComponent.ngOnInit end");
}


Expand Down
69 changes: 30 additions & 39 deletions src/app/general/service/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ export type Profile = {
};

const AUTH_KEY = 'vect.AuthService.auth';

declare let gapi: any;
const GOOGLE_PROFILE_URL = `https://www.googleapis.com/oauth2/v3/userinfo`;


@Injectable()
export class AuthService {
Expand All @@ -34,18 +35,18 @@ export class AuthService {
}


public async checkIfUserAuthenticated(): Promise<boolean> {
console.log('AuthService.checkIfUserAuthenticated before', this.userAuthenticated);
if (!this.userAuthenticated) {
await this.init();
const storedAccessToken = localStorage.getItem(AUTH_KEY);
if (storedAccessToken) {
this.requestProfile(storedAccessToken);
this.accessToken = storedAccessToken;
}
}
console.log('AuthService.checkIfUserAuthenticated after', this.userAuthenticated);
return this.userAuthenticated;
public async checkIfUserAuthenticated(): Promise<boolean> {
console.log('AuthService.checkIfUserAuthenticated before', this.userAuthenticated);
if (!this.userAuthenticated) {
await this.init();
const storedAccessToken = localStorage.getItem(AUTH_KEY);
if (storedAccessToken) {
await this.requestProfile(storedAccessToken);
this.accessToken = storedAccessToken;
}
}
console.log('AuthService.checkIfUserAuthenticated after', this.userAuthenticated);
return this.userAuthenticated;
}


Expand Down Expand Up @@ -83,7 +84,7 @@ export class AuthService {
throw (res);
}
if (res && res.access_token) {
this.requestProfile(res.access_token);
await this.requestProfile(res.access_token);

// wrong location?
// gapi.client.setApiKey(environment.gapi.api_key);
Expand All @@ -95,36 +96,26 @@ export class AuthService {
}


requestProfile(accessToken: string): void {
async requestProfile(accessToken: string): Promise<void> {
console.log('AuthService.requestProfile', accessToken);
const p1 = new Promise(function(resolve, reject) {
const req = new XMLHttpRequest();
const url = `https://www.googleapis.com/oauth2/v3/userinfo`;
req.addEventListener('loadend', function() {
const response = JSON.parse(this.responseText);
console.log('AuthService.requestProfile loadend response', response);
if (this.status === 200) {
resolve(response);
} else {
// @ts-ignore
reject(this, response);
}
});
req.open('GET', url, true);
req.setRequestHeader('Authorization', `Bearer ${accessToken}`);
req.send();
});

console.log('AuthService.requestProfile then');
p1.then(
this.handleProfileResponse,
function(errorMessage) {
console.error(errorMessage);
});
const res = await fetch(GOOGLE_PROFILE_URL, {
method: 'get',
headers: new Headers({
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json'
})
});

if (res.ok) {
const profileResponse = await res.json();
await this.handleProfileResponse(profileResponse);
}
console.log('AuthService.requestProfile end');
}

handleProfileResponse(profileResponse: any): void {

private async handleProfileResponse(profileResponse: any) {
console.log('AuthService.handleProfileResponse response', profileResponse);
this.profile = {
name: profileResponse.name,
Expand Down
6 changes: 3 additions & 3 deletions src/app/general/service/logged-in.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ export class LoggedInGuard implements CanActivate {
}

public async canActivate(): Promise<boolean> {
const canActivate = this.authService.checkIfUserAuthenticated();
console.log("LoggedInGuard.canActivate", canActivate);
return canActivate;
const userAuthenticated = await this.authService.checkIfUserAuthenticated();
console.log("LoggedInGuard.canActivate", userAuthenticated);
return userAuthenticated;
}

}
10 changes: 7 additions & 3 deletions src/app/manager/manager-panel/manager-panel.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,18 @@ export class ManagerPanelComponent implements OnInit {
protected diagramService: DiagramService,
private router: Router
) {
this.auth.authenticatedEvent.subscribe({
next: (value: Profile) => this.name = value.name
});
}

ngOnInit(): void {
if (this.auth.profile) {
this.updateProfileInfo(this.auth.profile);
}
}

updateProfileInfo(profile: Profile) {
console.log('ManagerPanelComponent.handleProfileUpdate');
this.name = profile.name;
}

public createNewDiagram(): void {
// console.log('ManagerPanelComponent.createNewDiagram');
Expand Down

0 comments on commit 66a0130

Please sign in to comment.