80 lines
2.4 KiB
TypeScript
80 lines
2.4 KiB
TypeScript
import { Injectable, WritableSignal, signal } from '@angular/core';
|
|
import { HttpClient } from '@angular/common/http';
|
|
import { environment } from 'src/environments/environment';
|
|
import { first, firstValueFrom } from 'rxjs';
|
|
|
|
export enum Role {
|
|
Admin = 3,
|
|
Employer = 2,
|
|
User = 1,
|
|
API = 0,
|
|
Deactivated = -1,
|
|
}
|
|
|
|
export interface User {
|
|
username: string;
|
|
role: Role;
|
|
projects: string[];
|
|
}
|
|
export interface ThisUser extends User {
|
|
chats: string[];
|
|
email: string;
|
|
}
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class UsersService {
|
|
private readonly url = environment.apiURL + '/users';
|
|
public $user = signal<ThisUser | undefined>(undefined);
|
|
|
|
public get token() {
|
|
return localStorage.getItem('token') ?? undefined;
|
|
}
|
|
public set token(token: string | undefined) {
|
|
if (token === undefined) localStorage.removeItem('token');
|
|
else localStorage.setItem('token', token);
|
|
}
|
|
|
|
public async updateUser() {
|
|
if (this.token) {
|
|
const user = await firstValueFrom(this.http.get<ThisUser>(`${this.url}/get?token=${this.token}`));
|
|
this.$user.set(user);
|
|
}
|
|
else this.$user.set(undefined);
|
|
}
|
|
|
|
public async logoff() {
|
|
if (!this.token) return;
|
|
await firstValueFrom(this.http.post(this.url + `/logout?token=${this.token}`, {}));
|
|
this.token = undefined;
|
|
this.$user.set(undefined);
|
|
}
|
|
public async login(username: string, password: string) {
|
|
await this.logoff();
|
|
const token = (await firstValueFrom(this.http.post<any>(this.url + `/login`, { username, password }))).token;
|
|
this.token = token;
|
|
await this.updateUser();
|
|
}
|
|
public async signup(username: string, password: string, email: string) {
|
|
await this.logoff();
|
|
await firstValueFrom(this.http.post(this.url + `/signup`, { username, password, email }));
|
|
await this.updateUser();
|
|
}
|
|
|
|
public async requestCode(username: string) {
|
|
await firstValueFrom(this.http.post<string>(this.url + `/requestCode`, { username }));
|
|
}
|
|
public async confirm(username: string, code: string) {
|
|
await firstValueFrom(this.http.post<string>(this.url + `/confirm`, { username, code }));
|
|
}
|
|
|
|
public async all() {
|
|
return await firstValueFrom(this.http.get<User[]>(this.url + `/all`));
|
|
}
|
|
|
|
public constructor(private http: HttpClient) {
|
|
this.updateUser();
|
|
}
|
|
}
|