daily pastebin goal
41%
SHARE
TWEET

Untitled

a guest May 23rd, 2018 128 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <div id="container">
  2.   <div id="login_card_container">
  3.     <div id="login_card" class="card col s12">
  4.       <form [formGroup]="loginForm" (ngSubmit)="onLogin()" class="col s12">
  5.         <h1 id="form_title">Login</h1>
  6.         <div class="row">
  7.           <div class="input-field col s12">
  8.             <input formControlName="username" id="username" type="text" class="validate" [ngClass]="{invalid: invalidCredentials}">
  9.             <label for="username">Username</label>
  10.           </div>
  11.         </div>
  12.         <div class="row">
  13.           <div class="input-field col s12">
  14.             <input formControlName="password" id="password" type="password" class="validate" [ngClass]="{invalid: invalidCredentials}">
  15.             <label for="password" data-error="Your username/password combination is invalid">Password</label>
  16.           </div>
  17.         </div>
  18.         <div id="login_button_container" class="row">
  19.           <button id="login_button" type="submit" class="btn waves-effect waves-light" [disabled]="!loginForm.valid">
  20.             <i class="fa fa-sign-in left"></i>
  21.             Login
  22.           </button>
  23.         </div>
  24.       </form>
  25.     </div>
  26.   </div>
  27. </div>
  28.    
  29. onLogin() {
  30.     this.loading = true;
  31.     this.auth.loginByUsernameAndPassword(
  32.       this.loginForm.controls['username'].value,
  33.       this.loginForm.controls['password'].value)
  34.       .subscribe(
  35.       result => {
  36.         if (result === true) {
  37.           this.router.navigate(['/']);
  38.         } else {
  39.           this.loading = false;
  40.           this.invalidCredentials = true;
  41.         }
  42.       },
  43.       error => {
  44.         this.loading = false;
  45.         this.invalidCredentials = true;
  46.       }
  47.       );
  48.   }
  49.    
  50. export class AuthService {
  51.   private static readonly CURRENT_USER = 'currentUser';
  52.   constructor(private http: Http, private router: Router) {
  53.     this.currentUser = this.loadCurrentUser();
  54.   }
  55.   public loginByUsernameAndPassword(username: string, password: string): Observable<boolean> {
  56.     let urlSearchParams = new URLSearchParams();
  57.     urlSearchParams.append('username', username);
  58.     urlSearchParams.append('password', password);
  59.     urlSearchParams.append('user_uniqueIdid', '0');
  60.     urlSearchParams.append('session_id', '0');
  61.     let body = urlSearchParams.toString();
  62.     let headers = new Headers();
  63.     headers.append('Content-Type', 'application/x-www-form-urlencoded');
  64.  
  65.     return this.http.post(Api.getUrl(Api.URLS.Login), body, {
  66.       headers: headers
  67.     })
  68.       .map((response: Response) => {
  69.         let res = response.json();
  70.         if (res.StatusCode === 0 && res.Token) {
  71.           this.currentUser = {
  72.             username: username,
  73.             token: res.Token,
  74.             role: res.StatusDescription.Role
  75.           }
  76.           localStorage.setItem(AuthService.CURRENT_USER, JSON.stringify(this.currentUser));
  77.           return true;
  78.         }else {
  79.           return false;
  80.         }
  81.       });
  82.   }
  83.  
  84.   public isAuthenticated(): boolean {
  85.     let currentUser: any = localStorage.getItem(AuthService.CURRENT_USER);
  86.     if (currentUser !== null) {
  87.       try {
  88.         currentUser = JSON.parse(currentUser);
  89.         if (!currentUser.username !== undefined &&
  90.           !currentUser.token !== undefined &&
  91.           !currentUser.permission !== undefined) {
  92.           return true;
  93.         }
  94.       } catch (ex) {
  95.       }
  96.     }
  97.     return false;
  98.   }
  99.   public getCurrentUser(): any {
  100.     return this.currentUser;
  101.   }
  102.  
  103.   private loadCurrentUser(): any {
  104.     let currentUser: any = localStorage.getItem(AuthService.CURRENT_USER);
  105.     if (currentUser !== null) {
  106.       try {
  107.         currentUser = JSON.parse(currentUser);
  108.         if (!currentUser.username !== undefined &&
  109.           !currentUser.token !== undefined &&
  110.           !currentUser.permission !== undefined) {
  111.           return currentUser;
  112.         }
  113.       } catch (ex) {
  114.       }
  115.     }
  116.  
  117.     return null;
  118.   }
  119.  
  120. }
  121.    
  122. describe('Component: Login', () => {
  123.     let comp: LoginComponent
  124.     let fixture: ComponentFixture<LoginComponent>;
  125.     let de: DebugElement;
  126.     let el: HTMLElement;    
  127.     beforeEach(async(() => {
  128.             TestBed.configureTestingModule({
  129.             declarations: [LoginComponent],
  130.             imports: [
  131.                 BrowserModule,
  132.                 FormsModule,
  133.                 ReactiveFormsModule,
  134.                 RouterTestingModule
  135.             ]
  136.         }).compileComponents().then(() => {
  137.             fixture = TestBed.createComponent(LoginComponent);
  138.             comp = fixture.componentInstance;
  139.             de = fixture.debugElement.query(By.css('form'));
  140.             el = de.nativeElement;
  141.         });
  142.     }));
  143. });
  144.    
  145. describe('Component: Login', () => {
  146.     let component: LoginComponent;
  147.     let fixture: ComponentFixture<LoginComponent>;
  148.  
  149.     beforeEach(() => {
  150.         TestBed.configureTestingModule({
  151.             imports: [ReactiveFormsModule, FormsModule, HttpModule, RouterTestingModule],
  152.             declarations: [LoginComponent],
  153.             providers: [AuthService],
  154.         });
  155.         fixture = TestBed.createComponent(LoginComponent);
  156.         component = fixture.componentInstance;
  157.         component.ngOnInit();
  158.     });
  159.     it('should call auth login method', async(() => {
  160.         let loginElement: DebugElement;
  161.         let debugElement = fixture.debugElement;
  162.         let authService = debugElement.injector.get(AuthService);
  163.         let loginSpy = spyOn(authService, 'loginByUsernameAndPassword').and.callThrough();
  164.         loginElement = fixture.debugElement.query(By.css('form'));
  165.         loginElement.triggerEventHandler('ngSubmit', null);
  166.         expect(loginSpy).toHaveBeenCalledTimes(1);
  167.     }));
  168. });
  169.    
  170. it('should call auth login method', async(() => {
  171.  let loginElement: DebugElement;
  172.  const debugElement = fixture.debugElement;
  173.  authService = debugElement.injector.get(AuthService);
  174.  loginSpy = spyOn(authService , 'loginByUsernameAndPassword').and.callThrough();
  175.  loginElement = fixture.debugElement.query(By.css('form'));
  176.  // to set values
  177.  component.loginForm.controls['username'].setValue('user'),
  178.  component.loginForm.controls['password'].setValue('123')
  179.  loginElement.triggerEventHandler('ngSubmit', null);
  180.  expect(loginSpy).toHaveBeenCalledTimes(1); // check that service is called once
  181. }));
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top