16848: Adds expiration date to the "Get API Token" dialog.
[arvados-workbench2.git] / src / store / auth / auth-action.test.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { initAuth } from "./auth-action";
6 import { API_TOKEN_KEY } from "~/services/auth-service/auth-service";
7
8 import 'jest-localstorage-mock';
9 import { ServiceRepository, createServices } from "~/services/services";
10 import { configureStore, RootStore } from "../store";
11 import { createBrowserHistory } from "history";
12 import { Config, mockConfig } from '~/common/config';
13 import { ApiActions } from "~/services/api/api-actions";
14 import { ACCOUNT_LINK_STATUS_KEY } from '~/services/link-account-service/link-account-service';
15 import Axios from "axios";
16 import MockAdapter from "axios-mock-adapter";
17 import { ImportMock } from 'ts-mock-imports';
18 import * as servicesModule from "~/services/services";
19
20 describe('auth-actions', () => {
21     const axiosInst = Axios.create({ headers: {} });
22     const axiosMock = new MockAdapter(axiosInst);
23
24     let store: RootStore;
25     let services: ServiceRepository;
26     const config: any = {};
27     const actions: ApiActions = {
28         progressFn: (id: string, working: boolean) => { },
29         errorFn: (id: string, message: string) => { }
30     };
31     let importMocks: any[];
32
33     beforeEach(() => {
34         axiosMock.reset();
35         services = createServices(mockConfig({}), actions, axiosInst);
36         store = configureStore(createBrowserHistory(), services, config);
37         localStorage.clear();
38         importMocks = [];
39     });
40
41     afterEach(() => {
42         importMocks.map(m => m.restore());
43     });
44
45     it('should initialise state with user and api token from local storage', (done) => {
46
47         axiosMock
48             .onGet("/users/current")
49             .reply(200, {
50                 email: "test@test.com",
51                 first_name: "John",
52                 last_name: "Doe",
53                 uuid: "zzzzz-tpzed-abcefg",
54                 owner_uuid: "ownerUuid",
55                 is_admin: false,
56                 is_active: true,
57                 username: "jdoe",
58                 prefs: {}
59             });
60
61         axiosMock
62             .onGet("/api_client_authorizations/current")
63             .reply(200, {
64                 expires_at: "2140-01-01T00:00:00.000Z"
65             });
66
67         axiosMock
68             .onGet("https://xc59z.arvadosapi.com/discovery/v1/apis/arvados/v1/rest")
69             .reply(200, {
70                 baseUrl: "https://xc59z.arvadosapi.com/arvados/v1",
71                 keepWebServiceUrl: "",
72                 keepWebInlineServiceUrl: "",
73                 remoteHosts: {},
74                 rootUrl: "https://xc59z.arvadosapi.com",
75                 uuidPrefix: "xc59z",
76                 websocketUrl: "",
77                 workbenchUrl: "",
78                 workbench2Url: "",
79                 revision: 12345678
80             });
81
82         importMocks.push(ImportMock.mockFunction(servicesModule, 'createServices', services));
83
84         // Only test the case when a link account operation is not being cancelled
85         sessionStorage.setItem(ACCOUNT_LINK_STATUS_KEY, "0");
86         localStorage.setItem(API_TOKEN_KEY, "token");
87
88         const config: any = {
89             rootUrl: "https://zzzzz.arvadosapi.com",
90             uuidPrefix: "zzzzz",
91             remoteHosts: { xc59z: "xc59z.arvadosapi.com" },
92             apiRevision: 12345678,
93             clusterConfig: {
94                 Login: { LoginCluster: "" },
95             },
96         };
97
98         store.dispatch(initAuth(config));
99
100         store.subscribe(() => {
101             const auth = store.getState().auth;
102             if (auth.apiToken === "token" &&
103                 auth.sessions.length === 2 &&
104                 auth.sessions[0].status === 2 &&
105                 auth.sessions[1].status === 2
106             ) {
107                 try {
108                     expect(auth).toEqual({
109                         apiToken: "token",
110                         apiTokenExpiration: new Date("2140-01-01T00:00:00.000Z"),
111                         config: {
112                             apiRevision: 12345678,
113                             clusterConfig: {
114                                 Login: {
115                                     LoginCluster: "",
116                                 },
117                             },
118                             remoteHosts: {
119                                 "xc59z": "xc59z.arvadosapi.com",
120                             },
121                             rootUrl: "https://zzzzz.arvadosapi.com",
122                             uuidPrefix: "zzzzz",
123                         },
124                         sshKeys: [],
125                         extraApiToken: undefined,
126                         extraApiTokenExpiration: undefined,
127                         homeCluster: "zzzzz",
128                         localCluster: "zzzzz",
129                         loginCluster: undefined,
130                         remoteHostsConfig: {
131                             "zzzzz": {
132                                 "apiRevision": 12345678,
133                                 "clusterConfig": {
134                                     "Login": {
135                                         "LoginCluster": "",
136                                     },
137                                 },
138                                 "remoteHosts": {
139                                     "xc59z": "xc59z.arvadosapi.com",
140                                 },
141                                 "rootUrl": "https://zzzzz.arvadosapi.com",
142                                 "uuidPrefix": "zzzzz",
143                             },
144                             "xc59z": mockConfig({
145                                 apiRevision: 12345678,
146                                 baseUrl: "https://xc59z.arvadosapi.com/arvados/v1",
147                                 rootUrl: "https://xc59z.arvadosapi.com",
148                                 uuidPrefix: "xc59z"
149                             })
150                         },
151                         remoteHosts: {
152                             zzzzz: "zzzzz.arvadosapi.com",
153                             xc59z: "xc59z.arvadosapi.com"
154                         },
155                         sessions: [{
156                             "active": true,
157                             "baseUrl": undefined,
158                             "clusterId": "zzzzz",
159                             "email": "test@test.com",
160                             "loggedIn": true,
161                             "remoteHost": "https://zzzzz.arvadosapi.com",
162                             "status": 2,
163                             "token": "token",
164                             "name": "John Doe",
165                             "apiRevision": 12345678,
166                             "uuid": "zzzzz-tpzed-abcefg",
167                             "userIsActive": true
168                         }, {
169                             "active": false,
170                             "baseUrl": "",
171                             "clusterId": "xc59z",
172                             "email": "",
173                             "loggedIn": false,
174                             "remoteHost": "xc59z.arvadosapi.com",
175                             "status": 2,
176                             "token": "",
177                             "name": "",
178                             "uuid": "",
179                             "apiRevision": 0,
180                         }],
181                         user: {
182                             email: "test@test.com",
183                             firstName: "John",
184                             lastName: "Doe",
185                             uuid: "zzzzz-tpzed-abcefg",
186                             ownerUuid: "ownerUuid",
187                             username: "jdoe",
188                             prefs: { profile: {} },
189                             isAdmin: false,
190                             isActive: true
191                         }
192                     });
193                     done();
194                 } catch (e) {
195                     console.log(e);
196                 }
197             }
198         });
199     });
200
201
202     // TODO: Add remaining action tests
203     /*
204        it('should fire external url to login', () => {
205        const initialState = undefined;
206        window.location.assign = jest.fn();
207        reducer(initialState, authActions.LOGIN());
208        expect(window.location.assign).toBeCalledWith(
209        `/login?return_to=${window.location.protocol}//${window.location.host}/token`
210        );
211        });
212
213        it('should fire external url to logout', () => {
214        const initialState = undefined;
215        window.location.assign = jest.fn();
216        reducer(initialState, authActions.LOGOUT());
217        expect(window.location.assign).toBeCalledWith(
218        `/logout?return_to=${location.protocol}//${location.host}`
219        );
220        });
221      */
222 });