minecraft-docker/backend/src/routes/auth/register.ts

61 lines
1.6 KiB
TypeScript

import { FromSchema } from 'json-schema-to-ts';
import { FastifyInstance } from 'fastify';
import { pbkdf2 } from 'node:crypto';
import { promisify } from 'node:util';
const schema = {
body: {
type: 'object',
required: ['username', 'password', 'key'],
properties: {
username: { type: 'string' },
password: { type: 'string' },
key: { type: 'string' }
}
}
} as const;
export default async (server: FastifyInstance) =>
server.post<{ Body: FromSchema<typeof schema.body> }>(
'/register',
{ schema },
async (req, reply) => {
if (req.body.key !== process.env.AUTH_SECRET)
return reply.code(403).send('Invalid register key');
const currentSeason = (
await server.db.season.findFirst({ where: { current: true }, select: { id: true } })
)?.id;
const pbkdf2Promise = promisify(pbkdf2);
const hash = await pbkdf2Promise(
req.body.password,
process.env.AUTH_SALT,
100000,
64,
'sha512'
);
server.log.info(reply.sent);
await server.db.user
.create({
data: {
nickname: req.body.username,
password: hash.toString('hex'),
accounts: {
create: {
season: {
connect: {
id: currentSeason
}
}
}
}
}
})
.then(user => reply.sendTokens(user))
.catch(err => {
if (err.code === 'P2002') reply.code(400).send('User is already exists');
reply.sendError(err);
});
}
);