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 { AxiosInstance } from "axios";
8 import { RootState } from "../store";
9 import { ServiceRepository } from "~/services/services";
10 import { SshKeyResource } from '~/models/ssh-key';
11 import { User } from "~/models/user";
12 import { Session } from "~/models/session";
13 import { Config } from '~/common/config';
14 import { initSessions } from "~/store/auth/auth-action-session";
16 export const authActions = unionize({
17 SAVE_API_TOKEN: ofType<string>(),
20 INIT: ofType<{ user: User, token: string }>(),
21 USER_DETAILS_REQUEST: {},
22 USER_DETAILS_SUCCESS: ofType<User>(),
23 SET_SSH_KEYS: ofType<SshKeyResource[]>(),
24 ADD_SSH_KEY: ofType<SshKeyResource>(),
25 REMOVE_SSH_KEY: ofType<string>(),
26 SET_SESSIONS: ofType<Session[]>(),
27 ADD_SESSION: ofType<Session>(),
28 REMOVE_SESSION: ofType<string>(),
29 UPDATE_SESSION: ofType<Session>()
32 function setAuthorizationHeader(services: ServiceRepository, token: string) {
33 services.apiClient.defaults.headers.common = {
34 Authorization: `OAuth2 ${token}`
36 services.webdavClient.defaults.headers = {
37 Authorization: `OAuth2 ${token}`
41 function removeAuthorizationHeader(client: AxiosInstance) {
42 delete client.defaults.headers.common.Authorization;
45 export const initAuth = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
46 const user = services.authService.getUser();
47 const token = services.authService.getApiToken();
49 setAuthorizationHeader(services, token);
52 dispatch(authActions.INIT({ user, token }));
53 dispatch<any>(initSessions(services.authService, config, user));
57 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
58 services.authService.saveApiToken(token);
59 setAuthorizationHeader(services, token);
60 dispatch(authActions.SAVE_API_TOKEN(token));
63 export const login = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
64 services.authService.login();
65 dispatch(authActions.LOGIN());
68 export const logout = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
69 services.authService.removeApiToken();
70 services.authService.removeUser();
71 removeAuthorizationHeader(services.apiClient);
72 services.authService.logout();
73 dispatch(authActions.LOGOUT());
76 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
77 dispatch(authActions.USER_DETAILS_REQUEST());
78 return services.authService.getUserDetails().then(user => {
79 services.authService.saveUser(user);
80 dispatch(authActions.USER_DETAILS_SUCCESS(user));
85 export type AuthAction = UnionOf<typeof authActions>;