-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Username validation refactor #1569
Merged
Merged
Changes from 7 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
ebf8365
Username validation in router. Validation refactor
infomiho def5853
Extract email utils into a separate file
infomiho 1e63194
Inline isEmailValid validator
infomiho 5c10b37
Split signup and login validation
infomiho 103d37a
Updates e2e tests
infomiho 9f86f78
Updates exports
infomiho 9e30f93
Updates docs and changelog
infomiho 9c85786
Cleanup
infomiho a9fb3e3
Custom sign-up docs
infomiho 625ee68
Cleanup docs
infomiho c4c9c6c
Docs cleanup
infomiho 0058e0a
Updates docs
infomiho File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
8 changes: 5 additions & 3 deletions
8
waspc/data/Generator/templates/server/src/auth/providers/email/requestPasswordReset.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
100 changes: 100 additions & 0 deletions
100
waspc/data/Generator/templates/server/src/auth/providers/email/utils.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
{{={= =}=}} | ||
import { sign } from '../../../core/auth.js' | ||
import { emailSender } from '../../../email/index.js'; | ||
import { Email } from '../../../email/core/types.js'; | ||
import { rethrowPossiblePrismaError } from '../../utils.js' | ||
import prisma from '../../../dbClient.js' | ||
import waspServerConfig from '../../../config.js'; | ||
import { type {= userEntityUpper =} } from '../../../entities/index.js' | ||
|
||
|
||
type {= userEntityUpper =}Id = {= userEntityUpper =}['id'] | ||
|
||
export async function updateUserEmailVerification(userId: {= userEntityUpper =}Id): Promise<void> { | ||
try { | ||
await prisma.{= userEntityLower =}.update({ | ||
where: { id: userId }, | ||
data: { isEmailVerified: true }, | ||
}) | ||
} catch (e) { | ||
rethrowPossiblePrismaError(e); | ||
} | ||
} | ||
|
||
export async function updateUserPassword(userId: {= userEntityUpper =}Id, password: string): Promise<void> { | ||
try { | ||
await prisma.{= userEntityLower =}.update({ | ||
where: { id: userId }, | ||
data: { password }, | ||
}) | ||
} catch (e) { | ||
rethrowPossiblePrismaError(e); | ||
} | ||
} | ||
|
||
export async function createEmailVerificationLink(user: {= userEntityUpper =}, clientRoute: string): Promise<string> { | ||
const token = await createEmailVerificationToken(user); | ||
return `${waspServerConfig.frontendUrl}${clientRoute}?token=${token}`; | ||
} | ||
|
||
export async function createPasswordResetLink(user: {= userEntityUpper =}, clientRoute: string): Promise<string> { | ||
const token = await createPasswordResetToken(user); | ||
return `${waspServerConfig.frontendUrl}${clientRoute}?token=${token}`; | ||
} | ||
|
||
async function createEmailVerificationToken(user: {= userEntityUpper =}): Promise<string> { | ||
return sign(user.id, { expiresIn: '30m' }); | ||
} | ||
|
||
async function createPasswordResetToken(user: {= userEntityUpper =}): Promise<string> { | ||
return sign(user.id, { expiresIn: '30m' }); | ||
} | ||
|
||
export async function sendPasswordResetEmail( | ||
email: string, | ||
content: Email, | ||
): Promise<void> { | ||
return sendEmailAndLogTimestamp(email, content, 'passwordResetSentAt'); | ||
} | ||
|
||
export async function sendEmailVerificationEmail( | ||
email: string, | ||
content: Email, | ||
): Promise<void> { | ||
return sendEmailAndLogTimestamp(email, content, 'emailVerificationSentAt'); | ||
} | ||
|
||
async function sendEmailAndLogTimestamp( | ||
email: string, | ||
content: Email, | ||
field: 'emailVerificationSentAt' | 'passwordResetSentAt', | ||
): Promise<void> { | ||
// Set the timestamp first, and then send the email | ||
// so the user can't send multiple requests while | ||
// the email is being sent. | ||
try { | ||
await prisma.{= userEntityLower =}.update({ | ||
where: { email }, | ||
data: { [field]: new Date() }, | ||
}) | ||
} catch (e) { | ||
rethrowPossiblePrismaError(e); | ||
} | ||
emailSender.send(content).catch((e) => { | ||
console.error(`Failed to send email for ${field}`, e); | ||
}); | ||
} | ||
|
||
export function isEmailResendAllowed( | ||
user: {= userEntityUpper =}, | ||
field: 'emailVerificationSentAt' | 'passwordResetSentAt', | ||
resendInterval: number = 1000 * 60, | ||
): boolean { | ||
const sentAt = user[field]; | ||
if (!sentAt) { | ||
return true; | ||
} | ||
const now = new Date(); | ||
const diff = now.getTime() - sentAt.getTime(); | ||
return diff > resendInterval; | ||
} |
3 changes: 2 additions & 1 deletion
3
waspc/data/Generator/templates/server/src/auth/providers/email/verifyEmail.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,17 +3,19 @@ import { verifyPassword, throwInvalidCredentialsError } from '../../../core/auth | |
import { handleRejection } from '../../../utils.js' | ||
|
||
import { findUserBy, createAuthToken } from '../../utils.js' | ||
import { ensureValidUsername, ensurePasswordIsPresent } from '../../validation.js' | ||
|
||
export default handleRejection(async (req, res) => { | ||
const args = req.body || {} | ||
const userFields = req.body || {} | ||
ensureValidArgs(userFields) | ||
|
||
const user = await findUserBy({ username: args.username }) | ||
const user = await findUserBy({ username: userFields.username }) | ||
if (!user) { | ||
throwInvalidCredentialsError() | ||
} | ||
|
||
try { | ||
await verifyPassword(user.password, args.password) | ||
await verifyPassword(user.password, userFields.password) | ||
} catch(e) { | ||
throwInvalidCredentialsError() | ||
} | ||
|
@@ -28,3 +30,8 @@ export default handleRejection(async (req, res) => { | |
|
||
return res.json({ token }) | ||
}) | ||
|
||
function ensureValidArgs(args: unknown): void { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Validating the username & password in the route |
||
ensureValidUsername(args); | ||
ensurePasswordIsPresent(args); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Moving email utils from
utils.ts
toproviders/email/utils.ts