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

mendersoftware / mender-server / 1460585995

19 Sep 2024 01:02PM UTC coverage: 78.395%. First build
1460585995

Pull #53

gitlab-ci

mzedel
fix: fixed an issue that prevented showing PATs on page refresh

Ticket: ME-340
Changelog: Title
Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #53: ME-340 - fix: fixed an issue that prevented showing PATs on page refresh

4530 of 6462 branches covered (70.1%)

Branch coverage included in aggregate %.

2 of 3 new or added lines in 1 file covered. (66.67%)

8620 of 10312 relevant lines covered (83.59%)

154.95 hits per line

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

88.89
/frontend/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 { useDispatch, useSelector } 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, getIsEnterprise } from '../../selectors';
42
import CopyCode from '../common/copy-code';
43
import Time, { RelativeTime } from '../common/time';
44

45
const useStyles = makeStyles()(theme => ({
13✔
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';
5✔
61
const columnData = [
5✔
62
  { id: 'token', label: 'Token', canShow, render: ({ token }) => token.name },
40✔
63
  { id: creationTimeAttribute, label: 'Date created', canShow, render: ({ token }) => <Time value={token[creationTimeAttribute]} /> },
40✔
64
  {
65
    id: 'expiration_date',
66
    label: 'Expires',
67
    canShow,
68
    render: ({ token }) => <RelativeTime updateTime={token.expiration_date} shouldCount="up" />
40✔
69
  },
70
  {
71
    id: 'last_used',
72
    label: 'Last used',
73
    canShow: ({ hasLastUsedInfo }) => hasLastUsedInfo,
12✔
74
    render: ({ token }) => <RelativeTime updateTime={token.last_used} />
40✔
75
  },
76
  {
77
    id: 'actions',
78
    label: 'Manage',
79
    canShow,
80
    render: ({ onRevokeTokenClick, token }) => <Button onClick={() => onRevokeTokenClick(token)}>Revoke</Button>
40✔
81
  }
82
];
83

84
const A_DAY = 24 * 60 * 60;
5✔
85
const expirationTimes = {
5✔
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, token, userRoles }) => {
5✔
104
  const [name, setName] = useState('');
50✔
105
  const [expirationTime, setExpirationTime] = useState(expirationTimes['a year'].value);
50✔
106
  const [expirationDate, setExpirationDate] = useState(new Date());
50✔
107
  const [hint, setHint] = useState('');
50✔
108
  const { classes } = useStyles();
50✔
109

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

118
  const onGenerateClick = useCallback(() => generateToken({ name, expiresIn: expirationTime }), [generateToken, name, expirationTime]);
50✔
119

120
  const onChangeExpirationTime = ({ target: { value } }) => setExpirationTime(value);
50✔
121

122
  const generationHandler = token ? onCancel : onGenerateClick;
50✔
123

124
  const generationLabel = token ? 'Close' : 'Create token';
50✔
125

126
  const nameUpdated = ({ target: { value } }) => setName(value);
50✔
127

128
  const tokenRoles = useMemo(() => userRoles.map(roleId => rolesById[roleId]?.name).join(', '), [rolesById, userRoles]);
50✔
129

130
  return (
50✔
131
    <Dialog open>
132
      <DialogTitle>Create new token</DialogTitle>
133
      <DialogContent className={classes.creationDialog}>
134
        <form>
135
          <TextField className={`${classes.formEntries} required`} disabled={!!token} onChange={nameUpdated} placeholder="Name" value={name} />
136
        </form>
137
        <div>
138
          <FormControl className={classes.formEntries}>
139
            <InputLabel>Expiration</InputLabel>
140
            <Select disabled={!!token} onChange={onChangeExpirationTime} value={expirationTime}>
141
              {Object.entries(expirationTimes).map(([title, item]) => (
142
                <MenuItem key={item.value} value={item.value}>
250✔
143
                  {title}
144
                </MenuItem>
145
              ))}
146
            </Select>
147
            {hint ? (
50!
148
              <FormHelperText className={classes.warning}>{hint}</FormHelperText>
149
            ) : (
150
              <FormHelperText title={expirationDate.toISOString().slice(0, 10)}>
151
                expires on <Time format="YYYY-MM-DD" value={expirationDate} />
152
              </FormHelperText>
153
            )}
154
          </FormControl>
155
        </div>
156
        {token && (
56✔
157
          <div className="margin-top margin-bottom">
158
            <CopyCode code={token} />
159
            <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>
160
          </div>
161
        )}
162
        {isEnterprise && (
98✔
163
          <FormControl className={classes.formEntries}>
164
            <TextField label="Permission level" id="role-name" value={tokenRoles} disabled />
165
            <FormHelperText>The token will have the same permissions as your user</FormHelperText>
166
          </FormControl>
167
        )}
168
      </DialogContent>
169
      <DialogActions>
170
        {!token && <Button onClick={onCancel}>Cancel</Button>}
94✔
171
        <Button disabled={!name.length} variant="contained" onClick={generationHandler}>
172
          {generationLabel}
173
        </Button>
174
      </DialogActions>
175
    </Dialog>
176
  );
177
};
178

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

192
export const AccessTokenManagement = () => {
5✔
193
  const [showGeneration, setShowGeneration] = useState(false);
29✔
194
  const [showRevocation, setShowRevocation] = useState(false);
29✔
195
  const [currentToken, setCurrentToken] = useState(null);
29✔
196
  const isEnterprise = useSelector(getIsEnterprise);
29✔
197
  const { tokens = [], roles: userRoles = [], id } = useSelector(getCurrentUser);
29!
198
  const rolesById = useSelector(state => state.users.rolesById);
54✔
199
  const dispatch = useDispatch();
29✔
200

201
  const { classes } = useStyles();
29✔
202

203
  useEffect(() => {
29✔
204
    if (!id) {
9!
NEW
205
      return;
×
206
    }
207
    dispatch(getTokens());
9✔
208
  }, [dispatch, id]);
209

210
  const toggleGenerateClick = () => {
29✔
211
    setCurrentToken(null);
4✔
212
    setShowGeneration(toggle);
4✔
213
  };
214

215
  const toggleRevocationClick = () => {
29✔
216
    setCurrentToken(null);
×
217
    setShowRevocation(toggle);
×
218
  };
219

220
  const onRevokeClick = token => dispatch(revokeToken(token)).then(() => toggleRevocationClick());
29✔
221

222
  const onRevokeTokenClick = token => {
29✔
223
    toggleRevocationClick();
×
224
    setCurrentToken(token);
×
225
  };
226

227
  const onGenerateClick = config => dispatch(generateToken(config)).then(results => setCurrentToken(results[results.length - 1]));
29✔
228

229
  const hasLastUsedInfo = useMemo(() => tokens.some(token => !!token.last_used), [tokens]);
29✔
230

231
  const columns = useMemo(
29✔
232
    () =>
233
      columnData.reduce((accu, column) => {
12✔
234
        if (!column.canShow({ hasLastUsedInfo })) {
60✔
235
          return accu;
4✔
236
        }
237
        accu.push(column);
56✔
238
        return accu;
56✔
239
      }, []),
240
    [hasLastUsedInfo]
241
  );
242

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

286
export default 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