1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { ofType, unionize, UnionOf } from '~/common/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";
12 export const authActions = unionize({
13 SAVE_API_TOKEN: ofType<string>(),
16 INIT: ofType<{ user: User, token: string }>(),
17 USER_DETAILS_REQUEST: {},
18 USER_DETAILS_SUCCESS: ofType<User>()
21 function setAuthorizationHeader(services: ServiceRepository, token: string) {
22 services.apiClient.defaults.headers.common = {
23 Authorization: `OAuth2 ${token}`
25 services.webdavClient.defaults.headers = {
26 Authorization: `OAuth2 ${token}`
30 function removeAuthorizationHeader(client: AxiosInstance) {
31 delete client.defaults.headers.common.Authorization;
34 export const initAuth = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
35 const user = services.authService.getUser();
36 const token = services.authService.getApiToken();
38 setAuthorizationHeader(services, token);
41 dispatch(authActions.INIT({ user, token }));
45 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
46 services.authService.saveApiToken(token);
47 setAuthorizationHeader(services, token);
48 dispatch(authActions.SAVE_API_TOKEN(token));
51 export const login = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
52 services.authService.login();
53 dispatch(authActions.LOGIN());
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());
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));
73 export type AuthAction = UnionOf<typeof authActions>;