OpenSlides/client/src/app/core/core-services/auth.service.ts

78 lines
2.3 KiB
TypeScript
Raw Normal View History

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { OperatorService } from 'app/core/core-services/operator.service';
import { environment } from 'environments/environment';
import { User } from '../../shared/models/users/user';
import { OpenSlidesService } from './openslides.service';
2018-10-26 10:23:14 +02:00
import { HttpService } from './http.service';
/**
* The data returned by a post request to the login route.
*/
interface LoginResponse {
user_id: number;
user: User;
}
/**
* Authenticates an OpenSlides user with username and password
*/
@Injectable({
providedIn: 'root'
})
2019-02-08 17:24:32 +01:00
export class AuthService {
/**
* Initializes the httpClient and the {@link OperatorService}.
*
2018-10-26 10:23:14 +02:00
* @param http HttpService to send requests to the server
* @param operator Who is using OpenSlides
* @param OpenSlides The openslides service
* @param router To navigate
*/
2018-08-29 13:21:25 +02:00
public constructor(
2018-10-26 10:23:14 +02:00
private http: HttpService,
2018-08-29 13:21:25 +02:00
private operator: OperatorService,
2018-10-26 10:23:14 +02:00
private OpenSlides: OpenSlidesService,
private router: Router
2019-02-08 17:24:32 +01:00
) {}
/**
* Try to log in a user.
*
* Returns an observable 'user' with the correct login information or an error.
* The user will then be stored in the {@link OperatorService},
* errors will be forwarded to the parents error function.
*
* @param username
* @param password
2018-10-26 10:23:14 +02:00
* @returns The login response.
*/
2018-10-26 10:23:14 +02:00
public async login(username: string, password: string): Promise<LoginResponse> {
const user = {
2018-06-30 16:56:18 +02:00
username: username,
password: password
};
2018-10-26 10:23:14 +02:00
const response = await this.http.post<LoginResponse>(environment.urlPrefix + '/users/login/', user);
this.operator.user = new User(response.user);
return response;
}
/**
* Logout function for both the client and the server.
*
* Will clear the current {@link OperatorService} and
* send a `post`-request to `/apps/users/logout/'`
*/
2018-10-26 10:23:14 +02:00
public async logout(): Promise<void> {
this.operator.user = null;
2018-10-26 10:23:14 +02:00
try {
await this.http.post(environment.urlPrefix + '/users/logout/', {});
} catch (e) {
// We do nothing on failures. Reboot OpenSlides anyway.
}
this.router.navigate(['/']);
this.OpenSlides.reboot();
}
}