summaryrefslogtreecommitdiff
path: root/src/server/api/authenticate.ts
blob: 6ea5a111bc9fb4705a163bfb21c80c9785ed9e7c (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
import isNativeToken from './common/is-native-token';
import { User } from '../../models/entities/user';
import { Users, AccessTokens, Apps } from '../../models';
import { AccessToken } from '../../models/entities/access-token';
import { Cache } from '@/misc/cache';

// TODO: TypeORMのカスタムキャッシュプロバイダを使っても良いかも
// ref. https://github.com/typeorm/typeorm/blob/master/docs/caching.md
const cache = new Cache<User>(1000 * 60 * 60);

export default async (token: string): Promise<[User | null | undefined, AccessToken | null | undefined]> => {
	if (token == null) {
		return [null, null];
	}

	if (isNativeToken(token)) {
		const cached = cache.get(token);
		if (cached) {
			return [cached, null];
		}

		// Fetch user
		const user = await Users
			.findOne({ token });

		if (user == null) {
			throw new Error('user not found');
		}

		cache.set(token, user);

		return [user, null];
	} else {
		// TODO: cache
		const accessToken = await AccessTokens.findOne({
			where: [{
				hash: token.toLowerCase() // app
			}, {
				token: token // miauth
			}],
		});

		if (accessToken == null) {
			throw new Error('invalid signature');
		}

		AccessTokens.update(accessToken.id, {
			lastUsedAt: new Date(),
		});

		const user = await Users
			.findOne({
				id: accessToken.userId // findOne(accessToken.userId) のように書かないのは後方互換性のため
			});

		if (accessToken.appId) {
			const app = await Apps
				.findOneOrFail(accessToken.appId);

			return [user, {
				id: accessToken.id,
				permission: app.permission
			} as AccessToken];
		} else {
			return [user, accessToken];
		}
	}
};