2018-06-19 16:55:50 +02:00
|
|
|
import { Injectable } from '@angular/core';
|
|
|
|
import { HttpClient, HttpResponse, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
|
|
|
|
import { Observable, of, throwError } from 'rxjs';
|
2018-06-28 17:11:04 +02:00
|
|
|
import { catchError, tap } from 'rxjs/operators';
|
2018-06-19 16:55:50 +02:00
|
|
|
|
2018-07-04 17:51:31 +02:00
|
|
|
import { User } from 'app/core/models/users/user';
|
2018-06-19 16:55:50 +02:00
|
|
|
|
|
|
|
const httpOptions = {
|
|
|
|
withCredentials: true,
|
|
|
|
headers: new HttpHeaders({
|
|
|
|
'Content-Type': 'application/json'
|
|
|
|
})
|
|
|
|
};
|
|
|
|
|
|
|
|
@Injectable({
|
|
|
|
providedIn: 'root'
|
|
|
|
})
|
|
|
|
export class AuthService {
|
|
|
|
isLoggedIn: boolean;
|
|
|
|
|
|
|
|
// store the URL so we can redirect after logging in
|
|
|
|
redirectUrl: string;
|
|
|
|
|
|
|
|
constructor(private http: HttpClient) {
|
|
|
|
//check for the cookie in local storrage
|
|
|
|
//TODO checks for username now since django does not seem to return a cookie
|
|
|
|
if (localStorage.getItem('username')) {
|
|
|
|
this.isLoggedIn = true;
|
|
|
|
} else {
|
|
|
|
this.isLoggedIn = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Initialize the service by querying the server
|
|
|
|
// Not sure if this makes sense, since a service is not supposed to init()
|
2018-06-28 12:20:37 +02:00
|
|
|
init(): Observable<User | any> {
|
|
|
|
return this.http.get<User>('/users/whoami/', httpOptions).pipe(
|
2018-06-19 16:55:50 +02:00
|
|
|
tap(val => {
|
|
|
|
console.log('auth-init-whami : ', val);
|
|
|
|
}),
|
|
|
|
catchError(this.handleError())
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
//loggins a users. expects a user model
|
2018-06-30 16:56:18 +02:00
|
|
|
login(username: string, password: string): Observable<User | any> {
|
|
|
|
const user: any = {
|
|
|
|
username: username,
|
|
|
|
password: password
|
|
|
|
};
|
2018-07-03 11:52:16 +02:00
|
|
|
return this.http.post<any>('/users/login/', user, httpOptions).pipe(
|
2018-06-19 16:55:50 +02:00
|
|
|
tap(val => {
|
2018-06-30 16:56:18 +02:00
|
|
|
localStorage.setItem('username', val.username);
|
2018-06-19 16:55:50 +02:00
|
|
|
this.isLoggedIn = true;
|
|
|
|
}),
|
|
|
|
catchError(this.handleError())
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
//logout the user
|
|
|
|
//TODO not yet used
|
2018-06-28 12:20:37 +02:00
|
|
|
logout(): Observable<User | any> {
|
2018-06-19 16:55:50 +02:00
|
|
|
this.isLoggedIn = false;
|
|
|
|
localStorage.removeItem('username');
|
|
|
|
|
2018-06-28 12:20:37 +02:00
|
|
|
return this.http.post<User>('/users/logout/', {}, httpOptions);
|
2018-06-19 16:55:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
//very generic error handling function.
|
|
|
|
//implicitly returns an observable that will display an error message
|
|
|
|
private handleError<T>() {
|
|
|
|
return (error: any): Observable<T> => {
|
|
|
|
console.error(error);
|
|
|
|
return of(error);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|