63 lines
1.5 KiB
TypeScript
63 lines
1.5 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import { HttpClient } from '@angular/common/http';
|
|
import {
|
|
BehaviorSubject,
|
|
Observable,
|
|
concat,
|
|
distinctUntilChanged,
|
|
map,
|
|
tap,
|
|
} from 'rxjs';
|
|
import { User } from '../models/user.model';
|
|
import { Router } from '@angular/router';
|
|
import { environment } from 'src/environments/environment';
|
|
|
|
@Injectable({ providedIn: 'root' })
|
|
export class UserService {
|
|
private currnetUserSubject = new BehaviorSubject<User | null>(null);
|
|
public currentUser = this.currnetUserSubject
|
|
.asObservable()
|
|
.pipe(distinctUntilChanged());
|
|
|
|
public isAuthenticated = this.currentUser.pipe(map((user) => !!user));
|
|
|
|
constructor(
|
|
private readonly http: HttpClient,
|
|
private readonly router: Router
|
|
) {}
|
|
|
|
logout(): void {
|
|
this.purgeAuth();
|
|
// post to api /revoke with cookie
|
|
this.http
|
|
.get(environment.api + '/auth/revoke', {
|
|
withCredentials: true,
|
|
})
|
|
.subscribe({
|
|
complete: () => this.router.navigateByUrl('/login'),
|
|
});
|
|
}
|
|
|
|
getCurrentUser(): Observable<{ user: User }> {
|
|
return this.http
|
|
.get<{ user: User }>(environment.api + '/auth/user', {
|
|
withCredentials: true,
|
|
})
|
|
.pipe(
|
|
tap({
|
|
next: ({ user }) => {
|
|
this.setAuth(user);
|
|
},
|
|
error: () => this.purgeAuth(),
|
|
})
|
|
);
|
|
}
|
|
|
|
setAuth(user: User): void {
|
|
void this.currnetUserSubject.next(user);
|
|
}
|
|
|
|
purgeAuth(): void {
|
|
void this.currnetUserSubject.next(null);
|
|
}
|
|
}
|