summaryrefslogtreecommitdiffstats
path: root/web/react/components/access_history_modal.jsx
blob: 85c28ca5c83ef7e74a537ad242c001096a29baef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

var Modal = ReactBootstrap.Modal;
import UserStore from '../stores/user_store.jsx';
import ChannelStore from '../stores/channel_store.jsx';
import * as AsyncClient from '../utils/async_client.jsx';
import LoadingScreen from './loading_screen.jsx';
import * as Utils from '../utils/utils.jsx';

export default class AccessHistoryModal extends React.Component {
    constructor(props) {
        super(props);

        this.onAuditChange = this.onAuditChange.bind(this);
        this.handleMoreInfo = this.handleMoreInfo.bind(this);
        this.onShow = this.onShow.bind(this);
        this.onHide = this.onHide.bind(this);
        this.formatAuditInfo = this.formatAuditInfo.bind(this);
        this.handleRevokedSession = this.handleRevokedSession.bind(this);

        const state = this.getStateFromStoresForAudits();
        state.moreInfo = [];

        this.state = state;
    }
    getStateFromStoresForAudits() {
        return {
            audits: UserStore.getAudits()
        };
    }
    onShow() {
        AsyncClient.getAudits();

        if ($(window).width() > 768) {
            $(ReactDOM.findDOMNode(this.refs.modalBody)).perfectScrollbar();
            $(ReactDOM.findDOMNode(this.refs.modalBody)).css('max-height', $(window).height() - 200);
        } else {
            $(ReactDOM.findDOMNode(this.refs.modalBody)).css('max-height', $(window).height() - 150);
        }
    }
    onHide() {
        this.setState({moreInfo: []});
        this.props.onHide();
    }
    componentDidMount() {
        UserStore.addAuditsChangeListener(this.onAuditChange);

        if (this.props.show) {
            this.onShow();
        }
    }
    componentDidUpdate(prevProps) {
        if (this.props.show && !prevProps.show) {
            this.onShow();
        }
    }
    componentWillUnmount() {
        UserStore.removeAuditsChangeListener(this.onAuditChange);
    }
    onAuditChange() {
        var newState = this.getStateFromStoresForAudits();
        if (!Utils.areObjectsEqual(newState.audits, this.state.audits)) {
            this.setState(newState);
        }
    }
    handleMoreInfo(index) {
        var newMoreInfo = this.state.moreInfo;
        newMoreInfo[index] = true;
        this.setState({moreInfo: newMoreInfo});
    }
    handleRevokedSession(sessionId) {
        return 'The session with id ' + sessionId + ' was revoked';
    }
    formatAuditInfo(currentAudit) {
        const currentActionURL = currentAudit.action.replace(/\/api\/v[1-9]/, '');

        let currentAuditDesc = '';

        if (currentActionURL.indexOf('/channels') === 0) {
            const channelInfo = currentAudit.extra_info.split(' ');
            const channelNameField = channelInfo[0].split('=');

            let channelURL = '';
            let channelObj;
            let channelName = '';
            if (channelNameField.indexOf('name') >= 0) {
                channelURL = channelNameField[channelNameField.indexOf('name') + 1];
                channelObj = ChannelStore.getByName(channelURL);
                if (channelObj) {
                    channelName = channelObj.display_name;
                } else {
                    channelName = channelURL;
                }
            }

            switch (currentActionURL) {
            case '/channels/create':
                currentAuditDesc = 'Created the ' + channelName + ' channel/group';
                break;
            case '/channels/create_direct':
                currentAuditDesc = 'Established a direct message channel with ' + Utils.getDirectTeammate(channelObj.id).username;
                break;
            case '/channels/update':
                currentAuditDesc = 'Updated the ' + channelName + ' channel/group name';
                break;
            case '/channels/update_desc': // support the old path
            case '/channels/update_header':
                currentAuditDesc = 'Updated the ' + channelName + ' channel/group header';
                break;
            default: {
                let userIdField = [];
                let userId = '';
                let username = '';

                if (channelInfo[1]) {
                    userIdField = channelInfo[1].split('=');

                    if (userIdField.indexOf('user_id') >= 0) {
                        userId = userIdField[userIdField.indexOf('user_id') + 1];
                        username = UserStore.getProfile(userId).username;
                    }
                }

                if (/\/channels\/[A-Za-z0-9]+\/delete/.test(currentActionURL)) {
                    currentAuditDesc = 'Deleted the channel/group with the URL ' + channelURL;
                } else if (/\/channels\/[A-Za-z0-9]+\/add/.test(currentActionURL)) {
                    currentAuditDesc = 'Added ' + username + ' to the ' + channelName + ' channel/group';
                } else if (/\/channels\/[A-Za-z0-9]+\/remove/.test(currentActionURL)) {
                    currentAuditDesc = 'Removed ' + username + ' from the ' + channelName + ' channel/group';
                }

                break;
            }
            }
        } else if (currentActionURL.indexOf('/oauth') === 0) {
            const oauthInfo = currentAudit.extra_info.split(' ');

            switch (currentActionURL) {
            case '/oauth/register': {
                const clientIdField = oauthInfo[0].split('=');

                if (clientIdField[0] === 'client_id') {
                    currentAuditDesc = 'Attempted to register a new OAuth Application with ID ' + clientIdField[1];
                }

                break;
            }
            case '/oauth/allow':
                if (oauthInfo[0] === 'attempt') {
                    currentAuditDesc = 'Attempted to allow a new OAuth service access';
                } else if (oauthInfo[0] === 'success') {
                    currentAuditDesc = 'Successfully gave a new OAuth service access';
                } else if (oauthInfo[0] === 'fail - redirect_uri did not match registered callback') {
                    currentAuditDesc = 'Failed to allow a new OAuth service access - the redirect URI did not match the previously registered callback';
                }

                break;
            case '/oauth/access_token':
                if (oauthInfo[0] === 'attempt') {
                    currentAuditDesc = 'Attempted to get an OAuth access token';
                } else if (oauthInfo[0] === 'success') {
                    currentAuditDesc = 'Successfully added a new OAuth service';
                } else {
                    const oauthTokenFailure = oauthInfo[0].split('-');

                    if (oauthTokenFailure[0].trim() === 'fail' && oauthTokenFailure[1]) {
                        currentAuditDesc = 'Failed to get an OAuth access token - ' + oauthTokenFailure[1].trim();
                    }
                }

                break;
            default:
                break;
            }
        } else if (currentActionURL.indexOf('/users') === 0) {
            const userInfo = currentAudit.extra_info.split(' ');

            switch (currentActionURL) {
            case '/users/login':
                if (userInfo[0] === 'attempt') {
                    currentAuditDesc = 'Attempted to login';
                } else if (userInfo[0] === 'success') {
                    currentAuditDesc = 'Successfully logged in';
                } else if (userInfo[0]) {
                    currentAuditDesc = 'FAILED login attempt';
                }

                break;
            case '/users/revoke_session':
                currentAuditDesc = this.handleRevokedSession(userInfo[0].split('=')[1]);
                break;
            case '/users/newimage':
                currentAuditDesc = 'Updated your profile picture';
                break;
            case '/users/update':
                currentAuditDesc = 'Updated the general settings of your account';
                break;
            case '/users/newpassword':
                if (userInfo[0] === 'attempted') {
                    currentAuditDesc = 'Attempted to change password';
                } else if (userInfo[0] === 'completed') {
                    currentAuditDesc = 'Successfully changed password';
                } else if (userInfo[0] === 'failed - tried to update user password who was logged in through oauth') {
                    currentAuditDesc = 'Failed to change password - tried to update user password who was logged in through oauth';
                }

                break;
            case '/users/update_roles': {
                const userRoles = userInfo[0].split('=')[1];

                currentAuditDesc = 'Updated user role(s) to ';
                if (userRoles.trim()) {
                    currentAuditDesc += userRoles;
                } else {
                    currentAuditDesc += 'member';
                }

                break;
            }
            case '/users/update_active': {
                const updateType = userInfo[0].split('=')[0];
                const updateField = userInfo[0].split('=')[1];

                /* Either describes account activation/deactivation or a revoked session as part of an account deactivation */
                if (updateType === 'active') {
                    if (updateField === 'true') {
                        currentAuditDesc = 'Account made active';
                    } else if (updateField === 'false') {
                        currentAuditDesc = 'Account made inactive';
                    }

                    const actingUserInfo = userInfo[1].split('=');
                    if (actingUserInfo[0] === 'session_user') {
                        const actingUser = UserStore.getProfile(actingUserInfo[1]);
                        const currentUser = UserStore.getCurrentUser();
                        if (currentUser && actingUser && (Utils.isAdmin(currentUser.roles) || Utils.isSystemAdmin(currentUser.roles))) {
                            currentAuditDesc += ' by ' + actingUser.username;
                        } else if (currentUser && actingUser) {
                            currentAuditDesc += ' by an admin';
                        }
                    }
                } else if (updateType === 'session_id') {
                    currentAuditDesc = this.handleRevokedSession(updateField);
                }

                break;
            }
            case '/users/send_password_reset':
                currentAuditDesc = 'Sent an email to ' + userInfo[0].split('=')[1] + ' to reset your password';
                break;
            case '/users/reset_password':
                if (userInfo[0] === 'attempt') {
                    currentAuditDesc = 'Attempted to reset password';
                } else if (userInfo[0] === 'success') {
                    currentAuditDesc = 'Successfully reset password';
                }

                break;
            case '/users/update_notify':
                currentAuditDesc = 'Updated your global notification settings';
                break;
            default:
                break;
            }
        } else if (currentActionURL.indexOf('/hooks') === 0) {
            const webhookInfo = currentAudit.extra_info.split(' ');

            switch (currentActionURL) {
            case '/hooks/incoming/create':
                if (webhookInfo[0] === 'attempt') {
                    currentAuditDesc = 'Attempted to create a webhook';
                } else if (webhookInfo[0] === 'success') {
                    currentAuditDesc = 'Successfully created a webhook';
                } else if (webhookInfo[0] === 'fail - bad channel permissions') {
                    currentAuditDesc = 'Failed to create a webhook - bad channel permissions';
                }

                break;
            case '/hooks/incoming/delete':
                if (webhookInfo[0] === 'attempt') {
                    currentAuditDesc = 'Attempted to delete a webhook';
                } else if (webhookInfo[0] === 'success') {
                    currentAuditDesc = 'Successfully deleted a webhook';
                } else if (webhookInfo[0] === 'fail - inappropriate conditions') {
                    currentAuditDesc = 'Failed to delete a webhook - inappropriate conditions';
                }

                break;
            default:
                break;
            }
        } else {
            switch (currentActionURL) {
            case '/logout':
                currentAuditDesc = 'Logged out of your account';
                break;
            case '/verify_email':
                currentAuditDesc = 'Sucessfully verified your email address';
                break;
            default:
                break;
            }
        }

        /* If all else fails... */
        if (!currentAuditDesc) {
            /* Currently not called anywhere */
            if (currentAudit.extra_info.indexOf('revoked_all=') >= 0) {
                currentAuditDesc = 'Revoked all current sessions for the team';
            } else {
                let currentActionDesc = '';
                if (currentActionURL && currentActionURL.lastIndexOf('/') !== -1) {
                    currentActionDesc = currentActionURL.substring(currentActionURL.lastIndexOf('/') + 1).replace('_', ' ');
                    currentActionDesc = Utils.toTitleCase(currentActionDesc);
                }

                let currentExtraInfoDesc = '';
                if (currentAudit.extra_info) {
                    currentExtraInfoDesc = currentAudit.extra_info;

                    if (currentExtraInfoDesc.indexOf('=') !== -1) {
                        currentExtraInfoDesc = currentExtraInfoDesc.substring(currentExtraInfoDesc.indexOf('=') + 1);
                    }
                }
                currentAuditDesc = currentActionDesc + ' ' + currentExtraInfoDesc;
            }
        }

        const currentDate = new Date(currentAudit.create_at);
        const currentAuditInfo = currentDate.toDateString() + ' - ' + currentDate.toLocaleTimeString(navigator.language, {hour: '2-digit', minute: '2-digit'}) + ' | ' + currentAuditDesc;
        return currentAuditInfo;
    }
    render() {
        var accessList = [];

        for (var i = 0; i < this.state.audits.length; i++) {
            const currentAudit = this.state.audits[i];
            const currentAuditInfo = this.formatAuditInfo(currentAudit);

            var moreInfo = (
                <a
                    href='#'
                    className='theme'
                    onClick={this.handleMoreInfo.bind(this, i)}
                >
                    {'More info'}
                </a>
            );

            if (this.state.moreInfo[i]) {
                if (!currentAudit.session_id) {
                    currentAudit.session_id = 'N/A';

                    if (currentAudit.action.search('/users/login') >= 0) {
                        if (currentAudit.extra_info === 'attempt') {
                            currentAudit.session_id += ' (Login attempt)';
                        } else {
                            currentAudit.session_id += ' (Login failure)';
                        }
                    }
                }

                moreInfo = (
                    <div>
                        <div>{'IP: ' + currentAudit.ip_address}</div>
                        <div>{'Session ID: ' + currentAudit.session_id}</div>
                    </div>
                );
            }

            var divider = null;
            if (i < this.state.audits.length - 1) {
                divider = (<div className='divider-light'></div>);
            }

            accessList[i] = (
                <div
                    key={'accessHistoryEntryKey' + i}
                    className='access-history__table'
                >
                    <div className='access__report'>
                        <div className='report__time'>{currentAuditInfo}</div>
                        <div className='report__info'>
                            {moreInfo}
                        </div>
                        {divider}
                    </div>
                </div>
            );
        }

        var content;
        if (this.state.audits.loading) {
            content = (<LoadingScreen />);
        } else {
            content = (<form role='form'>{accessList}</form>);
        }

        return (
            <Modal
                show={this.props.show}
                onHide={this.onHide}
                bsSize='large'
            >
                <Modal.Header closeButton={true}>
                    <Modal.Title>{'Access History'}</Modal.Title>
                </Modal.Header>
                <Modal.Body ref='modalBody'>
                    {content}
                </Modal.Body>
            </Modal>
        );
    }
}

AccessHistoryModal.propTypes = {
    show: React.PropTypes.bool.isRequired,
    onHide: React.PropTypes.func.isRequired
};