Sharkey/packages/backend/src/server/api/SigninService.ts

52 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-09-17 21:27:08 +03:00
import { Inject, Injectable } from '@nestjs/common';
import { DI } from '@/di-symbols.js';
import type { SigninsRepository, UsersRepository } from '@/models/index.js';
2022-09-20 23:33:11 +03:00
import type { Config } from '@/config.js';
2022-09-17 21:27:08 +03:00
import { IdService } from '@/core/IdService.js';
2023-02-13 08:50:22 +02:00
import type { LocalUser } from '@/models/entities/User.js';
2022-09-17 21:27:08 +03:00
import { GlobalEventService } from '@/core/GlobalEventService.js';
import { SigninEntityService } from '@/core/entities/SigninEntityService.js';
import { bindThis } from '@/decorators.js';
import type { FastifyRequest, FastifyReply } from 'fastify';
2022-09-17 21:27:08 +03: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,
) {
}
@bindThis
2023-02-13 08:50:22 +02:00
public signin(request: FastifyRequest, reply: FastifyReply, user: LocalUser) {
setImmediate(async () => {
// Append signin history
const record = await this.signinsRepository.insert({
id: this.idService.genId(),
createdAt: new Date(),
userId: user.id,
ip: request.ip,
2023-02-09 03:46:01 +02:00
headers: request.headers as any,
success: true,
}).then(x => this.signinsRepository.findOneByOrFail(x.identifiers[0]));
// Publish signin event
this.globalEventService.publishMainStream(user.id, 'signin', await this.signinEntityService.pack(record));
});
2023-02-09 03:47:03 +02:00
reply.code(200);
return {
id: user.id,
i: user.token,
};
2022-09-17 21:27:08 +03:00
}
}