I believe there are two potential approaches to handle visibility restrictions for your components.
In our application, we manage login and authentication through our auth.service.ts file.
// auth.service.ts
@Injectable({
providedIn: 'root'
})
export class AuthService {
private token: string;
private loggedIn = false;
constructor(private http: HttpClient) {}
getLoggedIn() {
return this.loggedIn;
}
login(email:string, password:string): Promise <string> {
const promise = new Promise < string > ((resolve, reject) => {
const authData = { email: email, password: password }
this.http.post < { token: string } > (environment.backendUrl + '/api/user/login', authData).toPromise()
.then(response => {
const token = response.token;
this.token = token;
if (token) {
this.loggedIn = true;
}
}
As shown in the above snippet, once a successful login occurs, we receive a token in our response body, similar to how tokens are obtained in your application. This token is then assigned to the token variable within our auth.service.ts file. Subsequently, we can access this token by calling the getLoggedIn() function from any part of the application after importing the auth.service.ts file.
To restrict component visibility based on the presence of a token, one approach involves importing the auth.service.ts file into the desired component and initializing it in the constructor as follows:
// .ts file where you want to restrict visibility
export class component {
loggedIn = false;
constructor(private authService: AuthService) {}
ngOnInit() {
this.loggedIn = this.authService.getLoggedIn();
}
The component checks for a token during the ngOnInit lifecycle hook. By leveraging the loggedIn variable with an *ngIf directive in the corresponding HTML file, we can selectively display certain elements or the entire component.
// .html file
<div *ngIf=loggedIn>
<h1> title </h1>
<p> here you be your text </p>
</div>
Alternatively, another method involves implementing a guard mechanism, as previously suggested by Mikhail and Gytis. This guard validates the presence of a token before routing to specific pages, ensuring that only authenticated users can access them. This can be achieved by creating an auth.guard.ts file:
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean | Observable < boolean > | Promise < boolean > {
const loggedIn = this.authService.getLoggedIn();
if (!loggedIn) {
this.router.navigate(['/login']);
}
return loggedIn;
}
}
By incorporating this guard, we can enforce token validation in our app-routing.ts configuration:
// app-routing.ts file
const routes: Routes = [
{ path: "", component: HomePageComponent },
{ path: "home", component: HomePageComponent },
{ path: "login", component: LoginPageComponent },
{ path: "signup", component: SignupPageComponent },
{ path: "profile/:id", component: ProfilePageComponent, canActivate: [AuthGuard] },
]
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: [AuthGuard]
})
export class AppRoutingModule {}
In this setup, the profile page is protected by the AuthGuard, ensuring that only authenticated users can access it. If a user attempts to visit the page without logging in, they will be redirected to the login page. This additional layer of security prompts users to log in before accessing restricted content via manual URL entry.
I am relatively new to Stack Overflow, but I have endeavored to provide a comprehensive response in the hopes of assisting you. Have a wonderful day!