summaryrefslogtreecommitdiff
path: root/src/server/api/endpoints/auth/session/generate.ts
blob: ca004e9b197cc5148134fc7ca649499aa6e8257e (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
import { v4 as uuid } from 'uuid';
import $ from 'cafy';
import config from '@/config';
import define from '../../../define';
import { ApiError } from '../../../error';
import { Apps, AuthSessions } from '../../../../../models';
import { genId } from '@/misc/gen-id';

export const meta = {
	tags: ['auth'],

	requireCredential: false as const,

	params: {
		appSecret: {
			validator: $.str,
		}
	},

	res: {
		type: 'object' as const,
		optional: false as const, nullable: false as const,
		properties: {
			token: {
				type: 'string' as const,
				optional: false as const, nullable: false as const,
				description: 'セッションのトークン'
			},
			url: {
				type: 'string' as const,
				optional: false as const, nullable: false as const,
				format: 'url',
				description: 'セッションのURL'
			},
		}
	},

	errors: {
		noSuchApp: {
			message: 'No such app.',
			code: 'NO_SUCH_APP',
			id: '92f93e63-428e-4f2f-a5a4-39e1407fe998'
		}
	}
};

export default define(meta, async (ps) => {
	// Lookup app
	const app = await Apps.findOne({
		secret: ps.appSecret
	});

	if (app == null) {
		throw new ApiError(meta.errors.noSuchApp);
	}

	// Generate token
	const token = uuid();

	// Create session token document
	const doc = await AuthSessions.save({
		id: genId(),
		createdAt: new Date(),
		appId: app.id,
		token: token
	});

	return {
		token: doc.token,
		url: `${config.authUrl}/${doc.token}`
	};
});