46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
import { IdentityContext } from '@app/server/identity';
|
|
import { prisma } from '@app/server/prisma/client';
|
|
import { MutationLoginArgs, Session } from '@generated/types';
|
|
import bcrypt from 'bcrypt';
|
|
import jwt from 'jsonwebtoken';
|
|
import { config } from '@app/server/main';
|
|
|
|
export async function LoginResolver(
|
|
_: any,
|
|
{ input }: MutationLoginArgs,
|
|
{ req, res, identity }: IdentityContext
|
|
): Promise<Session> {
|
|
const error = 'Invalid password or email';
|
|
|
|
const user = await prisma.user.findUnique({
|
|
where: { email: input.email }
|
|
});
|
|
if (user == null) throw new Error(error);
|
|
|
|
const match = await bcrypt.compare(input.password, user.password);
|
|
if (!match) throw new Error(error);
|
|
|
|
const accessToken = jwt.sign({ userId: user.id }, config.accessToken.secret, {
|
|
expiresIn: config.accessToken.expiresIn
|
|
});
|
|
const refreshToken = jwt.sign({ userId: user.id }, config.refreshToken.secret, {
|
|
expiresIn: config.refreshToken.expiresIn
|
|
});
|
|
|
|
await prisma.user.update({
|
|
where: { id: user.id },
|
|
data: { refreshToken }
|
|
});
|
|
|
|
res.cookie('jwt', refreshToken, {
|
|
httpOnly: true,
|
|
sameSite: 'none',
|
|
secure: true,
|
|
maxAge: config.refreshToken.maxAge
|
|
});
|
|
|
|
return {
|
|
userId: user.id,
|
|
accessToken
|
|
};
|
|
}
|