Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 29 additions & 30 deletions src/actions/email/sendInvite.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
'use server';
'use server'

import sgMail from '@sendgrid/mail';
import sgMail from '@sendgrid/mail'

import { prisma } from '@/prisma/client'


export interface User {
firstName: string
lastName: string
Expand All @@ -15,17 +14,17 @@ const getPatientName = async (id: string): Promise<User | null> => {
where: { id },
select: {
firstName: true,
lastName: true,
lastName: true
}
})
}

sgMail.setApiKey(process.env.SENDGRID_API_KEY!);
sgMail.setApiKey(process.env.SENDGRID_API_KEY!)

// Send invite email after login (with uid)
export async function sendInviteEmail(name: string, email: string, patientId: string) {
const patient = await getPatientName(patientId);
const patientName = patient ? `${patient.firstName} ${patient.lastName}` : '';
const patient = await getPatientName(patientId)
const patientName = patient ? `${patient.firstName} ${patient.lastName}` : ''

try {
const msg = {
Expand All @@ -36,45 +35,45 @@ export async function sendInviteEmail(name: string, email: string, patientId: st
<p>Dear ${name},</p>
<p>Your patient ${patientName} would like to share their symptoms data with you on our platform. </p>
<p>Register your account to view their spidergrams and track their data.</p>
<p>Here is a link to our website: https://team3docker.uksouth.cloudapp.azure.com/register</p>
<p>Here is a link to our website: ${process.env.NEXT_PUBLIC_APP_URL}/register</p>
<p>Kind regards,</p>
<p>The Spider team</p>
`,
};
`
}

await sgMail.send(msg)

await sgMail.send(msg);

return { success: true };
return { success: true }
} catch (error: any) {
console.error('[Invite Email Error]', error);
return { success: false, error: error.message };
console.error('[Invite Email Error]', error)

return { success: false, error: error.message }
}
}

// Send invite email before login (without uid)
export async function sendInviteEmailDuringRegistration(clinicianName: string, email: string) {
try {
const msg = {
to: email,
from: process.env.SENDGRID_SENDER_EMAIL!,
subject: 'You\'ve been invited to join our platform!',
html: `
const msg = {
to: email,
from: process.env.SENDGRID_SENDER_EMAIL!,
subject: "You've been invited to join our platform!",
html: `
<p>Dear ${clinicianName},</p>
<p>A new patient would like to share their symptoms data with you on our platform.</p>
<p>Register your account to view their spidergrams and track their data.</p>
<p>Here is a link to our website: https://team3.uksouth.cloudapp.azure.com</p>
<p>Kind regards,</p>
<p>The Spider team</p>
`,
};
await sgMail.send(msg);
return { success: true };
`
}

await sgMail.send(msg)

return { success: true }
} catch (error: any) {
console.error('[Invite Email Error]', error);
return { success: false, error: error.message };
console.error('[Invite Email Error]', error)

return { success: false, error: error.message }
}
}
96 changes: 45 additions & 51 deletions src/actions/email/sendReset.ts
Original file line number Diff line number Diff line change
@@ -1,118 +1,112 @@
'use server';
'use server'

import crypto from 'crypto';
import crypto from 'crypto'

import sgMail from '@sendgrid/mail';
import sgMail from '@sendgrid/mail'

import bcrypt from 'bcryptjs'

import bcrypt from 'bcryptjs';

import { prisma } from '@/prisma/client';



sgMail.setApiKey(process.env.SENDGRID_API_KEY!);
import { prisma } from '@/prisma/client'

sgMail.setApiKey(process.env.SENDGRID_API_KEY!)

export async function sendPasswordReset(email: string) {
try {
console.log('Checking for user with email:', email);
console.log('Checking for user with email:', email)

const user = await prisma.user.findUnique({ where: { email } });
const user = await prisma.user.findUnique({ where: { email } })

if (!user) {
console.warn('No user found with that email.');
console.warn('No user found with that email.')

return { success: false, error: 'No user found with that email.' };
return { success: false, error: 'No user found with that email.' }
}

const token = crypto.randomBytes(32).toString('hex');
const hashedToken = crypto.createHash('sha256').update(token).digest('hex');
const token = crypto.randomBytes(32).toString('hex')
const hashedToken = crypto.createHash('sha256').update(token).digest('hex')

try {
await prisma.user.update({
where: { email },
data: {
passwordResetToken: hashedToken,
passwordResetExpires: new Date(Date.now() + 1000 * 60 * 15),
},
});

passwordResetExpires: new Date(Date.now() + 1000 * 60 * 15)
}
})
} catch (updateError: any) {
console.error('Prisma update failed:', updateError);
return { success: false, error: 'Failed to update user in database.' };
console.error('Prisma update failed:', updateError)

return { success: false, error: 'Failed to update user in database.' }
}

const resetLink = `https://team3docker.uksouth.cloudapp.azure.com//reset-password/${token}`;
const resetLink = `${process.env.NEXT_PUBLIC_APP_URL}//reset-password/${token}`

const msg = {
to: email,
from: process.env.SENDGRID_SENDER_EMAIL!,
subject: 'Reset Your Password',
html: `<p>Click <a href="${resetLink}">here</a> to reset your password. This link is valid for 15 minutes.</p>`,
};
html: `<p>Click <a href="${resetLink}">here</a> to reset your password. This link is valid for 15 minutes.</p>`
}

await sgMail.send(msg);
return { success: true };
await sgMail.send(msg)

return { success: true }
} catch (error: any) {
console.error('Error in sendPasswordReset:', error);
return { success: false, error: error.message };
console.error('Error in sendPasswordReset:', error)

return { success: false, error: error.message }
}
}

export async function checkValidityToken(token: string) {
// Hash the token
const hashedToken = crypto.createHash('sha256').update(token).digest('hex');
const hashedToken = crypto.createHash('sha256').update(token).digest('hex')

const user = await prisma.user.findFirst({
where: { passwordResetToken: hashedToken },
select: { passwordResetExpires: true }
});

})

// Check if the user exists and if the token has expired
if (!user || !user.passwordResetExpires) {
throw new Error('Invalid or expired token');
throw new Error('Invalid or expired token')
}

// Compare expiration date with current time
const currentTime = new Date().toISOString();
const expirationTime = user.passwordResetExpires.toISOString();
const currentTime = new Date().toISOString()
const expirationTime = user.passwordResetExpires.toISOString()

if (currentTime > expirationTime) {
throw new Error('Token has expired');
throw new Error('Token has expired')
}

// If token is still valid, return true or user object
return true;
return true
}

export async function handleResetPassword(token: string, newPassword: string) {
const hashedToken = crypto.createHash('sha256').update(token).digest('hex');
const hashedToken = crypto.createHash('sha256').update(token).digest('hex')

const user = await prisma.user.findFirst({
where: {
passwordResetToken: hashedToken,
},
});
passwordResetToken: hashedToken
}
})

if (!user) {
return { success: false, error: 'Invalid or expired token.' };
return { success: false, error: 'Invalid or expired token.' }
}

const hashedPassword = await bcrypt.hash(newPassword, 10);
const hashedPassword = await bcrypt.hash(newPassword, 10)

await prisma.user.update({
where: { id: user.id },
data: {
hashedPassword,
passwordResetToken: null,
passwordResetExpires: null,
},
});
passwordResetExpires: null
}
})

return { success: true };
return { success: true }
}