2018-04-12 15:06:18 -06:00
|
|
|
import * as Koa from 'koa';
|
|
|
|
|
2018-04-01 22:15:53 -06:00
|
|
|
import config from '../../../config';
|
2019-04-07 06:50:36 -06:00
|
|
|
import { ILocalUser } from '../../../models/entities/user';
|
2019-07-17 13:22:44 -06:00
|
|
|
import { Signins } from '../../../models';
|
|
|
|
import { genId } from '../../../misc/gen-id';
|
|
|
|
import { publishMainStream } from '../../../services/stream';
|
2017-11-22 21:25:33 -07:00
|
|
|
|
2019-01-22 05:42:05 -07:00
|
|
|
export default function(ctx: Koa.BaseContext, user: ILocalUser, redirect = false) {
|
2017-11-22 21:25:33 -07:00
|
|
|
if (redirect) {
|
2018-11-27 13:27:34 -07:00
|
|
|
//#region Cookie
|
|
|
|
const expires = 1000 * 60 * 60 * 24 * 365; // One Year
|
|
|
|
ctx.cookies.set('i', user.token, {
|
|
|
|
path: '/',
|
|
|
|
domain: config.hostname,
|
|
|
|
// 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,
|
|
|
|
expires: new Date(Date.now() + expires),
|
|
|
|
maxAge: expires
|
|
|
|
});
|
|
|
|
//#endregion
|
|
|
|
|
2018-04-12 15:06:18 -06:00
|
|
|
ctx.redirect(config.url);
|
2018-04-12 20:44:39 -06:00
|
|
|
} else {
|
2018-11-28 00:19:02 -07:00
|
|
|
ctx.body = { i: user.token };
|
|
|
|
ctx.status = 200;
|
2017-11-22 21:25:33 -07:00
|
|
|
}
|
2019-07-17 13:22:44 -06: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-22 21:25:33 -07:00
|
|
|
}
|