Files
release-hive-fe/src/app/services/auth.service.ts

68 lines
1.5 KiB
TypeScript

import { Injectable } from '@angular/core';
import {TokenResponse} from "../interface/auth";
import moment from "moment";
import {HttpClient} from "@angular/common/http";
import {tap} from "rxjs";
@Injectable({
providedIn: 'root'
})
export class AuthService {
private apiUrl = 'http://localhost:8080/api/';
constructor(
private httpClient: HttpClient
) {
}
public register(email: string, username: string, password: string) {
const body = {
email: email,
username: username,
password: password
}
return this.httpClient.post(this.apiUrl + 'v1/auth/register', body);
}
public authenticate(email: string, password: string) {
const body = {
email: email,
password: password
}
return this.httpClient.post<TokenResponse>(this.apiUrl + 'v1/auth/login', body)
.pipe(tap(token => {this.setSession(token)}));
}
private setSession(res: TokenResponse) {
const expiresAt = moment().add(res.expiresIn, 'milliseconds');
localStorage.setItem('tokenId', res.token);
localStorage.setItem("expiresAt", JSON.stringify(expiresAt.valueOf()) );
}
public logout() {
localStorage.removeItem("tokenId");
localStorage.removeItem("expiresAt");
}
public isLoggedIn() {
return moment().isBefore(this.getExpiration());
}
isLoggedOut() {
return !this.isLoggedIn();
}
getExpiration() {
const expiration = localStorage.getItem("expiresAt");
const expiresAt = JSON.parse(expiration ? expiration : '{}');
return moment(expiresAt);
}
}