• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / gui / 1315906619

03 Jun 2024 11:58AM UTC coverage: 83.418% (-16.5%) from 99.964%
1315906619

Pull #4424

gitlab-ci

mzedel
feat: restructured account menu & added option to switch tenant in supporting setups

Ticket: MEN-6906
Changelog: Title
Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #4424: MEN-6906 - tenant switching

4477 of 6394 branches covered (70.02%)

25 of 30 new or added lines in 2 files covered. (83.33%)

1670 existing lines in 162 files now uncovered.

8502 of 10192 relevant lines covered (83.42%)

140.43 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.26
/src/js/components/app.js
1
// Copyright 2015 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14
import React, { useCallback, useEffect, useState } from 'react';
15
import { useIdleTimer, workerTimers } from 'react-idle-timer';
16
import { Provider, useDispatch, useSelector } from 'react-redux';
17
import { BrowserRouter, useLocation, useNavigate } from 'react-router-dom';
18

19
import createCache from '@emotion/cache';
20
import { CacheProvider } from '@emotion/react';
21
import { CssBaseline, GlobalStyles, ThemeProvider, createTheme, styled } from '@mui/material';
22
import { LocalizationProvider } from '@mui/x-date-pickers';
23
import { AdapterMoment } from '@mui/x-date-pickers/AdapterMoment';
24
import { makeStyles } from 'tss-react/mui';
25

26
import Cookies from 'universal-cookie';
27

28
import { parseEnvironmentInfo, setSnackbar } from '../actions/appActions';
29
import { logoutUser, setAccountActivationCode, setShowConnectingDialog } from '../actions/userActions';
30
import { getSessionInfo, maxSessionAge, updateMaxAge } from '../auth';
31
import SharedSnackbar from '../components/common/sharedsnackbar';
32
import { PrivateRoutes, PublicRoutes } from '../config/routes';
33
import { TIMEOUTS } from '../constants/appConstants';
34
import ErrorBoundary from '../errorboundary';
35
import { isDarkMode, toggle } from '../helpers';
36
import store from '../reducers';
37
import { getCurrentSession, getCurrentUser, getUserSettings } from '../selectors';
38
import { dark as darkTheme, light as lightTheme } from '../themes/Mender';
39
import Tracking from '../tracking';
40
import ConfirmDismissHelptips from './common/dialogs/confirmdismisshelptips';
41
import DeviceConnectionDialog from './common/dialogs/deviceconnectiondialog';
42
import Footer from './footer';
43
import Header from './header/header';
44
import LeftNav from './leftnav';
45
import SearchResult from './search-result';
46
import Uploads from './uploads';
47

48
const cache = createCache({ key: 'mui', prepend: true });
1✔
49

50
const activationPath = '/activate';
1✔
51
const trackingBlacklist = [/\/password\/.+/i];
1✔
52
const timeout = maxSessionAge * 1000; // 15 minutes idle time
1✔
53
const cookies = new Cookies();
1✔
54

55
const reducePalette =
56
  prefix =>
1✔
57
  (accu, [key, value]) => {
644✔
58
    if (value instanceof Object) {
2,828✔
59
      return {
616✔
60
        ...accu,
61
        ...Object.entries(value).reduce(reducePalette(`${prefix}-${key}`), {})
62
      };
63
    } else {
64
      accu[`${prefix}-${key}`] = value;
2,212✔
65
    }
66
    return accu;
2,212✔
67
  };
68

69
const cssVariables = ({ theme: { palette } }) => {
1✔
70
  const muiVariables = Object.entries(palette).reduce(reducePalette('--mui'), {});
28✔
71
  return {
28✔
72
    '@global': {
73
      ':root': {
74
        ...muiVariables,
75
        '--mui-overlay': palette.grey[400]
76
      }
77
    }
78
  };
79
};
80

81
const WrappedBaseline = styled(CssBaseline)(cssVariables);
1✔
82

83
const useStyles = makeStyles()(() => ({
4✔
84
  public: {
85
    display: 'grid',
86
    gridTemplateRows: 'max-content 1fr max-content',
87
    height: '100vh',
88
    '.content': {
89
      alignSelf: 'center',
90
      justifySelf: 'center'
91
    }
92
  }
93
}));
94

95
export const AppRoot = () => {
1✔
96
  const [showSearchResult, setShowSearchResult] = useState(false);
14✔
97
  const navigate = useNavigate();
14✔
98
  const { pathname = '', hash } = useLocation();
14!
99

100
  const dispatch = useDispatch();
14✔
101
  const { id: currentUser } = useSelector(getCurrentUser);
14✔
102
  const showDismissHelptipsDialog = useSelector(state => !state.onboarding.complete && state.onboarding.showTipsDialog);
1,593✔
103
  const showDeviceConnectionDialog = useSelector(state => state.users.showConnectDeviceDialog);
1,593✔
104
  const snackbar = useSelector(state => state.app.snackbar);
1,593✔
105
  const trackingCode = useSelector(state => state.app.trackerCode);
1,593✔
106
  const { mode } = useSelector(getUserSettings);
14✔
107
  const { token: storedToken } = getSessionInfo();
14✔
108
  const { expiresAt, token = storedToken } = useSelector(getCurrentSession);
14✔
109

110
  const trackLocationChange = useCallback(
14✔
111
    pathname => {
112
      let page = pathname;
5✔
113
      // if we're on page whose path might contain sensitive device/ group/ deployment names etc. we sanitize the sent information before submission
114
      if (page.includes('=') && (page.startsWith('/devices') || page.startsWith('/deployments'))) {
5!
UNCOV
115
        const splitter = page.lastIndexOf('/');
×
UNCOV
116
        const filters = page.slice(splitter + 1);
×
UNCOV
117
        const keyOnlyFilters = filters.split('&').reduce((accu, item) => `${accu}:${item.split('=')[0]}&`, ''); // assume the keys to filter by are not as revealing as the values things are filtered by
×
UNCOV
118
        page = `${page.substring(0, splitter)}?${keyOnlyFilters.substring(0, keyOnlyFilters.length - 1)}`; // cut off the last & of the reduced filters string
×
119
      } else if (page.startsWith(activationPath)) {
5!
UNCOV
120
        dispatch(setAccountActivationCode(page.substring(activationPath.length + 1)));
×
UNCOV
121
        navigate('/settings/my-profile', { replace: true });
×
122
      } else if (trackingBlacklist.some(item => !!page.match(item))) {
5!
UNCOV
123
        return;
×
124
      }
125
      Tracking.pageview(page);
5✔
126
    },
127
    [dispatch, navigate]
128
  );
129

130
  useEffect(() => {
14✔
131
    dispatch(parseEnvironmentInfo());
5✔
132
    if (!trackingCode) {
5✔
133
      return;
3✔
134
    }
135
    if (!cookies.get('_ga')) {
2!
136
      Tracking.cookieconsent().then(({ trackingConsentGiven }) => {
2✔
UNCOV
137
        if (trackingConsentGiven) {
×
UNCOV
138
          Tracking.initialize(trackingCode);
×
UNCOV
139
          Tracking.pageview();
×
140
        }
141
      });
142
    } else {
UNCOV
143
      Tracking.initialize(trackingCode);
×
144
    }
145
  }, [dispatch, trackingCode]);
146

147
  useEffect(() => {
14✔
148
    if (!(trackingCode && cookies.get('_ga'))) {
6!
149
      return;
6✔
150
    }
UNCOV
151
    trackLocationChange(pathname);
×
152
  }, [pathname, trackLocationChange, trackingCode]);
153

154
  useEffect(() => {
14✔
155
    trackLocationChange(pathname);
5✔
156
    // the following is added to ensure backwards capability for hash containing routes & links (e.g. /ui/#/devices => /ui/devices)
157
    if (hash) {
5!
UNCOV
158
      navigate(hash.substring(1));
×
159
    }
160
  }, [hash, navigate, pathname, trackLocationChange]);
161

162
  const updateExpiryDate = useCallback(() => updateMaxAge({ expiresAt, token }), [expiresAt, token]);
14✔
163

164
  const onIdle = useCallback(() => {
14✔
165
    if (!!expiresAt && currentUser) {
3✔
166
      // logout user and warn
167
      return dispatch(logoutUser())
1✔
168
        .catch(updateExpiryDate)
169
        .then(() => {
170
          navigate('//'); // double / to ensure the logged out URL conforms to `/ui/` in order to not trigger a redirect and potentially use state
1✔
171
          // async snackbar setting to ensure the login screen has loaded as the snackbar might be cleared by other actions otherwise
172
          setTimeout(() => dispatch(setSnackbar('Your session has expired. You have been automatically logged out due to inactivity.')), TIMEOUTS.oneSecond);
1✔
173
        });
174
    }
175
  }, [currentUser, dispatch, expiresAt, navigate, updateExpiryDate]);
176

177
  useIdleTimer({ crossTab: true, onAction: updateExpiryDate, onActive: updateExpiryDate, onIdle, syncTimers: 400, timeout, timers: workerTimers });
14✔
178

179
  const onToggleSearchResult = () => setShowSearchResult(toggle);
14✔
180

181
  const theme = createTheme(isDarkMode(mode) ? darkTheme : lightTheme);
14!
182

183
  const { classes } = useStyles();
14✔
184
  const globalCssVars = cssVariables({ theme })['@global'];
14✔
185

186
  return (
14✔
187
    <ThemeProvider theme={theme}>
188
      <WrappedBaseline enableColorScheme />
189
      <GlobalStyles styles={globalCssVars} />
190
      <>
191
        {token ? (
14✔
192
          <div id="app">
193
            <Header mode={mode} />
194
            <LeftNav />
195
            <div className="rightFluid container">
196
              <ErrorBoundary>
197
                <SearchResult onToggleSearchResult={onToggleSearchResult} open={showSearchResult} />
198
                <PrivateRoutes />
199
              </ErrorBoundary>
200
            </div>
201
            {showDismissHelptipsDialog && <ConfirmDismissHelptips />}
10!
UNCOV
202
            {showDeviceConnectionDialog && <DeviceConnectionDialog onCancel={() => dispatch(setShowConnectingDialog(false))} />}
×
203
          </div>
204
        ) : (
205
          <div className={classes.public}>
206
            <PublicRoutes />
207
            <Footer />
208
          </div>
209
        )}
UNCOV
210
        <SharedSnackbar snackbar={snackbar} setSnackbar={message => dispatch(setSnackbar(message))} />
×
211
        <Uploads />
212
      </>
213
    </ThemeProvider>
214
  );
215
};
216

217
export const AppProviders = ({ basename = 'ui' }) => (
1!
218
  <React.StrictMode>
1✔
219
    <Provider store={store}>
220
      <CacheProvider value={cache}>
221
        <LocalizationProvider dateAdapter={AdapterMoment}>
222
          <ErrorBoundary>
223
            <BrowserRouter basename={basename}>
224
              <AppRoot />
225
            </BrowserRouter>
226
          </ErrorBoundary>
227
        </LocalizationProvider>
228
      </CacheProvider>
229
    </Provider>
230
  </React.StrictMode>
231
);
232

233
export default AppRoot;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc