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 = () =>
35 (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
36 const user = services.authService.getUser();
37 const token = services.authService.getApiToken();
39 setAuthorizationHeader(services, token);
42 dispatch(authActions.INIT({ user, token }));
46 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
47 services.authService.saveApiToken(token);
48 setAuthorizationHeader(services, token);
49 dispatch(authActions.SAVE_API_TOKEN(token));
52 export const login = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
53 services.authService.login();
54 dispatch(authActions.LOGIN());
57 export const logout = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
58 services.authService.removeApiToken();
59 services.authService.removeUser();
60 removeAuthorizationHeader(services.apiClient);
61 services.authService.logout();
62 dispatch(authActions.LOGOUT());
65 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
66 dispatch(authActions.USER_DETAILS_REQUEST());
67 return services.authService.getUserDetails().then(user => {
68 services.authService.saveUser(user);
69 dispatch(authActions.USER_DETAILS_SUCCESS(user));
74 export type AuthAction = UnionOf<typeof authActions>;