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";
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>()
24 function setAuthorizationHeader(services: ServiceRepository, token: string) {
25 services.apiClient.defaults.headers.common = {
26 Authorization: `OAuth2 ${token}`
28 services.webdavClient.defaults.headers = {
29 Authorization: `OAuth2 ${token}`
33 function removeAuthorizationHeader(client: AxiosInstance) {
34 delete client.defaults.headers.common.Authorization;
37 export const initAuth = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
38 const user = services.authService.getUser();
39 const token = services.authService.getApiToken();
41 setAuthorizationHeader(services, token);
44 dispatch(authActions.INIT({ user, token }));
48 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
49 services.authService.saveApiToken(token);
50 setAuthorizationHeader(services, token);
51 dispatch(authActions.SAVE_API_TOKEN(token));
54 export const login = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
55 services.authService.login();
56 dispatch(authActions.LOGIN());
59 export const logout = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
60 services.authService.removeApiToken();
61 services.authService.removeUser();
62 removeAuthorizationHeader(services.apiClient);
63 services.authService.logout();
64 dispatch(authActions.LOGOUT());
67 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
68 dispatch(authActions.USER_DETAILS_REQUEST());
69 return services.authService.getUserDetails().then(user => {
70 services.authService.saveUser(user);
71 dispatch(authActions.USER_DETAILS_SUCCESS(user));
76 export type AuthAction = UnionOf<typeof authActions>;