2022-09-17 18:27:08 +00:00
|
|
|
import { Inject, Injectable } from '@nestjs/common';
|
|
|
|
import { DI } from '@/di-symbols.js';
|
2022-12-03 10:42:05 +00:00
|
|
|
import type { SigninsRepository, UsersRepository } from '@/models/index.js';
|
2022-09-20 20:33:11 +00:00
|
|
|
import type { Config } from '@/config.js';
|
2022-09-17 18:27:08 +00:00
|
|
|
import { IdService } from '@/core/IdService.js';
|
|
|
|
import type { ILocalUser } from '@/models/entities/User.js';
|
|
|
|
import { GlobalEventService } from '@/core/GlobalEventService.js';
|
|
|
|
import { SigninEntityService } from '@/core/entities/SigninEntityService.js';
|
2022-12-04 06:03:09 +00:00
|
|
|
import { bindThis } from '@/decorators.js';
|
2022-12-13 15:01:45 +00:00
|
|
|
import type { FastifyRequest, FastifyReply } from 'fastify';
|
2022-09-17 18:27:08 +00:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class SigninService {
|
|
|
|
constructor(
|
|
|
|
@Inject(DI.config)
|
|
|
|
private config: Config,
|
|
|
|
|
|
|
|
@Inject(DI.signinsRepository)
|
|
|
|
private signinsRepository: SigninsRepository,
|
|
|
|
|
|
|
|
private signinEntityService: SigninEntityService,
|
|
|
|
private idService: IdService,
|
|
|
|
private globalEventService: GlobalEventService,
|
|
|
|
) {
|
|
|
|
}
|
|
|
|
|
2022-12-04 06:03:09 +00:00
|
|
|
@bindThis
|
2022-12-03 10:42:05 +00:00
|
|
|
public signin(request: FastifyRequest, reply: FastifyReply, user: ILocalUser, redirect = false) {
|
|
|
|
setImmediate(async () => {
|
|
|
|
// Append signin history
|
|
|
|
const record = await this.signinsRepository.insert({
|
|
|
|
id: this.idService.genId(),
|
|
|
|
createdAt: new Date(),
|
|
|
|
userId: user.id,
|
|
|
|
ip: request.ip,
|
|
|
|
headers: request.headers,
|
|
|
|
success: true,
|
|
|
|
}).then(x => this.signinsRepository.findOneByOrFail(x.identifiers[0]));
|
|
|
|
|
|
|
|
// Publish signin event
|
|
|
|
this.globalEventService.publishMainStream(user.id, 'signin', await this.signinEntityService.pack(record));
|
|
|
|
});
|
|
|
|
|
2022-09-17 18:27:08 +00:00
|
|
|
if (redirect) {
|
|
|
|
//#region Cookie
|
2022-12-06 05:14:41 +00:00
|
|
|
reply.setCookie('igi', user.token!, {
|
2022-09-17 18:27:08 +00: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: this.config.url.startsWith('https'),
|
|
|
|
httpOnly: false,
|
|
|
|
});
|
|
|
|
//#endregion
|
|
|
|
|
2022-12-03 10:42:05 +00:00
|
|
|
reply.redirect(this.config.url);
|
2022-09-17 18:27:08 +00:00
|
|
|
} else {
|
2022-12-03 10:42:05 +00:00
|
|
|
reply.code(200);
|
|
|
|
return {
|
2022-09-17 18:27:08 +00:00
|
|
|
id: user.id,
|
|
|
|
i: user.token,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|