forked from RocketChat/Rocket.Chat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddOAuthApp.ts
More file actions
69 lines (58 loc) · 2.23 KB
/
addOAuthApp.ts
File metadata and controls
69 lines (58 loc) · 2.23 KB
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
import type { IOAuthApps, IUser } from '@rocket.chat/core-typings';
import { OAuthApps, Users } from '@rocket.chat/models';
import { Random } from '@rocket.chat/random';
import { Meteor } from 'meteor/meteor';
import { parseUriList } from './parseUriList';
import type { OauthAppsAddParams } from '../../../../api/server/v1/oauthapps';
import { hasPermissionAsync } from '../../../../authorization/server/functions/hasPermission';
export async function addOAuthApp(applicationParams: OauthAppsAddParams, uid: IUser['_id'] | undefined): Promise<IOAuthApps> {
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'addOAuthApp' });
}
const user = await Users.findOneById(uid, { projection: { username: 1 } });
if (!user?.username) {
// TODO: username is required, but not always present
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'addOAuthApp' });
}
if (!(await hasPermissionAsync(uid, 'manage-oauth-apps'))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'addOAuthApp' });
}
if (!applicationParams.name || typeof applicationParams.name.valueOf() !== 'string' || applicationParams.name.trim() === '') {
throw new Meteor.Error('error-invalid-name', 'Invalid name', { method: 'addOAuthApp' });
}
if (
!applicationParams.redirectUri ||
typeof applicationParams.redirectUri.valueOf() !== 'string' ||
applicationParams.redirectUri.trim() === ''
) {
throw new Meteor.Error('error-invalid-redirectUri', 'Invalid redirectUri', {
method: 'addOAuthApp',
});
}
if (typeof applicationParams.active !== 'boolean') {
throw new Meteor.Error('error-invalid-arguments', 'Invalid arguments', {
method: 'addOAuthApp',
});
}
const application = {
...applicationParams,
redirectUri: parseUriList(applicationParams.redirectUri),
clientId: Random.id(),
clientSecret: Random.secret(),
_createdAt: new Date(),
_updatedAt: new Date(),
_createdBy: {
_id: user._id,
username: user.username,
},
};
if (application.redirectUri.length === 0) {
throw new Meteor.Error('error-invalid-redirectUri', 'Invalid redirectUri', {
method: 'addOAuthApp',
});
}
return {
...application,
_id: (await OAuthApps.insertOne(application)).insertedId,
};
}