Why does the value not change to false in AuthGuard? - javascript

In the template component AppComponent, depending on the value, the variable this.loggedInService.isLoggedIn switches between the logIn() and logout() methods, which in the application component AppComponent are subscribed to these methods in the service LoggedinServiceand depending on the method, change the value of the variable to true or false.
Also in the Guard's method checkLogin (url: string) I return true or false depending on the value of the variable this.loggedInService.isLoggedIn.
When I start the application, I cannot enter the module, when I click on the button, I can, but when I repeat click on the button "exit", I can still go to the module.
How to make the switch to checkLogin work so that the authentication works correctly and save the value of switching the state between input and output when the page is restarted?
**AppComponent.html: **
<li class="nav-item">
<a class="btn btn-outline-success"
[class.btn-outline-success]="!this.loggedInService.isLoggedIn$"
[class.btn-outline-danger]="this.loggedInService.isLoggedIn$"
(click)="this.loggedInService.isLoggedIn$ ? logout() : logIn()">
{{this.loggedInService.isLoggedIn$ ? 'Exit' : 'Enter'}}
</a>
</li>
**AppComponent.ts **
export class AppComponent implements OnInit {
message: string;
constructor(public loggedInService: LoggedinService,
public router: Router) {
this.setMessage();
}
ngOnInit() {}
logIn(): void {
this.loggedInService.login().subscribe(() => {
if (this.loggedInService.isLoggedIn$) {
let redirect = this.loggedInService.redirectUrl ? this.loggedInService.redirectUrl :
'/gallery';
this.router.navigate([redirect]);
}
});
}
logout(): void {
this.loggedInService.logout();
}
}
LoggedinService:
export class LoggedinService {
isLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
isLoggedIn$: Observable<boolean> = this.isLoggedIn.asObservable();
redirectUrl: string;
constructor() {}
login(): Observable < boolean > {
return of(true).pipe(
delay(100),
tap(val => this.isLoggedIn.next(true))
);
}
logout(): void {
this.isLoggedIn.next(false);
}
}
AuthGuard:
export class AuthGuard implements CanActivate {
constructor(
private loggedInService: LoggedinService,
private router: Router
) {}
canActivate(next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> {
let url: string = state.url;
return this.loggedInService.isLoggedIn$;
}
checkLogin(url: string): boolean {
if (this.loggedInService.isLoggedIn) {
return true;
} else {
this.loggedInService.redirectUrl = url;
return false;
}
}
}

isLoggedIn in your LoggedinService is a Primitive Data type. So it is not passed by reference. It's passed by value. So if there is a change in it at one place, the same change won't reflect at other places where it is used.
This behavior is only exhibited by Objects as they are passed by reference and NOT value.
You could use a BehaviorSubject to fix this issue.
import { Injectable } from '#angular/core';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { Router } from '#angular/router';
import { delay, tap } from 'rxjs/operators';
#Injectable()
export class LoggedinService {
isLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
isLoggedIn$: Observable<boolean> = this.isLoggedIn.asObservable();
redirectUrl: string;
constructor(private router: Router) { }
login(): Observable<boolean> {
this.isLoggedIn.next(true);
return this.isLoggedIn$;
}
logout(): Observable<boolean> {
this.isLoggedIn.next(false);
return this.isLoggedIn$;
}
}
Now, instead of isLoggedIn of type boolean, you'll get isLoggedIn$ of type Observable which you'll have to subscribe to, to get the logged in status of the user.
You'll have to .subscribe to this.loggedInService.login() and this.loggedInService.login() in your AppComponent as both of them return isLoggedIn$. You'll have to create a local isLoggedIn property and assign it whatever is returned in your .subscribe. You can then set the button text and click handler based on the template based on this isLoggedIn property.
In the case, of AuthGuard, since a guard can return Observable<boolean> or Promise<boolean> or boolean, you can simply return this.loggedInService.isLoggedIn$
Here's a Sample StackBlitz for your ref.

Related

route to a specific component in angular from email [duplicate]

I have my application up and running with Angular 2.1.0.
The routes are protected via router Guards, canActivate.
When pointing the browser to a protected area like "localhost:8080/customers" I get redirected to my login page just like expected.
But after a successful login, I would like to be redirected back to calling URL ("/customers" in this case).
The code for handling the login looks like this
login(event, username, password) {
event.preventDefault();
var success = this.loginService.login(username, password);
if (success) {
console.log(this.router);
this.router.navigate(['']);
} else {
console.log("Login failed, display error to user");
}
}
The problem is, I don't know how to get a hold of the calling url from inside the login method.
I did find a question (and answer) regarding this but couldn't really make any sense of it.
Angular2 Redirect After Login
There's a tutorial in the Angular Docs, Milestone 5: Route guards. One possible way to achieve this is by using your AuthGuard to check for your login status and store the url on your AuthService.
AuthGuard
import { Injectable } from '#angular/core';
import {
CanActivate, Router,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '#angular/router';
import { AuthService } from './auth.service';
#Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
if (this.authService.isLoggedIn) { return true; }
// Store the attempted URL for redirecting
this.authService.redirectUrl = url;
// Navigate to the login page with extras
this.router.navigate(['/login']);
return false;
}
}
AuthService or your LoginService
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Router } from '#angular/router';
#Injectable()
export class AuthService {
isLoggedIn: boolean = false;
// store the URL so we can redirect after logging in
public redirectUrl: string;
constructor (
private http: Http,
private router: Router
) {}
login(username, password): Observable<boolean> {
const body = {
username,
password
};
return this.http.post('api/login', JSON.stringify(body)).map((res: Response) => {
// do whatever with your response
this.isLoggedIn = true;
if (this.redirectUrl) {
this.router.navigate([this.redirectUrl]);
this.redirectUrl = null;
}
}
}
logout(): void {
this.isLoggedIn = false;
}
}
I think this will give an idea how things work, of course you probably need to adapt to your code
This code will handle your request:
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router) {
}
canActivate(next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> {
return this.authService.isVerified
.take(1)
.map((isVerified: boolean) => {
if (!isVerified) {
this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
return false;
// return true;
}
return true;
});
}
}
but be aware that the URL params will not pass with the URL!!
You can find a nice tutorial here :
http://jasonwatmore.com/post/2016/12/08/angular-2-redirect-to-previous-url-after-login-with-auth-guard
The answers I saw were correct.
But the best way to answer your question is returnUrl.
like this:
export class AuthGuardService implements CanActivate {
constructor(private auth: AuthenticationService, private router: Router) { }
canActivate(next: ActivatedRouteSnapshot,
_state: import('#angular/router').RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
let isLoggedIn = false;
const idToken = next && next.queryParamMap.get('id_token');
try {
const expiresAt = idToken && JSON.parse(window.atob(idToken.split('.')[1])).exp * 1000;
if (idToken && expiresAt) {
isLoggedIn = true;
localStorage.setItem('id_token', idToken);
localStorage.setItem('expires_at', String(expiresAt));
} else {
isLoggedIn = this.auth.isLoggedIn();
}
} catch (e) {
console.error(e);
isLoggedIn = this.auth.isLoggedIn();
}
if (!isLoggedIn) {
//this section is important for you:
this.router.navigate(['/login'], { queryParams: { returnUrl: _state.url }});
}
return isLoggedIn;
}
}
This navigate create a url with returnUrl like a param, now you can read returnUrl from param.
GoodLuck.

Angular 4: reactive form control is stuck in pending state with a custom async validator

I am building an Angular 4 app that requires the BriteVerify email validation on form fields in several components. I am trying to implement this validation as a custom async validator that I can use with reactive forms. Currently, I can get the API response, but the control status is stuck in pending state. I get no errors so I am a bit confused. Please tell me what I am doing wrong. Here is my code.
Component
import { Component,
OnInit } from '#angular/core';
import { FormBuilder,
FormGroup,
FormControl,
Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { EmailValidationService } from '../services/email-validation.service';
import { CustomValidators } from '../utilities/custom-validators/custom-validators';
#Component({
templateUrl: './email-form.component.html',
styleUrls: ['./email-form.component.sass']
})
export class EmailFormComponent implements OnInit {
public emailForm: FormGroup;
public formSubmitted: Boolean;
public emailSent: Boolean;
constructor(
private router: Router,
private builder: FormBuilder,
private service: EmailValidationService
) { }
ngOnInit() {
this.formSubmitted = false;
this.emailForm = this.builder.group({
email: [ '', [ Validators.required ], [ CustomValidators.briteVerifyValidator(this.service) ] ]
});
}
get email() {
return this.emailForm.get('email');
}
// rest of logic
}
Validator class
import { AbstractControl } from '#angular/forms';
import { EmailValidationService } from '../../services/email-validation.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
export class CustomValidators {
static briteVerifyValidator(service: EmailValidationService) {
return (control: AbstractControl) => {
if (!control.valueChanges) {
return Observable.of(null);
} else {
return control.valueChanges
.debounceTime(1000)
.distinctUntilChanged()
.switchMap(value => service.validateEmail(value))
.map(data => {
return data.status === 'invalid' ? { invalid: true } : null;
});
}
}
}
}
Service
import { Injectable } from '#angular/core';
import { HttpClient,
HttpParams } from '#angular/common/http';
interface EmailValidationResponse {
address: string,
account: string,
domain: string,
status: string,
connected: string,
disposable: boolean,
role_address: boolean,
error_code?: string,
error?: string,
duration: number
}
#Injectable()
export class EmailValidationService {
public emailValidationUrl = 'https://briteverifyendpoint.com';
constructor(
private http: HttpClient
) { }
validateEmail(value) {
let params = new HttpParams();
params = params.append('address', value);
return this.http.get<EmailValidationResponse>(this.emailValidationUrl, {
params: params
});
}
}
Template (just form)
<form class="email-form" [formGroup]="emailForm" (ngSubmit)="sendEmail()">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<fieldset class="form-group required" [ngClass]="{ 'has-error': email.invalid && formSubmitted }">
<div>{{ email.status }}</div>
<label class="control-label" for="email">Email</label>
<input class="form-control input-lg" name="email" id="email" formControlName="email">
<ng-container *ngIf="email.invalid && formSubmitted">
<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Please enter valid email address.
</ng-container>
</fieldset>
<button type="submit" class="btn btn-primary btn-lg btn-block">Send</button>
</div>
</div>
</form>
There's a gotcha!
That is, your observable never completes...
This is happening because the observable never completes, so Angular does not know when to change the form status. So remember your observable must to complete.
You can accomplish this in many ways, for example, you can call the first() method, or if you are creating your own observable, you can call the complete method on the observer.
So you can use first()
UPDATE TO RXJS 6:
briteVerifyValidator(service: Service) {
return (control: AbstractControl) => {
if (!control.valueChanges) {
return of(null);
} else {
return control.valueChanges.pipe(
debounceTime(1000),
distinctUntilChanged(),
switchMap(value => service.getData(value)),
map(data => {
return data.status === 'invalid' ? { invalid: true } : null;
})
).pipe(first())
}
}
}
A slightly modified validator, i.e always returns error: STACKBLITZ
OLD:
.map(data => {
return data.status === 'invalid' ? { invalid: true } : null;
})
.first();
A slightly modified validator, i.e always returns error: STACKBLITZ
So what I did was to throw a 404 when the username was not taken and use the subscribe error path to resolve for null, and when I did get a response I resolved with an error. Another way would be to return a data property either filled width the username or empty
through the response object and use that insead of the 404
Ex.
In this example I bind (this) to be able to use my service inside the validator function
An extract of my component class ngOnInit()
//signup.component.ts
constructor(
private authService: AuthServic //this will be included with bind(this)
) {
ngOnInit() {
this.user = new FormGroup(
{
email: new FormControl("", Validators.required),
username: new FormControl(
"",
Validators.required,
CustomUserValidators.usernameUniqueValidator.bind(this) //the whole class
),
password: new FormControl("", Validators.required),
},
{ updateOn: "blur" });
}
An extract from my validator class
//user.validator.ts
...
static async usernameUniqueValidator(
control: FormControl
): Promise<ValidationErrors | null> {
let controlBind = this as any;
let authService = controlBind.authService as AuthService;
//I just added types to be able to get my functions as I type
return new Promise(resolve => {
if (control.value == "") {
resolve(null);
} else {
authService.checkUsername(control.value).subscribe(
() => {
resolve({
usernameExists: {
valid: false
}
});
},
() => {
resolve(null);
}
);
}
});
...
I've been doing it slightly differently and faced the same issue.
Here is my code and the fix in case if someone would need it:
forbiddenNames(control: FormControl): Promise<any> | Observable<any> {
const promise = new Promise<any>((resolve, reject) => {
setTimeout(() => {
if (control.value.toUpperCase() === 'TEST') {
resolve({'nameIsForbidden': true});
} else {
return null;//HERE YOU SHOULD RETURN resolve(null) instead of just null
}
}, 1);
});
return promise;
}
I tries using the .first(). technique described by #AT82 but I didn't find it solved the problem.
What I eventually discovered was that the form status was changing but it because I'm using onPush, the status change wasn't triggering change detection so nothing was updating in the page.
The solution I ended up going with was:
export class EmailFormComponent implements OnInit {
...
constructor(
...
private changeDetector: ChangeDetectorRef,
) {
...
// Subscribe to status changes on the form
// and use the statusChange to trigger changeDetection
this.myForm.statusChanges.pipe(
distinctUntilChanged()
).subscribe(() => this.changeDetector.markForCheck())
}
}
import { Component,
OnInit } from '#angular/core';
import { FormBuilder,
FormGroup,
FormControl,
Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { EmailValidationService } from '../services/email-validation.service';
import { CustomValidators } from '../utilities/custom-validators/custom-validators';
#Component({
templateUrl: './email-form.component.html',
styleUrls: ['./email-form.component.sass']
})
export class EmailFormComponent implements OnInit {
public emailForm: FormGroup;
public formSubmitted: Boolean;
public emailSent: Boolean;
constructor(
private router: Router,
private builder: FormBuilder,
private service: EmailValidationService
) { }
ngOnInit() {
this.formSubmitted = false;
this.emailForm = this.builder.group({
email: [ '', [ Validators.required ], [ CustomValidators.briteVerifyValidator(this.service) ] ]
});
}
get email() {
return this.emailForm.get('email');
}
// rest of logic
}

How to add query params to route in guard and pass it to component in Angular 4?

I am using a route guard in my angular 4 app, and I would like to add a query param to the route if a condition satisfies and return true.
Here's the code I have been working on
#Injectable()
export class ViewGuardService implements CanActivate {
constructor(private router: Router) { }
canActivate(activatedRoute: ActivatedRouteSnapshot, snapshot: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if(!this.router.url.includes('/order-management')) {
//ADD PARAMS TO ROUTE OR PASS DATA TO COMPONENT HERE AND THEN RETURN TRUE
return true;
} else {
this.route.navigate['/login'];
return false;
}
}
}
Usually, to navigate to a route with params we can use it as this.router.navigate(['/order-management', activatedRoute.url[0].path], { queryParams: { moveToOrders: true }});. But if I use this condition in the if condition, it turns out to an infinite loop of function calls.
So how do I pass params or data from the guard to the component? Please help me resolve this issue.
This is a bit hacky, but it works (Angular 11).
#Injectable({
providedIn: 'root'
})
export class SetQueryParamGuard implements CanActivate {
constructor(
private _router: Router
) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> {
const requiredQueryParam = route.queryParamMap.get('requiredQueryParam');
// Query param is set, no further action
if (requiredQueryParam) {
return of(true);
}
return of(
this._router
.parseUrl(state.url + `&requiredQueryParam=DEFAULT_VALUE`)
);
}
}

Error: No provider for RouterStateSnapshot when using with CanLoad guard in Angular 4

I am trying to redirect the users to login page, if the user isn't logged in. Once the user logs, I want to take the user back to the previous page. But I am getting an error as StaticInjectorError[RouterStateSnapshot]: NullInjectorError: No provider for RouterStateSnapshot!.
Here's the code for the CanLoad functionality:
#Injectable()
export class TokenGuardService implements CanLoad {
constructor(private authService: AuthService, private router: Router, private snapshot: RouterStateSnapshot) {}
canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
if(this.authService.doesTokenExist()) {
return true;
} else {
this.router.navigate(['/login'], { queryParams: { returnUrl: this.snapshot.url }});
return false;
}
}
and here's the code my Component
export class LoginComponent implements OnInit {
constructor(private loginService: LoginService, private router: Router, private route: ActivatedRoute) { }
ngOnInit() {
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/dashboard';
}
onLoginFormSubmit() {
//Some success scenario
if(success) {
this.router.navigate([this.returnUrl]);
}
}
Please help me resolve this issue.

Connect the authentication service with the AuthGuard (simple issue)

I guess it's quite simple issue, but unfortunately I don't really know how to deal with it.
I'm trying to connect my UserAuthenticationService service with the ActivationGuard.
UserAuthenticationService.ts:
import {Injectable} from '#angular/core';
import {Http} from '#angular/http';
#Injectable()
export class UserAuthenticationService {
isUserAuthenticated: boolean = false;
username: string;
constructor(private http: Http) {
}
authentication() {
this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
.subscribe(res => { //^^returns true or false, depending if the user is logged or not
this.isUserAuthenticated = res.json();
},
err => {
console.error('An error occured.' + err);
});
}
}
ActivationGuard.ts
import {Injectable} from '#angular/core';
import {Router, RouterStateSnapshot, ActivatedRouteSnapshot} from '#angular/router';
import {Observable} from 'rxjs/Observable';
import {UserAuthenticationService} from './UserAuthenticationService';
interface CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean
}
#Injectable()
export class WorksheetAccessGuard implements CanActivate {
constructor(private router: Router, private userService: UserAuthenticationService) {
}
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.userService) {
this.router.navigate(['/']);
return false;
}
return true;
}
}
Note
It works great, if I just use localStorage to store the information if the user is logged or not:
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (!localStorage.getItem('currentUser')) {
this.router.navigate(['/']);
return false;
}
return true;
}
But how can I connect the service with the guard? Looking forward for any kind of help. Thank you in advance.
If you need any more information, please let me know and I will edit my post.
Call authentication() method of UserAuthenticationService either in constructor or On ngOnit then it sets the isUserAuthenticated variable and use that in the ActivationGuard.ts
UserAuthenticationService.ts:
import {Injectable} from '#angular/core';
import {Http} from '#angular/http';
#Injectable()
export class UserAuthenticationService {
isUserAuthenticated: boolean = false;
username: string;
constructor(private http: Http) {
this.authentication();
}
authentication() {
this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
.subscribe(res => { //^^returns true or false, depending if the user is logged or not
this.isUserAuthenticated = res.json();
},
err => {
console.error('An error occured.' + err);
});
}
}
ActivationGuard.ts
#Injectable()
export class WorksheetAccessGuard implements CanActivate {
constructor(private router: Router, private userService: UserAuthenticationService) {
}
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.userService.isUserAuthenticated) {
this.router.navigate(['/']);
return false;
}
return true;
}
}
This is not the right approach for doing it. Every time you call the service , it initialize a new instance and hence you get a false.
You should create a singleton service instance ( via the main module in your app) - where it will contain your app state ( in memory / localstorage)
Then , when you'll call UserAuthenticationService - you won't update its owbn parameter but the main's one ( the singleton).
I suggest you to use a BehaviourSubject ( read about it , it's like a Subject but it also yields its last value without waiting to emit a value manually).
From that point your app can see from anywhere ig the user is logged in or not.

Categories

Resources