Create wt-odlux directory
[ccsdk/features.git] / sdnr / wt-odlux / odlux / framework / src / middleware / navigation.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 * as jwt from 'jsonwebtoken';
19 import { History, createHashHistory } from 'history';
20
21 import { User } from '../models/authentication';
22
23 import { LocationChanged, NavigateToApplication } from '../actions/navigationActions';
24 import { PushAction, ReplaceAction, GoAction, GoBackAction, GoForwardeAction } from '../actions/navigationActions';
25
26 import { applicationManager } from '../services/applicationManager';
27 import { loginUserAction, logoutUser } from '../actions/authentication';
28
29 import { ApplicationStore } from '../store/applicationStore';
30 import { Dispatch } from '../flux/store';
31
32 export const history = createHashHistory();
33 let applicationStore: ApplicationStore | null = null;
34
35 const routerMiddlewareCreator = (historyParam: History) => () => (next: Dispatch): Dispatch => (action) => {
36
37   if (action instanceof NavigateToApplication) {
38     const application = applicationManager.applications && applicationManager.applications[action.applicationName];
39     if (application) {
40       const href = `/${application.path || application.name}${action.href ? '/' + action.href : ''}`.replace(/\/{2,}/i, '/');
41       if (action.replace) {
42         historyParam.replace(href, action.state);
43       } else {
44         historyParam.push(href, action.state);
45       }
46     }
47   } else if (action instanceof PushAction) {
48     historyParam.push(action.href, action.state);
49   } else if (action instanceof ReplaceAction) {
50     historyParam.replace(action.href, action.state);
51   } else if (action instanceof GoAction) {
52     historyParam.go(action.index);
53   } else if (action instanceof GoBackAction) {
54     historyParam.goBack();
55   } else if (action instanceof GoForwardeAction) {
56     historyParam.goForward();
57   } else if (action instanceof LocationChanged) {
58     // ensure user is logged in and token is valid
59     if (action.pathname.startsWith('/oauth') && (action.search.startsWith('?token='))) {
60       const ind =  action.search.lastIndexOf('token=');
61       const tokenStr = ind > -1 ? action.search.substring(ind + 6) : null;
62       const token = tokenStr && jwt.decode(tokenStr);
63       if (tokenStr && token) {
64         // @ts-ignore
65         const user = new User({ username: token.name, access_token: tokenStr, token_type: 'Bearer', expires: token.exp, issued: token.iat }) || undefined;
66         applicationStore?.dispatch(loginUserAction(user));
67       }
68     } if (!action.pathname.startsWith('/login') && applicationStore && (!applicationStore.state.framework.authenticationState.user || !applicationStore.state.framework.authenticationState.user.isValid)) {
69       historyParam.replace(`/login?returnTo=${action.pathname}`);
70       applicationStore.dispatch(logoutUser());
71     
72     } else if (action.pathname.startsWith('/login') && applicationStore && (applicationStore.state.framework.authenticationState.user && applicationStore.state.framework.authenticationState.user.isValid)) {
73       historyParam.replace('/');
74     } else {
75       return next(action);
76     }
77   } else {
78     return next(action);
79   }
80   return action;
81 };
82
83 const startListener = (historyParam: History, store: ApplicationStore) => {
84   store.dispatch(new LocationChanged(historyParam.location.pathname, historyParam.location.search, historyParam.location.hash));
85   historyParam.listen((location) => {
86     store.dispatch(new LocationChanged(location.pathname, location.search, location.hash));
87   });
88 };
89
90 export const startHistoryListener = (store: ApplicationStore) => {
91   applicationStore = store;
92   startListener(history, store);
93 };
94
95 export const routerMiddleware = routerMiddlewareCreator(history);
96 export default routerMiddleware;