Enhanced file uploading for production (thanks citrinitas3421!)

This commit is contained in:
Ahmed Al-Taiar
2024-08-17 22:27:20 -04:00
parent a82caf96bf
commit 1c46a8e963
15 changed files with 320 additions and 51 deletions

View File

@ -1,5 +1,10 @@
import type { Decoded } from '@redwoodjs/api'
import { AuthenticationError, ForbiddenError } from '@redwoodjs/graphql-server'
import { decryptSession, getSession } from '@redwoodjs/auth-dbauth-api'
import {
AuthenticationError,
ForbiddenError,
ValidationError,
} from '@redwoodjs/graphql-server'
import { db } from './db'
@ -12,6 +17,10 @@ import { db } from './db'
*/
export const cookieName = 'session_%port%'
const cookieRegex = /([a-zA-Z0-9+/|=]{110})\w+/
const tokenRegex =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
/**
* The session object sent in as the first argument to getCurrentUser() will
* have a single key `id` containing the unique ID of the logged in user
@ -30,9 +39,8 @@ export const cookieName = 'session_%port%'
* seen if someone were to open the Web Inspector in their browser.
*/
export const getCurrentUser = async (session: Decoded) => {
if (!session || typeof session.id !== 'number') {
if (!session || typeof session.id !== 'number')
throw new Error('Invalid session')
}
return await db.user.findUnique({
where: { id: session.id },
@ -107,11 +115,29 @@ export const hasRole = (roles: AllowedRoles): boolean => {
* @see https://github.com/redwoodjs/redwood/tree/main/packages/auth for examples
*/
export const requireAuth = ({ roles }: { roles?: AllowedRoles } = {}) => {
if (!isAuthenticated()) {
if (!isAuthenticated())
throw new AuthenticationError("You don't have permission to do that.")
}
if (roles && !hasRole(roles)) {
if (roles && !hasRole(roles))
throw new ForbiddenError("You don't have access to do that.")
}
}
export const validateSessionCookie = (sessionCookie: string) => {
const sessionCookieContent = sessionCookie.substring(
sessionCookie.indexOf('=') + 1
)
if (!cookieRegex.test(sessionCookieContent))
throw new ValidationError('Invalid token format')
}
export const decryptAndValidateSession = (sessionCookie: string) => {
const cookie = cookieName.replace('%port%', '8911')
const [session, csrfToken] = decryptSession(getSession(sessionCookie, cookie))
if (!session.id) throw new ValidationError('Invalid session')
if (!tokenRegex.test(csrfToken))
throw new ValidationError('Invalid session format')
return session.id
}