Implement safe crypto

This commit is contained in:
nocnico
2025-04-28 20:22:39 +02:00
parent b5e96e02c3
commit 0fa4e1107b
5 changed files with 33 additions and 42 deletions

View File

@@ -1,5 +1,4 @@
"use server";
import { PrismaClient } from "@prisma/client";
import { prisma, Prisma } from "@repo/db";
import bcrypt from "bcryptjs";
import { sendMailByTemplate } from "../../../../helper/mail";
@@ -14,7 +13,11 @@ export const editUser = async (id: string, data: Prisma.UserUpdateInput) => {
};
export const resetPassword = async (id: string) => {
const password = Math.random().toString(36).slice(-8);
const array = new Uint8Array(8);
crypto.getRandomValues(array);
const password = Array.from(array, (byte) =>
("0" + (byte % 36).toString(36)).slice(-1),
).join("");
const hashedPassword = await bcrypt.hash(password, 12);
const user = await prisma.user.update({

View File

@@ -1,24 +1,30 @@
'use server';
import { getServerSession } from '../../../api/auth/[...nextauth]/auth';
import { Service } from '../page';
import { PrismaClient } from '@repo/db';
"use server";
import { getServerSession } from "../../../api/auth/[...nextauth]/auth";
import { Service } from "../page";
import { PrismaClient } from "@repo/db";
const prisma = new PrismaClient();
export const generateToken = async (service: Service) => {
const session = await getServerSession();
if (!session) return null;
const session = await getServerSession();
if (!session) return null;
const accessToken = Array.from({ length: 10 }, () =>
Math.floor(Math.random() * 10)
).join('');
const key = await crypto.subtle.generateKey(
{ name: "HMAC", hash: "SHA-256" },
true,
["sign"],
);
const exportedKey = await crypto.subtle.exportKey("raw", key);
const accessToken = Array.from(new Uint8Array(exportedKey))
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
const code = await prisma.oAuthToken.create({
data: {
clientId: service.id,
userId: session.user.id,
accessToken: accessToken,
},
});
return code;
const code = await prisma.oAuthToken.create({
data: {
clientId: service.id,
userId: session.user.id,
accessToken: accessToken,
},
});
return code;
};

View File

@@ -16,7 +16,11 @@ export const resetPassword = async (email: string) => {
return { error: "Nutzer nicht gefunden" };
}
const password = Math.random().toString(36).slice(-8);
const array = new Uint8Array(8);
crypto.getRandomValues(array);
const password = Array.from(array, (byte) =>
("0" + (byte % 36).toString(36)).slice(-1),
).join("");
const hashedPassword = await bcrypt.hash(password, 12);
await prisma.user.update({
where: {