2018-11-11 12:00:45 +01:00

91 lines
2.6 KiB
TypeScript

import { Injectable } from '@angular/core';
import { Router } from "@angular/router";
import { HttpClient } from "@angular/common/http";
import 'rxjs/Rx';
import { JwtHelperService } from '@auth0/angular-jwt';
import { environment } from '../../environments/environment';
const TOKEN_LS_NAME = 'token';
@Injectable()
export class AuthService {
private url = environment.apiUrl + '/api/auth';
public redirectUrl: string;
public isLoading: boolean = false;
public hasError: boolean = false;
public errorMessage: string = "";
constructor(private httpService: HttpClient,
private jwtHelperService: JwtHelperService,
private router: Router) {
}
get token(): string {
return localStorage.getItem(TOKEN_LS_NAME);
}
get isLoggedIn(): boolean {
try {
return !this.jwtHelperService.isTokenExpired(this.token);
} catch (ex) {
return false;
}
}
get tokenData() {
return this.jwtHelperService.decodeToken(this.token);
}
public authRedirect() {
this.router.navigate(['/bejelentkezes']);
}
public login(login: string, password: string) {
this.hasError = false;
this.isLoading = true;
this.httpService.post<AuthResponse>(this.url + '/login',{
'login': login,
'password': password,
}).subscribe(
apiResponse => {
this.isLoading = false;
if (apiResponse.message == 'login') {
localStorage.setItem(TOKEN_LS_NAME, apiResponse.token);
this.router.navigate(['/']);
} else {
this.hasError = true;
this.errorMessage = "Sikertelen bejelentkezés.";
}
},
err => {
console.log(err);
this.hasError = true;
this.errorMessage = "Hiba történt bejelentkezés közben.";
this.isLoading = false;
}
);
}
public renew() {
this.httpService.get<AuthResponse>(this.url + '/renew')
.subscribe(
apiResponse => {
if (apiResponse.message == 'renew') {
localStorage.setItem(TOKEN_LS_NAME, apiResponse.token);
}
},
err => console.log(err)
);
}
public logout() {
localStorage.removeItem(TOKEN_LS_NAME);
}
}
class AuthResponse {
public message: string;
public token: string;
}