Sharkey/packages/backend/src/server/api/endpoints/miauth/gen-token.ts

74 lines
1.3 KiB
TypeScript
Raw Normal View History

2020-03-28 04:24:37 +02:00
import $ from 'cafy';
import define from '../../define';
import { AccessTokens } from '@/models/index';
import { genId } from '@/misc/gen-id';
import { secureRndstr } from '@/misc/secure-rndstr';
2020-03-28 04:24:37 +02:00
export const meta = {
tags: ['auth'],
requireCredential: true as const,
secure: true,
params: {
session: {
2021-12-09 16:58:30 +02:00
validator: $.nullable.str,
2020-03-28 04:24:37 +02:00
},
name: {
2021-12-09 16:58:30 +02:00
validator: $.nullable.optional.str,
2020-03-28 04:24:37 +02:00
},
description: {
validator: $.nullable.optional.str,
},
iconUrl: {
validator: $.nullable.optional.str,
},
permission: {
validator: $.arr($.str).unique(),
},
},
res: {
type: 'object' as const,
optional: false as const, nullable: false as const,
properties: {
token: {
type: 'string' as const,
2021-12-09 16:58:30 +02:00
optional: false as const, nullable: false as const,
},
},
},
2020-03-28 04:24:37 +02:00
};
2022-01-02 19:12:50 +02:00
// eslint-disable-next-line import/no-default-export
2020-03-28 04:24:37 +02:00
export default define(meta, async (ps, user) => {
// Generate access token
const accessToken = secureRndstr(32, true);
2020-03-28 04:24:37 +02:00
const now = new Date();
2020-03-28 04:24:37 +02:00
// Insert access token doc
2021-03-21 14:27:09 +02:00
await AccessTokens.insert({
2020-03-28 04:24:37 +02:00
id: genId(),
createdAt: now,
lastUsedAt: now,
2020-03-28 04:24:37 +02:00
session: ps.session,
userId: user.id,
token: accessToken,
hash: accessToken,
name: ps.name,
description: ps.description,
iconUrl: ps.iconUrl,
permission: ps.permission,
});
2020-07-18 06:12:10 +03:00
return {
2021-12-09 16:58:30 +02:00
token: accessToken,
2020-07-18 06:12:10 +03:00
};
2020-03-28 04:24:37 +02:00
});