Commit f5fb45a0 authored by Jie Yuan's avatar Jie Yuan
Browse files

add auth service

parent df02f35a
Loading
Loading
Loading
Loading
+12 −0
Original line number Diff line number Diff line
import { TestBed } from '@angular/core/testing';

import { AuthService } from './auth.service';

describe('AuthService', () => {
  beforeEach(() => TestBed.configureTestingModule({}));

  it('should be created', () => {
    const service: AuthService = TestBed.get(AuthService);
    expect(service).toBeTruthy();
  });
});
+189 −0
Original line number Diff line number Diff line
import {EventEmitter, Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {HttpHeaders} from '@angular/common/http';
import {SharedService} from './shared-service';

@Injectable()
export class AuthService {

  loggedIn: boolean;
  loggedSubscription: EventEmitter<boolean>;
  public sharedHeaderString = '';
  
  constructor(private router: Router, private http: HttpClient, private sharedService: SharedService) {
    this.loggedIn = JSON.parse(sessionStorage.getItem('loggedIn'));
   this.loggedSubscription = new EventEmitter<boolean>();
   this.sharedHeaderString = '';
   console.log('in authservice constructor');
  }
  
  credentialAuthenticate(username, password)  {
    const user = {'usernameOrEmail': username, 'password': password};
    const signInHeaders = new HttpHeaders( true ?
    {
      'Content-Type' : 'application/json'
    } : {});
    this.http.post(this.sharedService.signInURL, user, {headers: signInHeaders})
    .subscribe(response => {
        if ( response['accessToken'] ) {
          console.log(response['accessToken']);
          this.headerBuilder(response['accessToken']);
          console.log('token successful');
          this.checkUser();
        } else {
          this.router.navigate(['/login']);
          console.log('password username does not match');
        }
    });
  }

  // check the user exisitence, and user authentation service type
  checkUser() {
    const headers = new HttpHeaders( this.sharedHeaderString ? {
      'Authorization' : this.sharedHeaderString ,
      'Content-Type' : 'application/json'
       } : {}
    );
   console.log(headers);
   console.log('show user request header');
   this.http.get(this.sharedService.userInfoURL,  {headers : headers} )
   .subscribe(response => {
     if (response['authService'] === 'USERNAME' ) {
         this.loginSuccess();
         //console.log(this.sharedHeaderString);
         //console.log(response);
         sessionStorage.setItem('authHeader',this.sharedHeaderString);
         console.log('login success');
     } else if (response['authService'] === 'AAI') {
       this.headerBuilder('');
       console.log('please login via AAI');
     } else {
       this.headerBuilder('');
       console.log('not authorized to get user details');
     }
   });
  }


  




 private headerBuilder(token): void {
   if ( token ) {
    const tmp =  'Bearer ' +  token;
    this.sharedHeaderString = tmp;
   } else {
     this.sharedHeaderString = '';
   }

 }


  isAuthenticated() {
    /** Calls backend **/
    const promise = new Promise<boolean>(
      (resolve, reject) => {
        setTimeout(() => {
          resolve(this.loggedIn);
        }, 800);
      }
    );
    return promise;
  }


  login(): Promise<boolean> {
    const self = this;
    return new Promise<boolean>( function (resolve, reject) {
      self.loggedIn = true;
      sessionStorage.setItem('loggedIn', JSON.stringify(self.loggedIn));
      self.router.navigate(['/dashboard'])
        .then(success => {
          self.loggedSubscription.emit(self.loggedIn);
          resolve(self.loggedIn);
        })
        .catch(error => {
          self.loggedIn = false;
          
          self.loggedSubscription.emit(self.loggedIn);
          reject(self.loggedIn);
        });
    });
  }

  logout() {
    //sessionStorage.setItem('authenticated', JSON.stringify(this.authenticated));
    this.loggedIn = false;
    sessionStorage.setItem('loggedIn', JSON.stringify(this.loggedIn));
    sessionStorage.removeItem('authHeader');
    sessionStorage.clear();
    //sessionStorage.clear();
    this.router.navigate(['/login']);
    this.loggedSubscription.emit(this.loggedIn);
    this.sharedHeaderString = '';
   
  }


  private loginSuccess(): void {
    this.login()
    .then(logStatus => {
      this.isAuthenticated()
        .then(
          (data) => {
            this.router.navigate(['/dashboard'])
              .then(sucess => {
              })
              .catch();
          }
        );
    })
    .catch(error => {
      this.router.navigate(['/login']);
    });
}

canEnterToDashboard(){
return false;
}


aaiRedirect() {
window.location.href  = this.sharedService.redirectionURL;
}

aaiAuthentication(token) {
  
  console.log('aai authenentication');
  //this.setCookie('JSESSIONID', sessionid);
  //this.setCookie('XSRF-TOKEN', xsrftoken);
  this.headerBuilder(token);
  const headers = new HttpHeaders( this.sharedHeaderString ? {
       'Authorization' : this.sharedHeaderString,
       'Content-Type' : 'application/json'
     } : {} );
  this.http.get(this.sharedService.userInfoURL, {headers : headers} )
  .subscribe(response => {
    if (response['authService'] === 'AAI') {
        this.loginSuccess();
        sessionStorage.setItem('authHeader',this.sharedHeaderString);
        console.log(this.sharedHeaderString);
        console.log(response);
        console.log('#####################');
    } else {
      this.router.navigate(['login']);
    }
  });
 /** if ( sessionid !== '' && xsrftoken !== '') {
     this.loginSuccess();
  } else {
    this.router.navigate['login'];
  }**/
}

}