hippofish/packages/backend/src/server/api/common/signin.ts

45 lines
1.1 KiB
TypeScript
Raw Normal View History

2018-04-12 23:06:18 +02:00
import * as Koa from 'koa';
import config from '@/config/index';
import { ILocalUser } from '@/models/entities/user';
import { Signins } from '@/models/index';
import { genId } from '@/misc/gen-id';
import { publishMainStream } from '@/services/stream';
2017-11-23 05:25:33 +01:00
2019-11-24 09:09:32 +01:00
export default function(ctx: Koa.Context, user: ILocalUser, redirect = false) {
2017-11-23 05:25:33 +01:00
if (redirect) {
2018-11-27 21:27:34 +01:00
//#region Cookie
ctx.cookies.set('igi', user.token, {
2018-11-27 21:27:34 +01: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 21:27:34 +01:00
});
//#endregion
2018-04-12 23:06:18 +02:00
ctx.redirect(config.url);
2018-04-13 04:44:39 +02:00
} else {
ctx.body = {
id: user.id,
i: user.token
};
2018-11-28 08:19:02 +01:00
ctx.status = 200;
2017-11-23 05:25:33 +01: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 05:25:33 +01:00
}