updated codegen, fixed tsconfig, added prisma

added login, registration and session check
This commit is contained in:
lnn0q 2025-03-23 21:06:15 +02:00
parent 9518787206
commit 04b606b7fa
24 changed files with 740 additions and 1747 deletions

View file

@ -1,25 +1,44 @@
import { prisma } from '@app/server/prisma/client';
import { MutationLoginArgs, Session } from '@generated/types';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
const usersDB = {
users: require('../model/users.json'),
setUsers: function (data) {
this.users = data;
}
};
export async function LoginResolver(_: any, { input }: MutationLoginArgs): Promise<Session> {
const error = 'Invalid username or password';
const handleLogin = async (req, res) => {
const { user, pwd } = req.body;
if (!user || !pwd) res.status(400).json({ message: 'Username and password are required.' });
const foundUser = usersDB.users.find(person => person.username === user);
if (!foundUser) return res.sendStatus(401); // unauthorized
// evaluate password
const match = await bcrypt.compare(pwd, foundUser.password);
if (match) {
// create JWTs
res.json({ success: `User ${user} is logged in.` });
} else {
res.sendStatus(401);
}
};
const user = await prisma.user.findUnique({
where: { email: input.email }
});
if (!user) throw new Error(error);
module.exports = { handleLogin };
const match = await bcrypt.compare(input.password, user.password);
if (!match) throw new Error(error);
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET;
const refreshTokenSecret = process.env.REFRESH_TOKEN_SECRET;
if (accessTokenSecret == null || refreshTokenSecret == null) throw new Error('No secrets found');
const accessToken = jwt.sign({ userId: user.id }, accessTokenSecret, {
expiresIn: '30s'
});
const refreshToken = jwt.sign({ userId: user.id }, refreshTokenSecret, {
expiresIn: '1d'
});
await prisma.user.update({
where: { id: user.id },
data: { refreshToken }
});
return {
accessToken,
refreshToken: {
token: refreshToken,
httpOnly: true,
secure: true,
maxAge: 24 * 60 * 60 * 1000,
sameSite: 'None'
}
};
}