89 lines
3.0 KiB
TypeScript
89 lines
3.0 KiB
TypeScript
import { FastifyInstance } from 'fastify';
|
|
import { FromSchema } from 'json-schema-to-ts';
|
|
import { stringify } from 'querystring';
|
|
import axios from 'axios';
|
|
|
|
const schema = {
|
|
querystring: {
|
|
type: 'object',
|
|
required: ['code', 'session'],
|
|
properties: {
|
|
code: { type: 'string' },
|
|
session: { type: 'string' }
|
|
}
|
|
}
|
|
} as const;
|
|
|
|
export default async (server: FastifyInstance) =>
|
|
server.get<{ Querystring: FromSchema<typeof schema.querystring> }>(
|
|
'/verify',
|
|
{ schema },
|
|
(req, reply) => {
|
|
axios
|
|
.post(
|
|
'https://auth.m0e.space/application/o/token/',
|
|
stringify({
|
|
client_id: process.env.AUTH_CLIENT_ID,
|
|
client_secret: process.env.AUTH_CLIENT_SECRET,
|
|
grant_type: 'authorization_code',
|
|
redirect_uri:
|
|
process.env.NODE_ENV === 'production'
|
|
? 'https://mc.m0e.space/api/auth/verify'
|
|
: 'http://localhost:8080/api/auth/verify',
|
|
code: req.query.code
|
|
})
|
|
)
|
|
.then(res =>
|
|
axios
|
|
.get('https://auth.m0e.space/application/o/userinfo/', {
|
|
headers: { Authorization: `Bearer ${res.data.access_token}` }
|
|
})
|
|
.then(async res => {
|
|
const user =
|
|
(await server.db.user.findFirst({ where: { id: res.data.sub } })) ||
|
|
(await server.db.user.create({ data: { id: res.data.sub } }));
|
|
const session = await server.db.session.findFirst({
|
|
where: { id: req.query.session }
|
|
});
|
|
if (!session) return reply.code(400).send('Invalid session');
|
|
const userByNickname = await server.db.user.findFirst({
|
|
where: { nickname: session.nickname }
|
|
});
|
|
if (!userByNickname) {
|
|
await Promise.all([
|
|
server.db.user.update({
|
|
where: { id: user.id },
|
|
data: { nickname: session.nickname }
|
|
}),
|
|
server.db.session.update({
|
|
where: { id: req.query.session },
|
|
data: {
|
|
verified: true
|
|
}
|
|
})
|
|
]).then(() => reply.redirect('https://mc.m0e.space/message/success'));
|
|
|
|
// await server.redis.publish('rpz_auth', req.query.session);
|
|
} else if (userByNickname.id !== user.id) reply.send(403).send('Forbidden');
|
|
else
|
|
await server.db.session
|
|
.update({
|
|
where: { id: req.query.session },
|
|
data: {
|
|
verified: true
|
|
}
|
|
})
|
|
.then(() => reply.redirect('https://mc.m0e.space/message/success'));
|
|
})
|
|
.catch(err => {
|
|
console.log(err);
|
|
reply.code(500).send(err);
|
|
})
|
|
)
|
|
.catch(err => {
|
|
console.log(err);
|
|
reply.code(500).send(err);
|
|
});
|
|
}
|
|
);
|