6b81c31796a41dce91cce146f560978cd5510d56
[arvados-workbench2.git] / src / store / auth / auth-action.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { ofType, default as unionize, UnionOf } from "unionize";
6 import { Dispatch } from "redux";
7 import { User } from "../../models/user";
8 import { RootState } from "../store";
9 import { ServiceRepository } from "../../services/services";
10 import { AxiosInstance } from "axios";
11
12 export const authActions = unionize({
13     SAVE_API_TOKEN: ofType<string>(),
14     LOGIN: {},
15     LOGOUT: {},
16     INIT: ofType<{ user: User, token: string }>(),
17     USER_DETAILS_REQUEST: {},
18     USER_DETAILS_SUCCESS: ofType<User>()
19 }, {
20     tag: 'type',
21     value: 'payload'
22 });
23
24 function setAuthorizationHeader(client: AxiosInstance, token: string) {
25     client.defaults.headers.common = {
26         Authorization: `OAuth2 ${token}`
27     };
28 }
29
30 function removeAuthorizationHeader(client: AxiosInstance) {
31     delete client.defaults.headers.common.Authorization;
32 }
33
34 export const initAuth = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
35     const user = services.authService.getUser();
36     const token = services.authService.getApiToken();
37     if (token) {
38         setAuthorizationHeader(services.apiClient, token);
39     }
40     if (token && user) {
41         dispatch(authActions.INIT({ user, token }));
42     }
43 };
44
45 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
46     services.authService.saveApiToken(token);
47     setAuthorizationHeader(services.apiClient, token);
48     dispatch(authActions.SAVE_API_TOKEN(token));
49 };
50
51 export const login = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
52     services.authService.login();
53     dispatch(authActions.LOGIN());
54 };
55
56 export const logout = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
57     services.authService.removeApiToken();
58     services.authService.removeUser();
59     removeAuthorizationHeader(services.apiClient);
60     services.authService.logout();
61     dispatch(authActions.LOGOUT());
62 };
63
64 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
65     dispatch(authActions.USER_DETAILS_REQUEST());
66     return services.authService.getUserDetails().then(user => {
67         services.authService.saveUser(user);
68         dispatch(authActions.USER_DETAILS_SUCCESS(user));
69         return user;
70     });
71 };
72
73 export type AuthAction = UnionOf<typeof authActions>;