1 | import { HttpClient, HttpHeaders } from "@angular/common/http";
|
---|
2 | import { Injectable } from "@angular/core";
|
---|
3 | import { Observable } from "rxjs";
|
---|
4 | import { map } from "rxjs/operators";
|
---|
5 | import { LoginRequest } from "../_models/dto/loginRequest";
|
---|
6 | import { UserDto } from "../_models/dto/userDto";
|
---|
7 | import { User } from "../_models/user";
|
---|
8 |
|
---|
9 | @Injectable({
|
---|
10 | providedIn: 'root'
|
---|
11 | })
|
---|
12 | export class UserService {
|
---|
13 |
|
---|
14 | headers = new HttpHeaders({
|
---|
15 | 'Content-Type': 'application/json',
|
---|
16 | 'Access-Control-Allow-Headers': 'Content-Type',
|
---|
17 |
|
---|
18 | });
|
---|
19 |
|
---|
20 | constructor(private httpClient: HttpClient) {
|
---|
21 |
|
---|
22 | }
|
---|
23 |
|
---|
24 | registerUser(user: UserDto): Observable<User> {
|
---|
25 | let url = "http://localhost:8080/api/users/register";
|
---|
26 | return this.httpClient.post<User>(url, user, { headers: this.headers });
|
---|
27 | }
|
---|
28 |
|
---|
29 | authenticateUser(loginResult: LoginRequest) {
|
---|
30 | let url = "http://localhost:8080/api/users/login";
|
---|
31 | return this.httpClient.post<any>(url, loginResult)
|
---|
32 | .pipe(
|
---|
33 | map(userData => {
|
---|
34 | sessionStorage.setItem("username", loginResult.username);
|
---|
35 | let tokenStr = userData.token;
|
---|
36 | sessionStorage.setItem("token", tokenStr);
|
---|
37 | return userData;
|
---|
38 | })
|
---|
39 | );
|
---|
40 | }
|
---|
41 |
|
---|
42 | isUserLoggedIn() {
|
---|
43 | let user = sessionStorage.getItem("username");
|
---|
44 | let token = sessionStorage.getItem("token");
|
---|
45 | return !(user === null);
|
---|
46 | }
|
---|
47 |
|
---|
48 | getAllUsernames() {
|
---|
49 | let url = "http://localhost:8080/api/users/usernames";
|
---|
50 | return this.httpClient.get<string[]>(url);
|
---|
51 | }
|
---|
52 |
|
---|
53 | getPassword(loginRequest : LoginRequest){
|
---|
54 | let url="http://localhost:8080/api/users/password";
|
---|
55 | const options = {
|
---|
56 |
|
---|
57 | body: {
|
---|
58 | "username": loginRequest.username
|
---|
59 |
|
---|
60 | }
|
---|
61 | }
|
---|
62 | return this.httpClient.request('get', url, options);
|
---|
63 | }
|
---|
64 |
|
---|
65 | }
|
---|