1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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 import { initSidePanelTree } from '../side-panel-tree/side-panel-tree-actions';
12 import { updateResources } from '../resources/resources-actions';
14 export const authActions = unionize({
15 SAVE_API_TOKEN: ofType<string>(),
18 INIT: ofType<{ user: User, token: string }>(),
19 USER_DETAILS_REQUEST: {},
20 USER_DETAILS_SUCCESS: ofType<User>()
26 function setAuthorizationHeader(services: ServiceRepository, token: string) {
27 services.apiClient.defaults.headers.common = {
28 Authorization: `OAuth2 ${token}`
30 services.webdavClient.defaults.headers = {
31 Authorization: `OAuth2 ${token}`
35 function removeAuthorizationHeader(client: AxiosInstance) {
36 delete client.defaults.headers.common.Authorization;
39 export const initAuth = () =>
40 (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
41 const user = services.authService.getUser();
42 const token = services.authService.getApiToken();
44 setAuthorizationHeader(services, token);
47 dispatch(authActions.INIT({ user, token }));
51 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
52 services.authService.saveApiToken(token);
53 setAuthorizationHeader(services, token);
54 dispatch(authActions.SAVE_API_TOKEN(token));
57 export const login = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
58 services.authService.login();
59 dispatch(authActions.LOGIN());
62 export const logout = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
63 services.authService.removeApiToken();
64 services.authService.removeUser();
65 removeAuthorizationHeader(services.apiClient);
66 services.authService.logout();
67 dispatch(authActions.LOGOUT());
70 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
71 dispatch(authActions.USER_DETAILS_REQUEST());
72 return services.authService.getUserDetails().then(user => {
73 services.authService.saveUser(user);
74 dispatch(authActions.USER_DETAILS_SUCCESS(user));
79 export type AuthAction = UnionOf<typeof authActions>;