Sharkey/src/server/api/common/signin.ts

45 lines
1.1 KiB
TypeScript
Raw Normal View History

2018-04-13 00:06:18 +03:00
import * as Koa from 'koa';
import config from '@/config/index.js';
import { ILocalUser } from '@/models/entities/user.js';
import { Signins } from '@/models/index.js';
import { genId } from '@/misc/gen-id.js';
import { publishMainStream } from '@/services/stream.js';
2017-11-23 06:25:33 +02:00
2019-11-24 10:09:32 +02:00
export default function(ctx: Koa.Context, user: ILocalUser, redirect = false) {
2017-11-23 06:25:33 +02:00
if (redirect) {
2018-11-27 22:27:34 +02:00
//#region Cookie
ctx.cookies.set('igi', user.token, {
2018-11-27 22:27:34 +02:00
path: '/',
// SEE: https://github.com/koajs/koa/issues/974
// When using a SSL proxy it should be configured to add the "X-Forwarded-Proto: https" header
secure: config.url.startsWith('https'),
httpOnly: false
2018-11-27 22:27:34 +02:00
});
//#endregion
2018-04-13 00:06:18 +03:00
ctx.redirect(config.url);
2018-04-13 05:44:39 +03:00
} else {
ctx.body = {
id: user.id,
i: user.token
};
2018-11-28 09:19:02 +02:00
ctx.status = 200;
2017-11-23 06:25:33 +02:00
}
(async () => {
// Append signin history
const record = await Signins.save({
id: genId(),
createdAt: new Date(),
userId: user.id,
ip: ctx.ip,
headers: ctx.headers,
success: true
});
// Publish signin event
publishMainStream(user.id, 'signin', await Signins.pack(record));
})();
2017-11-23 06:25:33 +02:00
}