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

mendersoftware / gui / 891984097

pending completion
891984097

Pull #3741

gitlab-ci

mzedel
chore: made use of common truth function across codebase to remove code duplication

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #3741: MEN-6487 - fix: added more granular check for device troubleshooting feature

4401 of 6401 branches covered (68.75%)

26 of 27 new or added lines in 8 files covered. (96.3%)

1702 existing lines in 165 files now uncovered.

8060 of 9779 relevant lines covered (82.42%)

123.44 hits per line

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

89.58
/src/js/components/settings/accesstokenmanagement.js
1
// Copyright 2022 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, useMemo, useState } from 'react';
15
import { connect } from 'react-redux';
16

17
// material ui
18
import {
19
  Button,
20
  Dialog,
21
  DialogActions,
22
  DialogContent,
23
  DialogTitle,
24
  FormControl,
25
  FormHelperText,
26
  InputLabel,
27
  MenuItem,
28
  Select,
29
  Table,
30
  TableBody,
31
  TableCell,
32
  TableHead,
33
  TableRow,
34
  TextField
35
} from '@mui/material';
36
import { makeStyles } from 'tss-react/mui';
37

38
import { generateToken, getTokens, revokeToken } from '../../actions/userActions';
39
import { canAccess as canShow } from '../../constants/appConstants';
40
import { customSort, toggle } from '../../helpers';
41
import { getCurrentUser, getTenantCapabilities } from '../../selectors';
42
import CopyCode from '../common/copy-code';
43
import Time, { RelativeTime } from '../common/time';
44

45
const useStyles = makeStyles()(theme => ({
6✔
46
  accessTokens: {
47
    minWidth: 900
48
  },
49
  creationDialog: {
50
    minWidth: 500
51
  },
52
  formEntries: {
53
    minWidth: 270
54
  },
55
  warning: {
56
    color: theme.palette.warning.main
57
  }
58
}));
59

60
const creationTimeAttribute = 'created_ts';
6✔
61
const columnData = [
6✔
62
  { id: 'token', label: 'Token', canShow, render: ({ token }) => token.name },
2✔
63
  { id: creationTimeAttribute, label: 'Date created', canShow, render: ({ token }) => <Time value={token[creationTimeAttribute]} /> },
2✔
64
  {
65
    id: 'expiration_date',
66
    label: 'Expires',
67
    canShow,
68
    render: ({ token }) => <RelativeTime updateTime={token.expiration_date} shouldCount="up" />
2✔
69
  },
70
  {
71
    id: 'last_used',
72
    label: 'Last used',
73
    canShow: ({ hasLastUsedInfo }) => hasLastUsedInfo,
4✔
74
    render: ({ token }) => <RelativeTime updateTime={token.last_used} />
2✔
75
  },
76
  {
77
    id: 'actions',
78
    label: 'Manage',
79
    canShow,
80
    render: ({ onRevokeTokenClick, token }) => <Button onClick={() => onRevokeTokenClick(token)}>Revoke</Button>
2✔
81
  }
82
];
83

84
const A_DAY = 24 * 60 * 60;
6✔
85
const expirationTimes = {
6✔
86
  'never': {
87
    value: 0,
88
    hint: (
89
      <>
90
        The token will never expire.
91
        <br />
92
        WARNING: Never-expiring tokens are against security best practices. We highly suggest setting a token expiration date and rotating the secret at least
93
        yearly.
94
      </>
95
    )
96
  },
97
  '7 days': { value: 7 * A_DAY },
98
  '30 days': { value: 30 * A_DAY },
99
  '90 days': { value: 90 * A_DAY },
100
  'a year': { value: 365 * A_DAY }
101
};
102

103
export const AccessTokenCreationDialog = ({ onCancel, generateToken, isEnterprise, rolesById, setToken, token, userRoles }) => {
6✔
104
  const [name, setName] = useState('');
13✔
105
  const [expirationTime, setExpirationTime] = useState(expirationTimes['a year'].value);
13✔
106
  const [expirationDate, setExpirationDate] = useState(new Date());
13✔
107
  const [hint, setHint] = useState('');
13✔
108
  const { classes } = useStyles();
13✔
109

110
  useEffect(() => {
13✔
111
    const date = new Date();
2✔
112
    date.setSeconds(date.getSeconds() + expirationTime);
2✔
113
    setExpirationDate(date);
2✔
114
    const hint = Object.values(expirationTimes).find(({ value }) => value === expirationTime)?.hint ?? '';
10✔
115
    setHint(hint);
2✔
116
  }, [expirationTime]);
117

118
  const onGenerateClick = useCallback(
13✔
119
    () => generateToken({ name, expiresIn: expirationTime }).then(results => setToken(results[results.length - 1])),
1✔
120
    [name, expirationTime]
121
  );
122

123
  const onChangeExpirationTime = ({ target: { value } }) => setExpirationTime(value);
13✔
124

125
  const generationHandler = token ? onCancel : onGenerateClick;
13✔
126

127
  const generationLabel = token ? 'Close' : 'Create token';
13✔
128

129
  const nameUpdated = ({ target: { value } }) => setName(value);
13✔
130

131
  const tokenRoles = useMemo(() => userRoles.map(roleId => rolesById[roleId]?.name).join(', '), [rolesById, userRoles]);
13✔
132

133
  return (
13✔
134
    <Dialog open>
135
      <DialogTitle>Create new token</DialogTitle>
136
      <DialogContent className={classes.creationDialog}>
137
        <form>
138
          <TextField className={`${classes.formEntries} required`} disabled={!!token} onChange={nameUpdated} placeholder="Name" value={name} />
139
        </form>
140
        <div>
141
          <FormControl className={classes.formEntries}>
142
            <InputLabel>Expiration</InputLabel>
143
            <Select disabled={!!token} onChange={onChangeExpirationTime} value={expirationTime}>
144
              {Object.entries(expirationTimes).map(([title, item]) => (
145
                <MenuItem key={item.value} value={item.value}>
65✔
146
                  {title}
147
                </MenuItem>
148
              ))}
149
            </Select>
150
            {hint ? (
13!
151
              <FormHelperText className={classes.warning}>{hint}</FormHelperText>
152
            ) : (
153
              <FormHelperText title={expirationDate.toISOString().slice(0, 10)}>
154
                expires on <Time format="YYYY-MM-DD" value={expirationDate} />
155
              </FormHelperText>
156
            )}
157
          </FormControl>
158
        </div>
159
        {token && (
16✔
160
          <div className="margin-top margin-bottom">
161
            <CopyCode code={token} />
162
            <p className="warning">This is the only time you will be able to see the token, so make sure to store it in a safe place.</p>
163
          </div>
164
        )}
165
        {isEnterprise && (
13!
166
          <FormControl className={classes.formEntries}>
167
            <TextField label="Permission level" id="role-name" value={tokenRoles} disabled />
168
            <FormHelperText>The token will have the same permissions as your user</FormHelperText>
169
          </FormControl>
170
        )}
171
      </DialogContent>
172
      <DialogActions>
173
        {!token && <Button onClick={onCancel}>Cancel</Button>}
23✔
174
        <Button disabled={!name.length} variant="contained" onClick={generationHandler}>
175
          {generationLabel}
176
        </Button>
177
      </DialogActions>
178
    </Dialog>
179
  );
180
};
181

182
export const AccessTokenRevocationDialog = ({ onCancel, revokeToken, token }) => (
6✔
183
  <Dialog open>
1✔
184
    <DialogTitle>Revoke token</DialogTitle>
185
    <DialogContent>
186
      Are you sure you want to revoke the token <b>{token?.name}</b>?
187
    </DialogContent>
188
    <DialogActions>
189
      <Button onClick={onCancel}>Cancel</Button>
UNCOV
190
      <Button onClick={() => revokeToken(token)}>Revoke Token</Button>
×
191
    </DialogActions>
192
  </Dialog>
193
);
194

195
export const AccessTokenManagement = ({ generateToken, getTokens, revokeToken, isEnterprise, rolesById, tokens = [], userRoles = [] }) => {
6!
196
  const [showGeneration, setShowGeneration] = useState(false);
6✔
197
  const [showRevocation, setShowRevocation] = useState(false);
6✔
198
  const [currentToken, setCurrentToken] = useState(null);
6✔
199

200
  const { classes } = useStyles();
6✔
201

202
  useEffect(() => {
6✔
203
    getTokens();
4✔
204
  }, []);
205

206
  const toggleGenerateClick = () => {
6✔
207
    setCurrentToken(null);
1✔
208
    setShowGeneration(toggle);
1✔
209
  };
210

211
  const toggleRevocationClick = () => {
6✔
UNCOV
212
    setCurrentToken(null);
×
UNCOV
213
    setShowRevocation(toggle);
×
214
  };
215

216
  const onRevokeClick = token => revokeToken(token).then(() => toggleRevocationClick());
6✔
217

218
  const onRevokeTokenClick = token => {
6✔
UNCOV
219
    toggleRevocationClick();
×
UNCOV
220
    setCurrentToken(token);
×
221
  };
222

223
  const hasLastUsedInfo = useMemo(() => tokens.some(token => !!token.last_used), [tokens]);
6✔
224

225
  const columns = useMemo(
6✔
226
    () =>
227
      columnData.reduce((accu, column) => {
4✔
228
        if (!column.canShow({ hasLastUsedInfo })) {
20✔
229
          return accu;
3✔
230
        }
231
        accu.push(column);
17✔
232
        return accu;
17✔
233
      }, []),
234
    [hasLastUsedInfo]
235
  );
236

237
  return (
6✔
238
    <>
239
      <div className={`flexbox space-between margin-top ${tokens.length ? classes.accessTokens : ''}`}>
6✔
240
        <p className="help-content">Personal access token management</p>
241
        <Button onClick={toggleGenerateClick}>Generate a token</Button>
242
      </div>
243
      {!!tokens.length && (
7✔
244
        <Table className={classes.accessTokens}>
245
          <TableHead>
246
            <TableRow>
247
              {columns.map(column => (
248
                <TableCell key={column.id} padding={column.disablePadding ? 'none' : 'normal'}>
5!
249
                  {column.label}
250
                </TableCell>
251
              ))}
252
            </TableRow>
253
          </TableHead>
254
          <TableBody>
255
            {tokens.sort(customSort(true, creationTimeAttribute)).map(token => (
256
              <TableRow key={token.id} hover>
2✔
257
                {columns.map(column => (
258
                  <TableCell key={column.id}>{column.render({ onRevokeTokenClick, token })}</TableCell>
10✔
259
                ))}
260
              </TableRow>
261
            ))}
262
          </TableBody>
263
        </Table>
264
      )}
265
      {showGeneration && (
8✔
266
        <AccessTokenCreationDialog
267
          onCancel={toggleGenerateClick}
268
          generateToken={generateToken}
269
          isEnterprise={isEnterprise}
270
          rolesById={rolesById}
271
          setToken={setCurrentToken}
272
          token={currentToken}
273
          userRoles={userRoles}
274
        />
275
      )}
276
      {showRevocation && <AccessTokenRevocationDialog onCancel={toggleRevocationClick} revokeToken={onRevokeClick} token={currentToken} />}
6!
277
    </>
278
  );
279
};
280

281
const actionCreators = { generateToken, getTokens, revokeToken };
6✔
282

283
const mapStateToProps = state => {
6✔
284
  const { isEnterprise } = getTenantCapabilities(state);
3✔
285
  const { tokens, roles: userRoles } = getCurrentUser(state);
3✔
286
  return {
3✔
287
    isEnterprise,
288
    rolesById: state.users.rolesById,
289
    tokens,
290
    userRoles
291
  };
292
};
293

294
export default connect(mapStateToProps, actionCreators)(AccessTokenManagement);
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