Merge "Web Client context menu item display"
[ccsdk/features.git] / sdnr / wt / odlux / framework / src / actions / authentication.ts
1 /**
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt odlux
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  */
18 import { Dispatch } from '../flux/store';
19 import { Action } from '../flux/action';
20 import { AuthPolicy, User } from '../models/authentication';
21 import { Settings } from '../models/settings';
22 import { saveInitialSettings, SetGeneralSettingsAction } from './settingsAction';
23 import { endWebsocketSession } from '../services/notificationService';
24 import { endUserSession, startUserSession } from '../services/userSessionService';
25 import { IApplicationStoreState } from '../store/applicationStore';
26
27 export class UpdateUser extends Action {
28
29   constructor(public user?: User) {
30     super();
31   }
32 }
33
34 export class UpdatePolicies extends Action {
35
36   constructor(public authPolicies?: AuthPolicy[]) {
37     super();
38   }
39 }
40
41 export const logoutUser = () => (dispatcher: Dispatch, getState: () => IApplicationStoreState) =>{
42
43   const { framework:{ applicationState:{ authentication }, authenticationState: { user } } } = getState();
44   
45   dispatcher(new UpdateUser(undefined));
46   dispatcher(new SetGeneralSettingsAction(null));
47   endWebsocketSession();
48   endUserSession();
49   localStorage.removeItem('userToken');
50
51
52   //only call if a user is currently logged in
53   if (authentication === 'oauth' && user) {
54
55     const url = window.location.origin;
56     window.location.href = `${url}/oauth/logout`;
57   }
58 };
59
60 /**
61  * Loads the user settings for the given user and dispatches a `saveInitialSettings` action with the result.
62  * @param user The user for which to load the settings.
63  * @param dispatcher The dispatcher function to use for dispatching the `saveInitialSettings` action.
64  */
65 const loadUserSettings = (user: User | undefined, dispatcher: Dispatch) => {
66
67   // fetch used, because state change for user login is not done when frameworks restRequest call is started (and is accordingly undefined -> /userdata call yields 401, unauthorized) and triggering an action from inside the handler / login event is impossible
68   // no timeout used, because it's bad practice to add a timeout to hopefully avoid a race condition
69   // hence, fetch used to simply use supplied user data for getting settings
70
71   if (user && user.isValid) {
72
73     fetch('/userdata', {
74       method: 'GET', 
75       headers: {
76         'Content-Type': 'application/json',
77         'Accept': 'application/json',
78         'Authorization': `${user.tokenType} ${user.token}`,
79       },
80     }).then((res: Response)=>{
81       if (res.status == 200) {
82         return res.json();
83       } else {
84         return null;
85       }
86     }).then((result:Settings)=>{
87       dispatcher(saveInitialSettings(result));
88     });
89   }  
90 };
91
92 /**
93  * Dispatches an `UpdateUser` action with the given user and starts a user session if the user is defined.
94  * Also loads the user settings for the given user and dispatches a `saveInitialSettings` action with the result.
95  * Finally, saves the user token to local storage.
96  * @param user The user to be logged in.
97  * @param dispatcher The dispatcher function to use for dispatching the actions.
98  */
99 export const loginUserAction = (user?: User) => (dispatcher: Dispatch) =>{
100   
101   dispatcher(new UpdateUser(user));
102   if (user) {
103     startUserSession(user);
104     loadUserSettings(user, dispatcher);
105     localStorage.setItem('userToken', user.toString());
106   }
107 };