Skip to content
Snippets Groups Projects
Commit a7d4584e authored by Caner's avatar Caner
Browse files

ES FUNKTIONIERT

parent f9d6aacb
No related branches found
No related tags found
1 merge request!45Email verify
Pipeline #39246 passed
import { db } from '@/lib/db'
import { randomUUID } from 'crypto';
import { redirect } from 'next/navigation'
import { NextRequest } from 'next/server'
export async function GET(
_request: NextRequest,
{
params,
}: {
params: { token: string }
}
) {
const { token } = params
const user = await db.user.findFirst({
where: {
ActivationToken: {
some: {
AND: [
{
activationDate: null,
},
{
createdAt: {
gt: new Date(Date.now() - 24 * 60 * 60 * 1000), // 24 hours ago
},
},
{
token
},
],
},
},
},
})
if (!user) {
throw new Error('Token is invalid or expired')
}
await db.user.update({
where: {
id: user.id,
},
data: {
emailVerified: true,
},
})
await db.activationToken.update({
where: {
token,
},
data: {
activationDate: new Date(),
},
})
redirect('/login')
}
\ No newline at end of file
import nodemailer from "nodemailer"; import nodemailer from "nodemailer";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { randomUUID } from "crypto";
import getURL from "@/lib/utils";
export async function POST(req: Request) { export async function POST(req: Request) {
const { email, subject, html } = await req.json(); const { email} = await req.json();
const transporter = nodemailer.createTransport({ const transporter = nodemailer.createTransport({
service: 'gmail', service: 'gmail',
host: 'smtp.gmail.com', host: 'smtp.gmail.com',
...@@ -12,26 +15,38 @@ export async function POST(req: Request) { ...@@ -12,26 +15,38 @@ export async function POST(req: Request) {
pass: process.env.NODEMAIL_PW, pass: process.env.NODEMAIL_PW,
}, },
}); });
const user = await db.user.findFirst({
where: {
email: email
}
});
const token = await db.activationToken.create({
data: {
token: `${randomUUID()}${randomUUID()}`.replace(/-/g, ''),
userId: user?.id!
},
});
const mailData = { const mailData = {
from: email, from: process.env.NODEMAIL_MAIL,
to: email, to: email,
subject: `${subject}`, subject: ` 'Email Verification for your GameUnity Account'`,
text: `${subject} | Sent from: ${email}`, html: `Hello ${user?.name} Please follow the Link: ${getURL(`/api/verification/${token.token}`)} and verify your email address.`,
html: `${html}`,
}; };
let emailRes; let emailRes;
try { try {
emailRes = await transporter.sendMail(mailData); emailRes = await transporter.sendMail(mailData);
console.log("Message sent", emailRes.messageId); console.log("Message sent", emailRes.messageId);
} catch (err) { } catch (err) {
console.log(err); console.log(err);
console.error("Error email could not be send"); console.error("Error email could not be send");
} }
console.log(emailRes?.messageId) console.log(emailRes?.messageId)
return NextResponse.json({ success: true, messageId: emailRes?.messageId }); return NextResponse.json({ success: true, messageId: emailRes?.messageId });
} }
\ No newline at end of file
...@@ -15,6 +15,7 @@ import { ToastAction } from "@/components/ui/toast" ...@@ -15,6 +15,7 @@ import { ToastAction } from "@/components/ui/toast"
import { toast } from "@/components/ui/use-toast" import { toast } from "@/components/ui/use-toast"
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import { userAuthSchema } from "@/lib/validations/auth" import { userAuthSchema } from "@/lib/validations/auth"
import { sendVerificationEmail } from "@/lib/validations/sendVerificationEmail"
interface UserAuthFormProps extends HTMLAttributes<HTMLDivElement> { interface UserAuthFormProps extends HTMLAttributes<HTMLDivElement> {
type: "login" | "signup" type: "login" | "signup"
...@@ -22,6 +23,7 @@ interface UserAuthFormProps extends HTMLAttributes<HTMLDivElement> { ...@@ -22,6 +23,7 @@ interface UserAuthFormProps extends HTMLAttributes<HTMLDivElement> {
type FormData = z.infer<typeof userAuthSchema> type FormData = z.infer<typeof userAuthSchema>
export function UserAuthForm({ type, className, ...props }: UserAuthFormProps) { export function UserAuthForm({ type, className, ...props }: UserAuthFormProps) {
const { const {
register, register,
...@@ -35,36 +37,7 @@ export function UserAuthForm({ type, className, ...props }: UserAuthFormProps) { ...@@ -35,36 +37,7 @@ export function UserAuthForm({ type, className, ...props }: UserAuthFormProps) {
const [isGitHubLoading, setIsGitHubLoading] = useState<boolean>(false) const [isGitHubLoading, setIsGitHubLoading] = useState<boolean>(false)
const router = useRouter(); const router = useRouter();
const searchParams = useSearchParams() const searchParams = useSearchParams()
//muss noch exportiert werden //muss noch exportiert werden
async function sendVerificationEmail(email: string) {
try {
const res = await fetch('/api/email', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email,
subject: 'Email Verification',
html: 'Please verify your email address.',
}),
});
const body = await res.json();
if (res.ok) {
alert(`${body.message} 🚀`);
}
if (res.status === 400) {
alert(`${body.message} 😢`);
}
} catch (err) {
console.log('Something went wrong: ', err);
}
}
async function onSubmit(data: FormData) { async function onSubmit(data: FormData) {
setIsLoading(true) setIsLoading(true)
......
export async function sendVerificationEmail(email: string) {
try {
const res = await fetch('/api/verifyEmail', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email,
}),
});
if (res.ok) {
alert(`Verification Email was send 🚀,/n Please Verify your Account!`);
}
if (res.status === 400) {
alert(`Something went wrong! Verification Email could not be send 😢`);
}
} catch (err) {
console.log('Something went wrong: ', err);
}
}
\ No newline at end of file
...@@ -58,7 +58,7 @@ model User { ...@@ -58,7 +58,7 @@ model User {
name String name String
username String? @unique username String? @unique
email String? @unique email String? @unique
emailVerified DateTime? @map("email_verified") emailVerified Boolean @default(false)
password String? password String?
image String? image String?
banner String? banner String?
...@@ -84,9 +84,23 @@ model User { ...@@ -84,9 +84,23 @@ model User {
following Follows[] @relation("following") following Follows[] @relation("following")
followers Follows[] @relation("follower") followers Follows[] @relation("follower")
ActivationToken ActivationToken[]
@@map("users") @@map("users")
} }
model ActivationToken{
id String @id @default(cuid())
token String @unique
activationDate DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId String
}
model Follows { model Follows {
followerId String followerId String
followingId String followingId String
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment