You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.3 KiB
57 lines
1.3 KiB
import { Injectable } from '@angular/core';
|
|
import { User } from '../cookbook/type';
|
|
|
|
@Injectable({
|
|
providedIn: 'root',
|
|
})
|
|
export class LoginService {
|
|
async logIn(username: string, password: string): Promise<boolean> {
|
|
const res = await fetch('https://dummyjson.com/user/login', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
username,
|
|
password,
|
|
expiresInMins: 30,
|
|
}),
|
|
});
|
|
if (res.status !== 200) {
|
|
return false;
|
|
}
|
|
const user: User = await res.json();
|
|
localStorage.setItem('user', JSON.stringify(user));
|
|
return true;
|
|
}
|
|
|
|
me(): Promise<User | null> {
|
|
const token = this.currentToken();
|
|
if (!token) {
|
|
return Promise.resolve(null);
|
|
}
|
|
return fetch('http://dummyjson.com/user/me', {
|
|
method: 'GET',
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`,
|
|
},
|
|
})
|
|
.then(res => res.json());
|
|
}
|
|
|
|
isLoggedIn(): boolean {
|
|
return this.currentToken() !== null;
|
|
}
|
|
|
|
currentToken(): string | null {
|
|
const json = localStorage?.getItem('user');
|
|
if (!json) return null;
|
|
return JSON.parse(json).token;
|
|
}
|
|
|
|
logOut(): void {
|
|
localStorage?.removeItem('user');
|
|
}
|
|
}
|