I'm an Angular newbie working on user authentication (IDE: VS Code) (using auth0 as authentication service). My problem is that when I try to use the function below, "get", "authenticated", and "boolean" all come up underlined in red, and I don't know what's going on. Basically, the function is supposed to check whether the parsed argument is true or not:
get authenticated(): boolean {
return JSON.parse(localStorage.getItem(this._authFlag) || '{}');
}
VS Code tells me it cannot find the names "get" and "authenticated", which I'm assuming is leading to the error of boolean needing to be a type and not a value. Any ideas on what I'm doing wrong? Here's the full component file:
import { Injectable } from '@angular/core';
//npm install --save @types/auth0-js (CLI cmd)
import * as auth0 from 'auth0-js';
import { environment } from '../../environments/environment';
import{
Observable,
BehaviorSubject,
bindNodeCallback,
of
} from 'rxjs';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthService {
auth0 = new auth0.WebAuth({
clientID: environment.auth0.clientID,
domain: environment.auth0.domain,
responseType: 'token id_token',
scope: 'openid profile email'
});
//Track whether or not to renew token
private _authFlag = 'isLoggedIn';
private _userProfileFlag = 'userProfile';
//Store authentication data & create stream for token
token$!: Observable<string>;
//Create stream for user profile data
userProfile$ = new BehaviorSubject<any>(null);
//Authentication Navigation
onAuthSuccessUrl = '/';
onAuthFailureUrl = '/';
logoutUrl = environment.auth0.logoutUrl;
//Create observable of Auth0, then parseHash() function to gather 'auth' results
parseHash$ = bindNodeCallback(this.auth0.parseHash.bind(this.auth0));
//Create observable of Auth0 checkSession() function to verify authorization server session and renew tokens
checkSession$ = bindNodeCallback(this.auth0.checkSession.bind(this.auth0));
constructor(private router: Router) {
const userProfile = localStorage.getItem(this._userProfileFlag);
if (userProfile) {
this.userProfile$.next(JSON.parse(userProfile));
}
}
login = () => this.auth0.authorize();
handleLoginCallback = () => {
if (window.location.hash && !this.authenticated) {
this.parseHash$().subscribe({
next: authResult => {
this._setAuth(authResult);
window.location.hash = '';
this.router.navigate([this.onAuthSuccessUrl]);
},
error: err => this._handleError(err)
});
}
};
//Save authentication data and update login status subject
private _setAuth = (authResult: any) => {
//Observable of token
this.token$ = of(authResult.accessToken);
const userProfile = authResult.idTokenPayload;
//Emit value for user data subject
this.userProfile$.next(userProfile);
//save 'userProfile' in 'localStorage'
localStorage.setItem(this._userProfileFlag, JSON.stringify(userProfile));
//Set flag in local storage stating that this app is logged in
localStorage.setItem(this._authFlag, JSON.stringify(true));
const renewAuth = () => {
if (this.authenticated) {
this.checkSession$({}).subscribe({
next: authResult => this._setAuth(authResult),
error: err => {
localStorage.removeItem(this._authFlag);
localStorage.removeItem(this._userProfileFlag);
this.router.navigate([this.onAuthFailureUrl]);
}
});
}
}
const logout = () => {
//Set authentication status flag in local storage to false
localStorage.setItem(this._authFlag, JSON.stringify(false));
//remove the userProfile data
localStorage.removeItem(this._userProfileFlag);
//refresh, then redirect to homepage
this.auth0.logout({
returnTo: this.logoutUrl,
clientID: environment.auth0.clientID
});
};
get authenticated(): boolean {
return JSON.parse(localStorage.getItem(this._authFlag) || '{}');
}
}
//Utility functions
private _handleError = (err: { error_description: any; }) => {
if (err.error_description) {
console.error(`Error: ${err.error_description}`);
} else {
console.error(`Error: ${JSON.stringify(err)}`);
}
};
}
CodePudding user response:
Issue 1: authenticated
getter placed in wrong place
From your code,
private _setAuth = (authResult: any) => {
...
get authenticated(): boolean {
return JSON.parse(localStorage.getItem(this._authFlag) || '{}');
}
}
Solution for Issue 1: Move out authenticated
getter of _setAuth
method.
private _setAuth = (authResult: any) => {
...
}
get authenticated(): boolean {
return JSON.parse(localStorage.getItem(this._authFlag) || '{}');
}
Issue 2: Duplicate variable name authenticated
with getter authenticated
.
You don't need to create variable while you have authenticated
getter. Otherwise it is conflicted with variable name
Solution for Issue 2: Remove the variable declaration.
authenticated!: boolean;