Taobin-Recipe-Manager/client/src/app/core/services/user.service.ts

64 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-09-18 08:50:13 +07:00
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {
BehaviorSubject,
Observable,
concat,
2023-09-18 08:50:13 +07:00
distinctUntilChanged,
map,
tap,
} from 'rxjs';
import { User } from '../models/user.model';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';
2023-09-18 08:50:13 +07:00
@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));
2023-09-18 08:50:13 +07:00
constructor(
private readonly http: HttpClient,
private readonly router: Router
2023-09-18 08:50:13 +07:00
) {}
logout(): void {
this.purgeAuth();
// post to api /revoke with cookie
this.http
.get(environment.api + '/auth/revoke', {
withCredentials: true,
2023-09-18 08:50:13 +07:00
})
.subscribe({
complete: () => this.router.navigateByUrl('/login'),
});
2023-09-18 08:50:13 +07:00
}
getCurrentUser(): Observable<{ user: User }> {
2023-09-18 08:50:13 +07:00
return this.http
.get<{ user: User }>(environment.api + '/auth/user', {
withCredentials: true,
})
.pipe(
tap({
next: ({ user }) => {
this.setAuth(user);
},
error: () => this.purgeAuth(),
})
);
2023-09-18 08:50:13 +07:00
}
setAuth(user: User): void {
void this.currnetUserSubject.next(user);
}
purgeAuth(): void {
void this.currnetUserSubject.next(null);
2023-09-18 08:50:13 +07:00
}
}