VICE / Client / src / app / authentication.service.ts
authentication.service.ts
Raw
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { HttpClient, HttpClientModule, HttpHeaders } from '@angular/common/http';
import { sha256 } from 'js-sha256';
import { environment } from './../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  public authHeader: HttpHeaders = new HttpHeaders().set("Authorization", "NA NA");
  private authenticated$: BehaviorSubject<AuthLevel> = new BehaviorSubject<AuthLevel>(AuthLevel.None);
  status = this.authenticated$.asObservable();

  private userID: BehaviorSubject<string> = new BehaviorSubject<string>("");
  user = this.userID.asObservable();

  constructor(private http: HttpClient){}

  public authenticate(email: string, pw: string) {
    let emailhash = sha256(email);
    let pwhash = sha256(pw);
    this.authHeader = new HttpHeaders().set("Authorization", emailhash + " " + pwhash);

    let result = this.http.post(environment.ip + "/authenticate",
     {emailhash: emailhash, pwhash: pwhash}).toPromise();

    this.userID.next(emailhash);

    return result;
  }

  public swapAuth(auth: AuthLevel) {
    this.authenticated$.next(auth);
  }

  public deauthenticate() {
    this.authenticated$.next(AuthLevel.None);
    this.authHeader.set("Authorization", "NA NA");
    this.userID.next("");
  }
}

export enum AuthLevel {
  None,
  Base,
  Manage,
  Admin
}