Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Http Interceptor #50

Closed
jtan80813 opened this issue Dec 2, 2018 · 1 comment
Closed

Http Interceptor #50

jtan80813 opened this issue Dec 2, 2018 · 1 comment

Comments

@jtan80813
Copy link

jtan80813 commented Dec 2, 2018

Hi. I have a problem in my authentication. I have attached the http interceptor in every request i make. I have a problem in logging in of my application. I am not able to login since i have this error in my code
capture

These are my codes

onSignIn() {
    const formData = {
      email: this.loginForm.get('email').value,
      password: this.loginForm.get('password').value
    };
    if (this.loginForm.valid) {
      this.authService.signinUser(formData)
      .subscribe(
        data => {
          console.log(data);
          this.cookieService.set('auth_token', data.token);
          console.log(data);
        },
        error => {
          console.log(error);
        });
    }
  }
`@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  private authService: AuthService;

  constructor(private injector: Injector, private router: Router, private cookieService: CookieService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // Get the auth header from the service.
    this.authService = this.injector.get(AuthService);
    const token: string = this.cookieService.get('auth_token');
    const role: string = this.authService.getRole();
    const corp: string = this.cookieService.get('corp_id');
    const dept: string = this.cookieService.get('dept_id');
    const user = this.cookieService.get('user_id');

    if (role !== null) {
      req = req.clone({ headers: req.headers.set('role' ? 'role' : null , role ? role : null) });
    }

    if (corp !== null) {
      req = req.clone({ headers: req.headers.set('corp-id' ? 'corp-id' : null , corp ? corp : null) });
    }

    if (dept !== null) {
      req = req.clone({ headers: req.headers.set('dept-id' ? 'dept-id' : null , dept ? dept : null) });
    }

    if (user !== null) {
      req = req.clone({ headers: req.headers.set('user-id' ? 'user-id' : null , user ? user : null) });
    }

    if (token) {
      req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
    }

    if (!req.headers.has('Content-Type')) {
      req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
    }

    req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
    return next.handle(req).do(
      (event: HttpEvent<any>) => {},
      (err: any) => {
        if (err instanceof HttpErrorResponse) {
          if (err.status === 401 || err.status === 403 || err.status === 400 ) {
            swal('Session Expired!", "Sorry, your session has expired, you will be redirected to the login page", "warning');
            this.authService.logout();
          }
          if (err.status === 500 || err.status === 0 ) {
            this.router.navigate(['error'])
          }
        }
      }
      )
  }`

`export class AuthService {
  token: string;

  constructor(private httpClient: HttpClient, private router: Router, private cookieService: CookieService) {}

  signinUser(formData) {
    return this.httpClient
    .post(
       `${environment.url}/auth/login`,
       JSON.stringify(formData)
    )
    .map((response: any) => {
         return response;
        });
  }

  logout(): void {
    localStorage.clear();
    this.router.navigate(['login']);
  }

  setSession(token: string): void {
    this.cookieService.set('auth_token', JSON.stringify(token));
  }

  isLoggedIn(): boolean {
    const token = this.getToken();
    if (!token) {
      return false;
    }
    return true;
  }

  getToken(): string {
    return this.cookieService.get('auth_token');
  }

  getRole() {
    return this.cookieService.get('user_role');
  }

  getCorp() {
    return this.cookieService.get('corp_id')
  }

  getDept() {
    return this.cookieService.get('dept_id')
  }

  getUserID() {
    return this.cookieService.get('user_id')
  }`
@CunningFatalist
Copy link
Contributor

Hello,

this seems to be an implementation issue and has nothing to do with any ngx-cookie-service bugs or issues. Therefore, helping you is sadly out of scope for us. However, you can ask the friendly people over at StackOverflow for help. I'm sure someone there will have a tip for you.

Cheers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants