iceshrimp-legacy/packages/backend/src/server/api/common/signin.ts

45 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-01-13 05:40:33 +01:00
import type Koa from "koa";
2018-04-12 23:06:18 +02:00
2023-01-13 05:40:33 +01:00
import config from "@/config/index.js";
import type { 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 05:25:33 +01:00
2023-01-13 05:40:33 +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
2023-01-13 05:40:33 +01:00
ctx.cookies.set("igi", user.token!, {
path: "/",
2018-11-27 21:27:34 +01:00
// 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
2023-01-13 05:40:33 +01:00
secure: config.url.startsWith("https"),
2021-12-09 15:58:30 +01:00
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,
2021-12-09 15:58:30 +01:00
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.insert({
id: genId(),
createdAt: new Date(),
userId: user.id,
ip: ctx.ip,
headers: ctx.headers,
2021-12-09 15:58:30 +01:00
success: true,
2023-01-13 05:40:33 +01:00
}).then((x) => Signins.findOneByOrFail(x.identifiers[0]));
// Publish signin event
2023-01-13 05:40:33 +01:00
publishMainStream(user.id, "signin", await Signins.pack(record));
})();
2017-11-23 05:25:33 +01:00
}