0

I'm trying to get an observable in Angular 4 project\ The get request is okay but I'm getting pushed away to 403 unauthorized page while I'm the admin, I'm trying to understand the problem of this, I debugged the code but I cant get it, The code run perfectly fine but I'm getting pushed to 403 anyway...

   isAdmin(): Observable<object> {
        if (!this._isAdmin) {
            this._isAdmin = this.http.get('./api/account/admin')
            .map(
        (res: Response) => res.json())
        .publishReplay(1)
        .refCount()
        .catch((error: any) => {
            this.router.navigate(['/error/403']);
            return Observable.throw(error.json().error || 'Server error');
        })      
    }
        if (!this._isAdmin) {
            this.router.navigate(['/error/403']);
            return Observable.throw('Server error');
        }        
        return this._isAdmin;
    }



   canActivate(
     next: ActivatedRouteSnapshot,
     state: RouterStateSnapshot): boolean {             
         console.log("check");
     const allowedRoles = next.data.permittedRoles as Array<string>;

        this.authService.isAdmin().subscribe(
            (data: any) => {
            if (!data) {
                this.router.navigate(['/error/403']);
                return false;
            }
            allowedRoles.forEach((element: any) => {
                if (data.RoleType === element) {         
         if (data.IsAdmin) {
                return true;
            }         
        }
    }),
    (err: any) =>         
    {
        console.log(err);
        this.router.navigate(['/error/403']);
        return false;
}});
this.router.navigate(['/error/403']);
       return false;
}
}
O. Dror
  • 93
  • 1
  • 10
  • Try to use pipable operators in your isAdmin method. And in Angular 4 you get json, you don't need `res.json()` – igor_c Sep 11 '19 at 12:45
  • Need to remove res.json()? to this => .map( (res: Response)) .publishReplay(1) .refCount() @igor_c – O. Dror Sep 11 '19 at 12:48

2 Answers2

0

Well after some months I wasn't aware of this but my IIS Authentication was Anonymous & Windows authentication, I had to remove the Anonymous Authentication in order it to work

O. Dror
  • 93
  • 1
  • 10
-1

You need to return an observable from your guard, since you cannot return from subscribe. Also if you are using HttpClient, that I hope you do, you don't need to parse to JSON, as the HttpClient does that for you. If you are using Http, I strongly suggest you move on to using HttpClient. Anyway, assuming you are using HttpClient, your code should looks something like this:

isAdmin(): Observable<object> {
  return this.http.get('./api/account/admin')
}

and the guard (which I slightly modified from Norbert's answer by changing subscribe to map):

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
  this.authService.isAdmin().map((data) => {
    if (data && data.isAdmin) {
      return true;
    }
    this.router.navigate(['/error/403']);
    return false;
  }
}  

I omitted the forEach loop, since I didn't see how it would fit in here, since you are anyway checking if data.isAdmin exists. But if you for some reason need it, I would suggest a for loop, forEach cannot return anything. Also you need to assign the truthy or falsy value to variable, since in a for loop return just breaks the loop.

let bool = false;
for(let element of allowedRoles) {
  if (data.RoleType === element) {
    if (data.IsAdmin) {
      bool = true;
      return;
    } 
  }
}

if (bool) { return true }
AT82
  • 71,416
  • 24
  • 140
  • 167
  • If you set the return type of `canActivate` to `boolean` or `UrlTree` but never return a `UrlTree` then its kinda useless to set it at all. Also you call the method `router.parseUrl(...)` whitch return `UrlTree` and dont use it. Please don't just copy and paste answers. – Norbert Bartko Sep 11 '19 at 14:21
  • @NorbertBartko, eh... from where do I just "copy and paste" answer? This came from my head, but sure, I can remove the `UrlTree`, and I also see another error I made, so thanks for making me look closer at my code. – AT82 Sep 11 '19 at 14:27
  • @NorbertBartko, aaah, now I perhaps understand what you mean with copying perhaps. Sure, I used your code as base but put my own twist on it. So I did not copy your answer, which would have been a no-no and also no point in then even write up an answer. But excuse me if that offended you. I could of course had copied OP's code and rewrite all of it, but since your answer was closer to mine I ruthlessly used it as a base. Sorry again, I'll be sure to be more respecting in future. – AT82 Sep 11 '19 at 14:39