diff --git a/waspc/ChangeLog.md b/waspc/ChangeLog.md index ff5c907542..3ee26f32fc 100644 --- a/waspc/ChangeLog.md +++ b/waspc/ChangeLog.md @@ -1,5 +1,27 @@ # Changelog +## 0.14.1 (2024-08-26) + +### 🎉 New Features + +- Wasp now supports `onBeforeLogin` and `onAfterLogin` auth hooks! You can use these hooks to run custom logic before and after a user logs in. For example, you can use the `onBeforeLogin` hook to check if the user is allowed to log in. +- OAuth refresh tokens are here. If the OAuth provider supports refresh tokens, you'll be able to use them to refresh the access token when it expires. This is useful for using OAuth provider APIs in the background e.g. accessing user's calendar events. + +### ⚠️ Breaking Changes + +- To make the API consistent across different auth hooks, we change how the `onBeforeOAuthRedirect` hook receives the `uniqueRequestId` value to `oauth.uniqueRequestId`. + +### 🐞 Bug fixes + +- Prisma file parser now allows using empty arrays as default values. + +### 🔧 Small improvements + +- Replace `oslo/password` with directly using `@node-rs/argon2` +- We now use `websocket` transport for the WebSocket client to avoid issues when deploying the server behind a load balancer. + +Community contributions by @rubyisrust @santolucito @sezercik @LLxD! + ## 0.14.0 (2024-07-17) ### 🎉 New Features diff --git a/waspc/data/Generator/templates/sdk/wasp/server/auth/hooks.ts b/waspc/data/Generator/templates/sdk/wasp/server/auth/hooks.ts index a3754e7f6a..67b1f2431c 100644 --- a/waspc/data/Generator/templates/sdk/wasp/server/auth/hooks.ts +++ b/waspc/data/Generator/templates/sdk/wasp/server/auth/hooks.ts @@ -1,3 +1,4 @@ +{{={= =}=}} import type { Request as ExpressRequest } from 'express' import { type ProviderId, createUser, findAuthWithUserBy } from '../../auth/utils.js' import { prisma } from '../index.js' @@ -35,7 +36,7 @@ export type OnAfterLoginHook = ( export type InternalAuthHookParams = { /** * Prisma instance that can be used to interact with the database. - */ + */ prisma: typeof prisma } @@ -48,86 +49,102 @@ export type InternalAuthHookParams = { type OnBeforeSignupHookParams = { /** * Provider ID object that contains the provider name and the provide user ID. - */ + */ providerId: ProviderId /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest } & InternalAuthHookParams type OnAfterSignupHookParams = { /** * Provider ID object that contains the provider name and the provide user ID. - */ + */ providerId: ProviderId /** * User object that was created during the signup process. - */ + */ user: Awaited> - oauth?: { - /** - * Access token that was received during the OAuth flow. - */ - accessToken: string - /** - * Unique request ID that was generated during the OAuth flow. - */ - uniqueRequestId: string - }, + /** + * OAuth flow data that was generated during the OAuth flow. This is only + * available if the user signed up using OAuth. + */ + oauth?: OAuthData /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest } & InternalAuthHookParams type OnBeforeOAuthRedirectHookParams = { /** * URL that the OAuth flow should redirect to. - */ + */ url: URL /** * Unique request ID that was generated during the OAuth flow. - */ - uniqueRequestId: string + */ + oauth: Pick /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest } & InternalAuthHookParams type OnBeforeLoginHookParams = { /** * Provider ID object that contains the provider name and the provide user ID. - */ + */ providerId: ProviderId + /** + * User that is trying to log in. + */ + user: Awaited>['user'] /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest } & InternalAuthHookParams type OnAfterLoginHookParams = { /** * Provider ID object that contains the provider name and the provide user ID. - */ + */ providerId: ProviderId - oauth?: { - /** - * Access token that was received during the OAuth flow. - */ - accessToken: string - /** - * Unique request ID that was generated during the OAuth flow. - */ - uniqueRequestId: string - }, /** * User that is logged in. - */ + */ user: Awaited>['user'] + /** + * OAuth flow data that was generated during the OAuth flow. This is only + * available if the user logged in using OAuth. + */ + oauth?: OAuthData /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest } & InternalAuthHookParams + +// PUBLIC API +export type OAuthData = { + /** + * Unique request ID that was generated during the OAuth flow. + */ + uniqueRequestId: string +} & ( + {=# enabledProviders.isGoogleAuthEnabled =} + | { providerName: 'google'; tokens: import('arctic').GoogleTokens } + {=/ enabledProviders.isGoogleAuthEnabled =} + {=# enabledProviders.isDiscordAuthEnabled =} + | { providerName: 'discord'; tokens: import('arctic').DiscordTokens } + {=/ enabledProviders.isDiscordAuthEnabled =} + {=# enabledProviders.isGitHubAuthEnabled =} + | { providerName: 'github'; tokens: import('arctic').GitHubTokens } + {=/ enabledProviders.isGitHubAuthEnabled =} + {=# enabledProviders.isKeycloakAuthEnabled =} + | { providerName: 'keycloak'; tokens: import('arctic').KeycloakTokens } + {=/ enabledProviders.isKeycloakAuthEnabled =} + | never +) diff --git a/waspc/data/Generator/templates/sdk/wasp/server/auth/index.ts b/waspc/data/Generator/templates/sdk/wasp/server/auth/index.ts index 9c305a8749..945793b0bc 100644 --- a/waspc/data/Generator/templates/sdk/wasp/server/auth/index.ts +++ b/waspc/data/Generator/templates/sdk/wasp/server/auth/index.ts @@ -30,12 +30,17 @@ export type { OnBeforeLoginHook, OnAfterLoginHook, InternalAuthHookParams, + OAuthData, } from './hooks.js' -{=# isEmailAuthEnabled =} +{=# isExternalAuthEnabled =} +export * from './oauth/index.js' +{=/ isExternalAuthEnabled =} + +{=# enabledProviders.isEmailAuthEnabled =} export * from './email/index.js' -{=/ isEmailAuthEnabled =} +{=/ enabledProviders.isEmailAuthEnabled =} -{=# isUsernameAndPasswordAuthEnabled =} +{=# enabledProviders.isUsernameAndPasswordAuthEnabled =} export * from './username.js' -{=/ isUsernameAndPasswordAuthEnabled =} +{=/ enabledProviders.isUsernameAndPasswordAuthEnabled =} diff --git a/waspc/data/Generator/templates/server/src/auth/providers/oauth/env.ts b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/env.ts similarity index 74% rename from waspc/data/Generator/templates/server/src/auth/providers/oauth/env.ts rename to waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/env.ts index 24776c6dd3..ada2452b8e 100644 --- a/waspc/data/Generator/templates/server/src/auth/providers/oauth/env.ts +++ b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/env.ts @@ -1,14 +1,13 @@ -import { type ProviderConfig } from "wasp/auth/providers/types"; - +// PRIVATE API (SDK) export function ensureEnvVarsForProvider( envVarNames: EnvVarName[], - provider: ProviderConfig, + providerName: string, ): Record { const result: Record = {}; for (const envVarName of envVarNames) { const value = process.env[envVarName]; if (!value) { - throw new Error(`${envVarName} env variable is required when using the ${provider.displayName} auth provider.`); + throw new Error(`${envVarName} env variable is required when using the ${providerName} auth provider.`); } result[envVarName] = value; } diff --git a/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/index.ts b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/index.ts new file mode 100644 index 0000000000..7fc28ed4c2 --- /dev/null +++ b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/index.ts @@ -0,0 +1,31 @@ +{{={= =}=}} +{=# enabledProviders.isGoogleAuthEnabled =} +// PUBLIC API +export { google } from './providers/google.js'; +{=/ enabledProviders.isGoogleAuthEnabled =} +{=# enabledProviders.isDiscordAuthEnabled =} +// PUBLIC API +export { discord } from './providers/discord.js'; +{=/ enabledProviders.isDiscordAuthEnabled =} +{=# enabledProviders.isGitHubAuthEnabled =} +// PUBLIC API +export { github } from './providers/github.js'; +{=/ enabledProviders.isGitHubAuthEnabled =} +{=# enabledProviders.isKeycloakAuthEnabled =} +// PUBLIC API +export { keycloak } from './providers/keycloak.js'; +{=/ enabledProviders.isKeycloakAuthEnabled =} + +// PRIVATE API +export { + loginPath, + callbackPath, + exchangeCodeForTokenPath, + handleOAuthErrorAndGetRedirectUri, + getRedirectUriForOneTimeCode, +} from './redirect.js' + +// PRIVATE API +export { + tokenStore, +} from './oneTimeCode.js' diff --git a/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/oneTimeCode.ts b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/oneTimeCode.ts new file mode 100644 index 0000000000..4f2d8ebb08 --- /dev/null +++ b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/oneTimeCode.ts @@ -0,0 +1,50 @@ +import { createJWT, validateJWT, TimeSpan } from '../../../auth/jwt.js' + +export const tokenStore = createTokenStore(); + +function createTokenStore() { + const usedTokens = new Map(); + + const validFor = new TimeSpan(1, 'm') // 1 minute + const cleanupAfter = 1000 * 60 * 60; // 1 hour + + function createToken(userId: string): Promise { + return createJWT( + { + id: userId, + }, + { + expiresIn: validFor, + } + ); + } + + function verifyToken(token: string): Promise<{ id: string }> { + return validateJWT(token); + } + + function isUsed(token: string): boolean { + return usedTokens.has(token); + } + + function markUsed(token: string): void { + usedTokens.set(token, Date.now()); + cleanUp(); + } + + function cleanUp(): void { + const now = Date.now(); + for (const [token, timestamp] of usedTokens.entries()) { + if (now - timestamp > cleanupAfter) { + usedTokens.delete(token); + } + } + } + + return { + createToken, + verifyToken, + isUsed, + markUsed, + }; +} diff --git a/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/provider.ts b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/provider.ts new file mode 100644 index 0000000000..c2aee70897 --- /dev/null +++ b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/provider.ts @@ -0,0 +1,23 @@ +import { OAuth2Provider, OAuth2ProviderWithPKCE } from "arctic"; + +export function defineProvider< + OAuthClient extends OAuth2Provider | OAuth2ProviderWithPKCE, + Env extends Record +>({ + id, + displayName, + env, + oAuthClient, +}: { + id: string; + displayName: string; + env: Env; + oAuthClient: OAuthClient; +}) { + return { + id, + displayName, + env, + oAuthClient, + }; +} diff --git a/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/providers/discord.ts b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/providers/discord.ts new file mode 100644 index 0000000000..52e396f7a6 --- /dev/null +++ b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/providers/discord.ts @@ -0,0 +1,28 @@ +{{={= =}=}} +import { Discord } from "arctic"; + +import { defineProvider } from "../provider.js"; +import { ensureEnvVarsForProvider } from "../env.js"; +import { getRedirectUriForCallback } from "../redirect.js"; + +const id = "{= providerId =}"; +const displayName = "{= displayName =}"; + +const env = ensureEnvVarsForProvider( + ["DISCORD_CLIENT_ID", "DISCORD_CLIENT_SECRET"], + displayName +); + +const oAuthClient = new Discord( + env.DISCORD_CLIENT_ID, + env.DISCORD_CLIENT_SECRET, + getRedirectUriForCallback(id).toString(), +); + +// PUBLIC API +export const discord = defineProvider({ + id, + displayName, + env, + oAuthClient, +}); diff --git a/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/providers/github.ts b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/providers/github.ts new file mode 100644 index 0000000000..e9c5019c37 --- /dev/null +++ b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/providers/github.ts @@ -0,0 +1,26 @@ +{{={= =}=}} +import { GitHub } from "arctic"; + +import { ensureEnvVarsForProvider } from "../env.js"; +import { defineProvider } from "../provider.js"; + +const id = "{= providerId =}"; +const displayName = "{= displayName =}"; + +const env = ensureEnvVarsForProvider( + ["GITHUB_CLIENT_ID", "GITHUB_CLIENT_SECRET"], + displayName +); + +const oAuthClient = new GitHub( + env.GITHUB_CLIENT_ID, + env.GITHUB_CLIENT_SECRET, +); + +// PUBLIC API +export const github = defineProvider({ + id, + displayName, + env, + oAuthClient, +}); diff --git a/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/providers/google.ts b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/providers/google.ts new file mode 100644 index 0000000000..cf157ae12b --- /dev/null +++ b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/providers/google.ts @@ -0,0 +1,28 @@ +{{={= =}=}} +import { Google } from "arctic"; + +import { ensureEnvVarsForProvider } from "../env.js"; +import { getRedirectUriForCallback } from "../redirect.js"; +import { defineProvider } from "../provider.js"; + +const id = "{= providerId =}"; +const displayName = "{= displayName =}"; + +const env = ensureEnvVarsForProvider( + ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"], + displayName, +); + +const oAuthClient = new Google( + env.GOOGLE_CLIENT_ID, + env.GOOGLE_CLIENT_SECRET, + getRedirectUriForCallback(id).toString(), +); + +// PUBLIC API +export const google = defineProvider({ + id, + displayName, + env, + oAuthClient, +}); diff --git a/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/providers/keycloak.ts b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/providers/keycloak.ts new file mode 100644 index 0000000000..93136732d9 --- /dev/null +++ b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/providers/keycloak.ts @@ -0,0 +1,29 @@ +{{={= =}=}} +import { Keycloak } from "arctic"; + +import { ensureEnvVarsForProvider } from "../env.js"; +import { getRedirectUriForCallback } from "../redirect.js"; +import { defineProvider } from "../provider.js"; + +const id = "{= providerId =}"; +const displayName = "{= displayName =}"; + +const env = ensureEnvVarsForProvider( + ["KEYCLOAK_REALM_URL", "KEYCLOAK_CLIENT_ID", "KEYCLOAK_CLIENT_SECRET"], + displayName, +); + +const oAuthClient = new Keycloak( + env.KEYCLOAK_REALM_URL, + env.KEYCLOAK_CLIENT_ID, + env.KEYCLOAK_CLIENT_SECRET, + getRedirectUriForCallback(id).toString(), +); + +// PUBLIC API +export const keycloak = defineProvider({ + id, + displayName, + env, + oAuthClient, +}); diff --git a/waspc/data/Generator/templates/server/src/auth/providers/oauth/redirect.ts b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/redirect.ts similarity index 87% rename from waspc/data/Generator/templates/server/src/auth/providers/oauth/redirect.ts rename to waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/redirect.ts index 2408a27b5e..415459bf17 100644 --- a/waspc/data/Generator/templates/server/src/auth/providers/oauth/redirect.ts +++ b/waspc/data/Generator/templates/sdk/wasp/server/auth/oauth/redirect.ts @@ -1,20 +1,23 @@ {{={= =}=}} -import { config } from 'wasp/server' -import { HttpError } from 'wasp/server' +import { config, HttpError } from '../../index.js' +// PRIVATE API (server) export const loginPath = '{= serverOAuthLoginHandlerPath =}' -export const callbackPath = '{= serverOAuthCallbackHandlerPath =}' + +// PRIVATE API (server) export const exchangeCodeForTokenPath = '{= serverExchangeCodeForTokenHandlerPath =}' -const clientOAuthCallbackPath = '{= clientOAuthCallbackPath =}' -export function getRedirectUriForCallback(providerName: string): URL { - return new URL(`${config.serverUrl}/auth/${providerName}/${callbackPath}`); -} +// PRIVATE API (server) +export const callbackPath = '{= serverOAuthCallbackHandlerPath =}' +const clientOAuthCallbackPath = '{= clientOAuthCallbackPath =}' + +// PRIVATE API (server) export function getRedirectUriForOneTimeCode(oneTimeCode: string): URL { return new URL(`${config.frontendUrl}${clientOAuthCallbackPath}#${oneTimeCode}`); } +// PRIVATE API (server) export function handleOAuthErrorAndGetRedirectUri(error: unknown): URL { if (error instanceof HttpError) { const errorMessage = isHttpErrorWithExtraMessage(error) @@ -26,6 +29,11 @@ export function handleOAuthErrorAndGetRedirectUri(error: unknown): URL { return getRedirectUriForError("An unknown error occurred while trying to log in with the OAuth provider."); } +// PRIVATE API (SDK) +export function getRedirectUriForCallback(providerName: string): URL { + return new URL(`${config.serverUrl}/auth/${providerName}/${callbackPath}`); +} + function getRedirectUriForError(error: string): URL { return new URL(`${config.frontendUrl}${clientOAuthCallbackPath}?error=${error}`); } diff --git a/waspc/data/Generator/templates/server/src/auth/providers/config/discord.ts b/waspc/data/Generator/templates/server/src/auth/providers/config/discord.ts index a5e3bcd6fe..0f7d11bbc7 100644 --- a/waspc/data/Generator/templates/server/src/auth/providers/config/discord.ts +++ b/waspc/data/Generator/templates/server/src/auth/providers/config/discord.ts @@ -1,9 +1,7 @@ {{={= =}=}} -import { Discord } from "arctic"; import type { ProviderConfig } from "wasp/auth/providers/types"; -import { getRedirectUriForCallback } from "../oauth/redirect.js"; -import { ensureEnvVarsForProvider } from "../oauth/env.js"; +import { discord } from "wasp/server/auth"; import { mergeDefaultAndUserConfig } from "../oauth/config.js"; import { createOAuthProviderRouter } from "../oauth/handler.js"; @@ -23,20 +21,9 @@ const _waspUserDefinedConfigFn = undefined {=/ configFn.isDefined =} const _waspConfig: ProviderConfig = { - id: "{= providerId =}", - displayName: "{= displayName =}", + id: discord.id, + displayName: discord.displayName, createRouter(provider) { - const env = ensureEnvVarsForProvider( - ["DISCORD_CLIENT_ID", "DISCORD_CLIENT_SECRET"], - provider - ); - - const discord = new Discord( - env.DISCORD_CLIENT_ID, - env.DISCORD_CLIENT_SECRET, - getRedirectUriForCallback(provider.id).toString(), - ); - const config = mergeDefaultAndUserConfig({ scopes: {=& requiredScopes =}, }, _waspUserDefinedConfigFn); @@ -72,8 +59,8 @@ const _waspConfig: ProviderConfig = { provider, oAuthType: 'OAuth2', userSignupFields: _waspUserSignupFields, - getAuthorizationUrl: ({ state }) => discord.createAuthorizationURL(state, config), - getProviderTokens: ({ code }) => discord.validateAuthorizationCode(code), + getAuthorizationUrl: ({ state }) => discord.oAuthClient.createAuthorizationURL(state, config), + getProviderTokens: ({ code }) => discord.oAuthClient.validateAuthorizationCode(code), getProviderInfo: ({ accessToken }) => getDiscordProfile(accessToken), }); }, diff --git a/waspc/data/Generator/templates/server/src/auth/providers/config/github.ts b/waspc/data/Generator/templates/server/src/auth/providers/config/github.ts index 12723302f9..da79e04bf2 100644 --- a/waspc/data/Generator/templates/server/src/auth/providers/config/github.ts +++ b/waspc/data/Generator/templates/server/src/auth/providers/config/github.ts @@ -1,8 +1,7 @@ {{={= =}=}} -import { GitHub } from "arctic"; import type { ProviderConfig } from "wasp/auth/providers/types"; -import { ensureEnvVarsForProvider } from "../oauth/env.js"; +import { github } from "wasp/server/auth"; import { mergeDefaultAndUserConfig } from "../oauth/config.js"; import { createOAuthProviderRouter } from "../oauth/handler.js"; @@ -22,19 +21,9 @@ const _waspUserDefinedConfigFn = undefined {=/ configFn.isDefined =} const _waspConfig: ProviderConfig = { - id: "{= providerId =}", - displayName: "{= displayName =}", + id: github.id, + displayName: github.displayName, createRouter(provider) { - const env = ensureEnvVarsForProvider( - ["GITHUB_CLIENT_ID", "GITHUB_CLIENT_SECRET"], - provider - ); - - const github = new GitHub( - env.GITHUB_CLIENT_ID, - env.GITHUB_CLIENT_SECRET, - ); - const config = mergeDefaultAndUserConfig({ scopes: {=& requiredScopes =}, }, _waspUserDefinedConfigFn); @@ -79,8 +68,8 @@ const _waspConfig: ProviderConfig = { provider, oAuthType: 'OAuth2', userSignupFields: _waspUserSignupFields, - getAuthorizationUrl: ({ state }) => github.createAuthorizationURL(state, config), - getProviderTokens: ({ code }) => github.validateAuthorizationCode(code), + getAuthorizationUrl: ({ state }) => github.oAuthClient.createAuthorizationURL(state, config), + getProviderTokens: ({ code }) => github.oAuthClient.validateAuthorizationCode(code), getProviderInfo: ({ accessToken }) => getGithubProfile(accessToken), }); }, diff --git a/waspc/data/Generator/templates/server/src/auth/providers/config/google.ts b/waspc/data/Generator/templates/server/src/auth/providers/config/google.ts index 93ba70bf2e..0209353162 100644 --- a/waspc/data/Generator/templates/server/src/auth/providers/config/google.ts +++ b/waspc/data/Generator/templates/server/src/auth/providers/config/google.ts @@ -1,9 +1,7 @@ {{={= =}=}} -import { Google } from "arctic"; - import type { ProviderConfig } from "wasp/auth/providers/types"; -import { getRedirectUriForCallback } from "../oauth/redirect.js"; -import { ensureEnvVarsForProvider } from "../oauth/env.js"; +import { google } from "wasp/server/auth"; + import { mergeDefaultAndUserConfig } from "../oauth/config.js"; import { createOAuthProviderRouter } from "../oauth/handler.js"; @@ -23,20 +21,9 @@ const _waspUserDefinedConfigFn = undefined {=/ configFn.isDefined =} const _waspConfig: ProviderConfig = { - id: "{= providerId =}", - displayName: "{= displayName =}", + id: google.id, + displayName: google.displayName, createRouter(provider) { - const env = ensureEnvVarsForProvider( - ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"], - provider - ); - - const google = new Google( - env.GOOGLE_CLIENT_ID, - env.GOOGLE_CLIENT_SECRET, - getRedirectUriForCallback(provider.id).toString(), - ); - const config = mergeDefaultAndUserConfig({ scopes: {=& requiredScopes =}, }, _waspUserDefinedConfigFn); @@ -68,8 +55,8 @@ const _waspConfig: ProviderConfig = { provider, oAuthType: 'OAuth2WithPKCE', userSignupFields: _waspUserSignupFields, - getAuthorizationUrl: ({ state, codeVerifier }) => google.createAuthorizationURL(state, codeVerifier, config), - getProviderTokens: ({ code, codeVerifier }) => google.validateAuthorizationCode(code, codeVerifier), + getAuthorizationUrl: ({ state, codeVerifier }) => google.oAuthClient.createAuthorizationURL(state, codeVerifier, config), + getProviderTokens: ({ code, codeVerifier }) => google.oAuthClient.validateAuthorizationCode(code, codeVerifier), getProviderInfo: ({ accessToken }) => getGoogleProfile(accessToken), }); }, diff --git a/waspc/data/Generator/templates/server/src/auth/providers/config/keycloak.ts b/waspc/data/Generator/templates/server/src/auth/providers/config/keycloak.ts index 95d75c656f..f80d56ad46 100644 --- a/waspc/data/Generator/templates/server/src/auth/providers/config/keycloak.ts +++ b/waspc/data/Generator/templates/server/src/auth/providers/config/keycloak.ts @@ -1,9 +1,7 @@ {{={= =}=}} -import { Keycloak } from "arctic"; import type { ProviderConfig } from "wasp/auth/providers/types"; -import { getRedirectUriForCallback } from "../oauth/redirect.js"; -import { ensureEnvVarsForProvider } from "../oauth/env.js"; +import { keycloak } from "wasp/server/auth"; import { mergeDefaultAndUserConfig } from "../oauth/config.js"; import { createOAuthProviderRouter } from "../oauth/handler.js"; @@ -23,21 +21,9 @@ const _waspUserDefinedConfigFn = undefined {=/ configFn.isDefined =} const _waspConfig: ProviderConfig = { - id: "{= providerId =}", - displayName: "{= displayName =}", + id: keycloak.id, + displayName: keycloak.displayName, createRouter(provider) { - const env = ensureEnvVarsForProvider( - ["KEYCLOAK_REALM_URL", "KEYCLOAK_CLIENT_ID", "KEYCLOAK_CLIENT_SECRET"], - provider - ); - - const keycloak = new Keycloak( - env.KEYCLOAK_REALM_URL, - env.KEYCLOAK_CLIENT_ID, - env.KEYCLOAK_CLIENT_SECRET, - getRedirectUriForCallback(provider.id).toString(), - ); - const config = mergeDefaultAndUserConfig({ scopes: {=& requiredScopes =}, }, _waspUserDefinedConfigFn); @@ -46,7 +32,7 @@ const _waspConfig: ProviderConfig = { providerProfile: unknown; providerUserId: string; }> { - const userInfoEndpoint = `${env.KEYCLOAK_REALM_URL}/protocol/openid-connect/userinfo`; + const userInfoEndpoint = `${keycloak.env.KEYCLOAK_REALM_URL}/protocol/openid-connect/userinfo`; const response = await fetch( userInfoEndpoint, { @@ -70,8 +56,8 @@ const _waspConfig: ProviderConfig = { provider, oAuthType: 'OAuth2WithPKCE', userSignupFields: _waspUserSignupFields, - getAuthorizationUrl: ({ state, codeVerifier }) => keycloak.createAuthorizationURL(state, codeVerifier, config), - getProviderTokens: ({ code, codeVerifier }) => keycloak.validateAuthorizationCode(code, codeVerifier), + getAuthorizationUrl: ({ state, codeVerifier }) => keycloak.oAuthClient.createAuthorizationURL(state, codeVerifier, config), + getProviderTokens: ({ code, codeVerifier }) => keycloak.oAuthClient.validateAuthorizationCode(code, codeVerifier), getProviderInfo: ({ accessToken }) => getKeycloakProfile(accessToken), }); }, diff --git a/waspc/data/Generator/templates/server/src/auth/providers/email/login.ts b/waspc/data/Generator/templates/server/src/auth/providers/email/login.ts index 9fdf60b8aa..4e3ddb3913 100644 --- a/waspc/data/Generator/templates/server/src/auth/providers/email/login.ts +++ b/waspc/data/Generator/templates/server/src/auth/providers/email/login.ts @@ -36,7 +36,11 @@ export function getLoginRoute() { const auth = await findAuthWithUserBy({ id: authIdentity.authId }) - await onBeforeLoginHook({ req, providerId }) + await onBeforeLoginHook({ + req, + providerId, + user: auth.user, + }) const session = await createSession(auth.id) diff --git a/waspc/data/Generator/templates/server/src/auth/providers/oauth/handler.ts b/waspc/data/Generator/templates/server/src/auth/providers/oauth/handler.ts index 869052d7ac..ec02cf5a67 100644 --- a/waspc/data/Generator/templates/server/src/auth/providers/oauth/handler.ts +++ b/waspc/data/Generator/templates/server/src/auth/providers/oauth/handler.ts @@ -6,7 +6,6 @@ import { type UserSignupFields, type ProviderConfig, } from 'wasp/auth/providers/types' - import { type OAuthType, type OAuthStateFor, @@ -19,10 +18,11 @@ import { callbackPath, loginPath, handleOAuthErrorAndGetRedirectUri, -} from './redirect.js' +} from 'wasp/server/auth' +import { OAuthData } from 'wasp/server/auth' import { onBeforeOAuthRedirectHook } from '../../hooks.js' -export function createOAuthProviderRouter({ +export function createOAuthProviderRouter({ provider, oAuthType, userSignupFields, @@ -51,14 +51,12 @@ export function createOAuthProviderRouter({ */ getProviderTokens: ( oAuthState: OAuthStateWithCodeFor, - ) => Promise<{ - accessToken: string - }> + ) => Promise /* The function that returns the user's profile and ID using the access token. */ - getProviderInfo: ({ accessToken }: { accessToken: string }) => Promise<{ + getProviderInfo: (tokens: Tokens) => Promise<{ providerUserId: string providerProfile: unknown }> @@ -77,7 +75,7 @@ export function createOAuthProviderRouter({ const { url: redirectUrlAfterHook } = await onBeforeOAuthRedirectHook({ req, url: redirectUrl, - uniqueRequestId: oAuthState.state, + oauth: { uniqueRequestId: oAuthState.state } }) return redirect(res, redirectUrlAfterHook.toString()) }), @@ -92,11 +90,9 @@ export function createOAuthProviderRouter({ provider, req, }) - const { accessToken } = await getProviderTokens(oAuthState) + const tokens = await getProviderTokens(oAuthState) - const { providerProfile, providerUserId } = await getProviderInfo({ - accessToken, - }) + const { providerProfile, providerUserId } = await getProviderInfo(tokens) try { const redirectUri = await finishOAuthFlowAndGetRedirectUri({ provider, @@ -104,8 +100,17 @@ export function createOAuthProviderRouter({ providerUserId, userSignupFields, req, - accessToken, - oAuthState, + oauth: { + uniqueRequestId: oAuthState.state, + // OAuth params are built as a discriminated union + // of provider names and their respective tokens. + // We are using a generic ProviderConfig and tokens type + // is inferred from the getProviderTokens function. + // Instead of building complex TS machinery to ensure that + // the providerName and tokens match, we are using any here. + providerName: provider.id as any, + tokens, + }, }) // Redirect to the client with the one time code return redirect(res, redirectUri.toString()) diff --git a/waspc/data/Generator/templates/server/src/auth/providers/oauth/oneTimeCode.ts b/waspc/data/Generator/templates/server/src/auth/providers/oauth/oneTimeCode.ts index 0b98a1d879..cf1410c10f 100644 --- a/waspc/data/Generator/templates/server/src/auth/providers/oauth/oneTimeCode.ts +++ b/waspc/data/Generator/templates/server/src/auth/providers/oauth/oneTimeCode.ts @@ -2,12 +2,9 @@ import { Router } from "express"; import { HttpError } from 'wasp/server'; import { handleRejection } from 'wasp/server/utils' -import { createJWT, validateJWT, TimeSpan } from 'wasp/auth/jwt' import { findAuthWithUserBy } from 'wasp/auth/utils' import { createSession } from 'wasp/auth/session' -import { exchangeCodeForTokenPath } from "./redirect.js"; - -export const tokenStore = createTokenStore(); +import { exchangeCodeForTokenPath, tokenStore } from "wasp/server/auth"; export function setupOneTimeCodeRoute(router: Router) { router.post( @@ -40,50 +37,3 @@ export function setupOneTimeCodeRoute(router: Router) { }) ); } - -function createTokenStore() { - const usedTokens = new Map(); - - const validFor = new TimeSpan(1, 'm') // 1 minute - const cleanupAfter = 1000 * 60 * 60; // 1 hour - - function createToken(userId: string): Promise { - return createJWT( - { - id: userId, - }, - { - expiresIn: validFor, - } - ); - } - - function verifyToken(token: string): Promise<{ id: string }> { - return validateJWT(token); - } - - function isUsed(token: string): boolean { - return usedTokens.has(token); - } - - function markUsed(token: string): void { - usedTokens.set(token, Date.now()); - cleanUp(); - } - - function cleanUp(): void { - const now = Date.now(); - for (const [token, timestamp] of usedTokens.entries()) { - if (now - timestamp > cleanupAfter) { - usedTokens.delete(token); - } - } - } - - return { - createToken, - verifyToken, - isUsed, - markUsed, - }; -} diff --git a/waspc/data/Generator/templates/server/src/auth/providers/oauth/user.ts b/waspc/data/Generator/templates/server/src/auth/providers/oauth/user.ts index e1958d0510..799e615439 100644 --- a/waspc/data/Generator/templates/server/src/auth/providers/oauth/user.ts +++ b/waspc/data/Generator/templates/server/src/auth/providers/oauth/user.ts @@ -11,8 +11,8 @@ import { import { type {= authEntityUpper =} } from 'wasp/entities' import { prisma } from 'wasp/server' import { type UserSignupFields, type ProviderConfig } from 'wasp/auth/providers/types' -import { getRedirectUriForOneTimeCode } from './redirect' -import { tokenStore } from './oneTimeCode' +import { type OAuthData } from 'wasp/server/auth' +import { getRedirectUriForOneTimeCode, tokenStore } from 'wasp/server/auth' import { onBeforeSignupHook, onAfterSignupHook, @@ -26,16 +26,14 @@ export async function finishOAuthFlowAndGetRedirectUri({ providerUserId, userSignupFields, req, - accessToken, - oAuthState, + oauth }: { provider: ProviderConfig; providerProfile: unknown; providerUserId: string; userSignupFields: UserSignupFields | undefined; req: ExpressRequest; - accessToken: string; - oAuthState: { state: string }; + oauth: OAuthData; }): Promise { const providerId = createProviderId(provider.id, providerUserId); @@ -44,8 +42,7 @@ export async function finishOAuthFlowAndGetRedirectUri({ providerProfile, userSignupFields, req, - accessToken, - oAuthState, + oauth, }); const oneTimeCode = await tokenStore.createToken(authId) @@ -60,15 +57,13 @@ async function getAuthIdFromProviderDetails({ providerProfile, userSignupFields, req, - accessToken, - oAuthState, + oauth, }: { providerId: ProviderId; providerProfile: any; userSignupFields: UserSignupFields | undefined; req: ExpressRequest; - accessToken: string; - oAuthState: { state: string }; + oauth: OAuthData; }): Promise<{= authEntityUpper =}['id']> { const existingAuthIdentity = await prisma.{= authIdentityEntityLower =}.findUnique({ where: { @@ -86,26 +81,27 @@ async function getAuthIdFromProviderDetails({ if (existingAuthIdentity) { const authId = existingAuthIdentity.{= authFieldOnAuthIdentityEntityName =}.id + // NOTE: Fetching the user to pass it to the login hooks - it's a bit wasteful + // but we wanted to keep the onAfterLoginHook params consistent for all auth providers. + const auth = await findAuthWithUserBy({ id: authId }) + // NOTE: We are calling login hooks here even though we didn't log in the user yet. // It's because we have access to the OAuth tokens here and we want to pass them to the hooks. // We could have stored the tokens temporarily and called the hooks after the session is created, // but this keeps the implementation simpler. // The downside of this approach is that we can't provide the session to the login hooks, but this is // an okay trade-off because OAuth tokens are more valuable to users than the session ID. - await onBeforeLoginHook({ req, providerId }) - - // NOTE: Fetching the user to pass it to the onAfterLoginHook - it's a bit wasteful - // but we wanted to keep the onAfterLoginHook params consistent for all auth providers. - const auth = await findAuthWithUserBy({ id: authId }) + await onBeforeLoginHook({ + req, + providerId, + user: auth.user, + }) // NOTE: check the comment above onBeforeLoginHook for the explanation why we call onAfterLoginHook here. await onAfterLoginHook({ req, providerId, - oauth: { - accessToken, - uniqueRequestId: oAuthState.state, - }, + oauth, user: auth.user, }) @@ -131,10 +127,7 @@ async function getAuthIdFromProviderDetails({ req, providerId, user, - oauth: { - accessToken, - uniqueRequestId: oAuthState.state, - }, + oauth, }) return user.auth.id diff --git a/waspc/data/Generator/templates/server/src/auth/providers/username/login.ts b/waspc/data/Generator/templates/server/src/auth/providers/username/login.ts index 106de623ac..e45aecfae5 100644 --- a/waspc/data/Generator/templates/server/src/auth/providers/username/login.ts +++ b/waspc/data/Generator/templates/server/src/auth/providers/username/login.ts @@ -35,7 +35,11 @@ export default handleRejection(async (req, res) => { id: authIdentity.authId }) - await onBeforeLoginHook({ req, providerId }) + await onBeforeLoginHook({ + req, + providerId, + user: auth.user, + }) const session = await createSession(auth.id) diff --git a/waspc/e2e-test/test-outputs/waspBuild-golden/waspBuild/main.wasp b/waspc/e2e-test/test-outputs/waspBuild-golden/waspBuild/main.wasp index eb7c32e2d1..1d5e7fc6a1 100644 --- a/waspc/e2e-test/test-outputs/waspBuild-golden/waspBuild/main.wasp +++ b/waspc/e2e-test/test-outputs/waspBuild-golden/waspBuild/main.wasp @@ -1,6 +1,6 @@ app waspBuild { wasp: { - version: "^0.14.0" + version: "^0.14.1" }, title: "waspBuild" } diff --git a/waspc/e2e-test/test-outputs/waspCompile-golden/waspCompile/main.wasp b/waspc/e2e-test/test-outputs/waspCompile-golden/waspCompile/main.wasp index 925dc6c4fe..6e0a63a5de 100644 --- a/waspc/e2e-test/test-outputs/waspCompile-golden/waspCompile/main.wasp +++ b/waspc/e2e-test/test-outputs/waspCompile-golden/waspCompile/main.wasp @@ -1,6 +1,6 @@ app waspCompile { wasp: { - version: "^0.14.0" + version: "^0.14.1" }, title: "waspCompile" } diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/files.manifest b/waspc/e2e-test/test-outputs/waspComplexTest-golden/files.manifest index 1cca8a12a5..6f80170dcd 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/files.manifest +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/files.manifest @@ -278,6 +278,24 @@ waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/hooks.js.map waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.d.ts waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.js waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.js.map +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/env.d.ts +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/env.js +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/env.js.map +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/index.d.ts +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/index.js +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/index.js.map +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/oneTimeCode.d.ts +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/oneTimeCode.js +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/oneTimeCode.js.map +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/provider.d.ts +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/provider.js +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/provider.js.map +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/providers/google.d.ts +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/providers/google.js +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/providers/google.js.map +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/redirect.d.ts +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/redirect.js +waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/redirect.js.map waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/user.d.ts waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/user.js waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/user.js.map @@ -398,6 +416,12 @@ waspComplexTest/.wasp/out/sdk/wasp/server/_types/taggedEntities.ts waspComplexTest/.wasp/out/sdk/wasp/server/api/index.ts waspComplexTest/.wasp/out/sdk/wasp/server/auth/hooks.ts waspComplexTest/.wasp/out/sdk/wasp/server/auth/index.ts +waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/env.ts +waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/index.ts +waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/oneTimeCode.ts +waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/provider.ts +waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/providers/google.ts +waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/redirect.ts waspComplexTest/.wasp/out/sdk/wasp/server/auth/user.ts waspComplexTest/.wasp/out/sdk/wasp/server/config.ts waspComplexTest/.wasp/out/sdk/wasp/server/crud/index.ts @@ -446,10 +470,8 @@ waspComplexTest/.wasp/out/server/src/auth/providers/config/google.ts waspComplexTest/.wasp/out/server/src/auth/providers/index.ts waspComplexTest/.wasp/out/server/src/auth/providers/oauth/config.ts waspComplexTest/.wasp/out/server/src/auth/providers/oauth/cookies.ts -waspComplexTest/.wasp/out/server/src/auth/providers/oauth/env.ts waspComplexTest/.wasp/out/server/src/auth/providers/oauth/handler.ts waspComplexTest/.wasp/out/server/src/auth/providers/oauth/oneTimeCode.ts -waspComplexTest/.wasp/out/server/src/auth/providers/oauth/redirect.ts waspComplexTest/.wasp/out/server/src/auth/providers/oauth/state.ts waspComplexTest/.wasp/out/server/src/auth/providers/oauth/types.ts waspComplexTest/.wasp/out/server/src/auth/providers/oauth/user.ts diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/.waspchecksums b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/.waspchecksums index 58122aeafb..1a3367fda5 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/.waspchecksums +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/.waspchecksums @@ -487,7 +487,7 @@ "file", "../out/sdk/wasp/package.json" ], - "865b586bae503309553b1f897b264a4a888400919e509b906047ec972c9b22a0" + "c31d84c5efffac3e5f6e069acf14be8e468b86f01f5188f01dd45fd1f2804760" ], [ [ @@ -536,14 +536,56 @@ "file", "../out/sdk/wasp/server/auth/hooks.ts" ], - "3105d318bcb86a6638f414a155aad29dcea3613f7f14c6c282b677b9333eac57" + "1626df1c652b4f5d5f6a64c6537bae422243e62c867e668c16968738fd9637b1" ], [ [ "file", "../out/sdk/wasp/server/auth/index.ts" ], - "20277db8773191867bd7938215abdf4a6814f84ba38fd55dd36ae5ebbbbe0754" + "9f932aba0d2ca6d1d2ff6fd826d238da3719b7676e7b42e97430af6f86fd03e2" + ], + [ + [ + "file", + "../out/sdk/wasp/server/auth/oauth/env.ts" + ], + "50416a8c284fdbb3952e21e1617da2270b99dba717023babc7c32f5b12a63a32" + ], + [ + [ + "file", + "../out/sdk/wasp/server/auth/oauth/index.ts" + ], + "bc8cf4d3b89018a68704d30bc3183bbd58461c9db0796f603f3e13179d604630" + ], + [ + [ + "file", + "../out/sdk/wasp/server/auth/oauth/oneTimeCode.ts" + ], + "0cee805003b69e48c01bb1e7bfefb4bc6d0fab504ada926f5c3de6f8a5505335" + ], + [ + [ + "file", + "../out/sdk/wasp/server/auth/oauth/provider.ts" + ], + "2a2015d905a2ceddb45ff1034b283b242df153ddf2cabd05fddd4746365622df" + ], + [ + [ + "file", + "../out/sdk/wasp/server/auth/oauth/providers/google.ts" + ], + "2a30b51f7be3a627d652e164669b01832345763597aa1e0badf7d321ccdc3bdb" + ], + [ + [ + "file", + "../out/sdk/wasp/server/auth/oauth/redirect.ts" + ], + "2fb01e01e8e5209c8b96b0f25f2fcab5fb30c0c8c3a228d65711f3ce11031942" ], [ [ @@ -844,7 +886,7 @@ "file", "server/package.json" ], - "23fbe60e2f89a7fb12a11bd11aef43e3ed713ffd49697ab40c1cbbf0b3c4c84d" + "204a25f8a86edd2b492f841d2314c510a8f450205620427bb52de7d3ebb1ea1c" ], [ [ @@ -886,7 +928,7 @@ "file", "server/src/auth/providers/config/google.ts" ], - "d53d1fb541e3ef3f2b2996731c4da7ef5db0568aed39f03f1de3f9b6d3d30471" + "b2ebe3b7789b4abfb66a4c206a189e8559627ab0ebcf8b9b812747a962c35cce" ], [ [ @@ -909,33 +951,19 @@ ], "7fb6658564e8af442d0f0b5874879e6788e91e89d98a8265621dd323135f5916" ], - [ - [ - "file", - "server/src/auth/providers/oauth/env.ts" - ], - "65c5ce3b4ead10faad600435654d2614a862281ce5177996599bc159c39bb551" - ], [ [ "file", "server/src/auth/providers/oauth/handler.ts" ], - "7ca4820825cb4cc445c9161c391f2aaefe7c0d072e84fd9569f8d607e2bf2a28" + "a8ce8d2b140a59e07d767cc640b9a2b0116e2dafc3ef98ae67fa7cdab3527416" ], [ [ "file", "server/src/auth/providers/oauth/oneTimeCode.ts" ], - "6a23d30c2d98e14f6e293ebf3bb9392d25a3eeb7f1ec98078440a11af0aa0c78" - ], - [ - [ - "file", - "server/src/auth/providers/oauth/redirect.ts" - ], - "099d0b7aee0eafd258f4e656f405816e3f0d26dcaa705d97d3c9044f67824146" + "c9bf9cb3ce635f8f53f2b176e4e9f8e39851ee1a2ba972221f3eaf1a0826fab9" ], [ [ @@ -956,7 +984,7 @@ "file", "server/src/auth/providers/oauth/user.ts" ], - "4ae56549dccf3fa5d75250ef9593e1cf65012bf48219895dc92df586e5d95a45" + "0798bdc8635f62e693d7bb4df5ab5ee4ec08a59b43cee3ce14094fd9ae19c89e" ], [ [ diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/installedNpmDepsLog.json b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/installedNpmDepsLog.json index 5b7b096d34..9c7f062316 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/installedNpmDepsLog.json +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/installedNpmDepsLog.json @@ -1 +1 @@ -{"_waspSdkNpmDeps":{"dependencies":[{"name":"@prisma/client","version":"5.18.0"},{"name":"prisma","version":"5.18.0"},{"name":"@tanstack/react-query","version":"^4.29.0"},{"name":"axios","version":"^1.4.0"},{"name":"express","version":"~4.18.1"},{"name":"mitt","version":"3.0.0"},{"name":"react","version":"^18.2.0"},{"name":"lodash.merge","version":"^4.6.2"},{"name":"react-router-dom","version":"^5.3.3"},{"name":"react-hook-form","version":"^7.45.4"},{"name":"superjson","version":"^1.12.2"},{"name":"@types/express-serve-static-core","version":"^4.17.13"},{"name":"@types/react-router-dom","version":"^5.3.3"},{"name":"@stitches/react","version":"^1.2.8"},{"name":"@node-rs/argon2","version":"^1.8.3"},{"name":"lucia","version":"^3.0.1"},{"name":"oslo","version":"^1.1.2"},{"name":"@lucia-auth/adapter-prisma","version":"^4.0.0"},{"name":"@sendgrid/mail","version":"^7.7.0"},{"name":"uuid","version":"^9.0.0"},{"name":"vitest","version":"^1.2.1"},{"name":"@vitest/ui","version":"^1.2.1"},{"name":"jsdom","version":"^21.1.1"},{"name":"@testing-library/react","version":"^14.1.2"},{"name":"@testing-library/jest-dom","version":"^6.3.0"},{"name":"msw","version":"^1.1.0"},{"name":"pg-boss","version":"^8.4.2"}],"devDependencies":[{"name":"@tsconfig/node18","version":"latest"}]},"_userNpmDeps":{"userDependencies":[{"name":"react","version":"^18.2.0"},{"name":"wasp","version":"file:.wasp/out/sdk/wasp"}],"userDevDependencies":[{"name":"@types/react","version":"^18.0.37"},{"name":"prisma","version":"5.18.0"},{"name":"typescript","version":"^5.1.0"},{"name":"vite","version":"^4.3.9"}]},"_waspFrameworkNpmDeps":{"npmDepsForWebApp":{"dependencies":[{"name":"@tanstack/react-query","version":"^4.29.0"},{"name":"axios","version":"^1.4.0"},{"name":"mitt","version":"3.0.0"},{"name":"react-dom","version":"^18.2.0"},{"name":"react-hook-form","version":"^7.45.4"},{"name":"react-router-dom","version":"^5.3.3"},{"name":"superjson","version":"^1.12.2"}],"devDependencies":[{"name":"@tsconfig/vite-react","version":"^2.0.0"},{"name":"@types/react-dom","version":"^18.0.11"},{"name":"@types/react-router-dom","version":"^5.3.3"},{"name":"@vitejs/plugin-react","version":"^4.2.1"},{"name":"dotenv","version":"^16.0.3"}]},"npmDepsForServer":{"dependencies":[{"name":"arctic","version":"^1.2.1"},{"name":"cookie-parser","version":"~1.4.6"},{"name":"cors","version":"^2.8.5"},{"name":"dotenv","version":"16.0.2"},{"name":"express","version":"~4.18.1"},{"name":"helmet","version":"^6.0.0"},{"name":"morgan","version":"~1.10.0"},{"name":"rate-limiter-flexible","version":"^2.4.1"},{"name":"superjson","version":"^1.12.2"}],"devDependencies":[{"name":"@tsconfig/node18","version":"latest"},{"name":"@types/cors","version":"^2.8.5"},{"name":"@types/express","version":"^4.17.13"},{"name":"@types/express-serve-static-core","version":"^4.17.13"},{"name":"@types/node","version":"^18.0.0"},{"name":"nodemon","version":"^2.0.19"},{"name":"rollup","version":"^4.9.6"},{"name":"rollup-plugin-esbuild","version":"^6.1.1"},{"name":"standard","version":"^17.0.0"}]}}} \ No newline at end of file +{"_waspSdkNpmDeps":{"dependencies":[{"name":"@prisma/client","version":"5.18.0"},{"name":"prisma","version":"5.18.0"},{"name":"@tanstack/react-query","version":"^4.29.0"},{"name":"axios","version":"^1.4.0"},{"name":"express","version":"~4.18.1"},{"name":"mitt","version":"3.0.0"},{"name":"react","version":"^18.2.0"},{"name":"lodash.merge","version":"^4.6.2"},{"name":"react-router-dom","version":"^5.3.3"},{"name":"react-hook-form","version":"^7.45.4"},{"name":"superjson","version":"^1.12.2"},{"name":"@types/express-serve-static-core","version":"^4.17.13"},{"name":"@types/react-router-dom","version":"^5.3.3"},{"name":"@stitches/react","version":"^1.2.8"},{"name":"@node-rs/argon2","version":"^1.8.3"},{"name":"arctic","version":"^1.2.1"},{"name":"lucia","version":"^3.0.1"},{"name":"oslo","version":"^1.1.2"},{"name":"@lucia-auth/adapter-prisma","version":"^4.0.0"},{"name":"@sendgrid/mail","version":"^7.7.0"},{"name":"uuid","version":"^9.0.0"},{"name":"vitest","version":"^1.2.1"},{"name":"@vitest/ui","version":"^1.2.1"},{"name":"jsdom","version":"^21.1.1"},{"name":"@testing-library/react","version":"^14.1.2"},{"name":"@testing-library/jest-dom","version":"^6.3.0"},{"name":"msw","version":"^1.1.0"},{"name":"pg-boss","version":"^8.4.2"}],"devDependencies":[{"name":"@tsconfig/node18","version":"latest"}]},"_userNpmDeps":{"userDependencies":[{"name":"react","version":"^18.2.0"},{"name":"wasp","version":"file:.wasp/out/sdk/wasp"}],"userDevDependencies":[{"name":"@types/react","version":"^18.0.37"},{"name":"prisma","version":"5.18.0"},{"name":"typescript","version":"^5.1.0"},{"name":"vite","version":"^4.3.9"}]},"_waspFrameworkNpmDeps":{"npmDepsForWebApp":{"dependencies":[{"name":"@tanstack/react-query","version":"^4.29.0"},{"name":"axios","version":"^1.4.0"},{"name":"mitt","version":"3.0.0"},{"name":"react-dom","version":"^18.2.0"},{"name":"react-hook-form","version":"^7.45.4"},{"name":"react-router-dom","version":"^5.3.3"},{"name":"superjson","version":"^1.12.2"}],"devDependencies":[{"name":"@tsconfig/vite-react","version":"^2.0.0"},{"name":"@types/react-dom","version":"^18.0.11"},{"name":"@types/react-router-dom","version":"^5.3.3"},{"name":"@vitejs/plugin-react","version":"^4.2.1"},{"name":"dotenv","version":"^16.0.3"}]},"npmDepsForServer":{"dependencies":[{"name":"cookie-parser","version":"~1.4.6"},{"name":"cors","version":"^2.8.5"},{"name":"dotenv","version":"16.0.2"},{"name":"express","version":"~4.18.1"},{"name":"helmet","version":"^6.0.0"},{"name":"morgan","version":"~1.10.0"},{"name":"rate-limiter-flexible","version":"^2.4.1"},{"name":"superjson","version":"^1.12.2"}],"devDependencies":[{"name":"@tsconfig/node18","version":"latest"},{"name":"@types/cors","version":"^2.8.5"},{"name":"@types/express","version":"^4.17.13"},{"name":"@types/express-serve-static-core","version":"^4.17.13"},{"name":"@types/node","version":"^18.0.0"},{"name":"nodemon","version":"^2.0.19"},{"name":"rollup","version":"^4.9.6"},{"name":"rollup-plugin-esbuild","version":"^6.1.1"},{"name":"standard","version":"^17.0.0"}]}}} \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/hooks.d.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/hooks.d.ts index e8ab8850ae..fe3999de1d 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/hooks.d.ts +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/hooks.d.ts @@ -17,89 +17,92 @@ export type OnAfterLoginHook = (params: Expand) => void export type InternalAuthHookParams = { /** * Prisma instance that can be used to interact with the database. - */ + */ prisma: typeof prisma; }; type OnBeforeSignupHookParams = { /** * Provider ID object that contains the provider name and the provide user ID. - */ + */ providerId: ProviderId; /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest; } & InternalAuthHookParams; type OnAfterSignupHookParams = { /** * Provider ID object that contains the provider name and the provide user ID. - */ + */ providerId: ProviderId; /** * User object that was created during the signup process. - */ + */ user: Awaited>; - oauth?: { - /** - * Access token that was received during the OAuth flow. - */ - accessToken: string; - /** - * Unique request ID that was generated during the OAuth flow. - */ - uniqueRequestId: string; - }; + /** + * OAuth flow data that was generated during the OAuth flow. This is only + * available if the user signed up using OAuth. + */ + oauth?: OAuthData; /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest; } & InternalAuthHookParams; type OnBeforeOAuthRedirectHookParams = { /** * URL that the OAuth flow should redirect to. - */ + */ url: URL; /** * Unique request ID that was generated during the OAuth flow. - */ - uniqueRequestId: string; + */ + oauth: Pick; /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest; } & InternalAuthHookParams; type OnBeforeLoginHookParams = { /** * Provider ID object that contains the provider name and the provide user ID. - */ + */ providerId: ProviderId; + /** + * User that is trying to log in. + */ + user: Awaited>['user']; /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest; } & InternalAuthHookParams; type OnAfterLoginHookParams = { /** * Provider ID object that contains the provider name and the provide user ID. - */ + */ providerId: ProviderId; - oauth?: { - /** - * Access token that was received during the OAuth flow. - */ - accessToken: string; - /** - * Unique request ID that was generated during the OAuth flow. - */ - uniqueRequestId: string; - }; /** * User that is logged in. - */ + */ user: Awaited>['user']; + /** + * OAuth flow data that was generated during the OAuth flow. This is only + * available if the user logged in using OAuth. + */ + oauth?: OAuthData; /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest; } & InternalAuthHookParams; +export type OAuthData = { + /** + * Unique request ID that was generated during the OAuth flow. + */ + uniqueRequestId: string; +} & ({ + providerName: 'google'; + tokens: import('arctic').GoogleTokens; +} | never); export {}; diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.d.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.d.ts index 54d5306997..d387a6172f 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.d.ts +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.d.ts @@ -1,4 +1,5 @@ export { defineUserSignupFields, } from '../../auth/providers/types.js'; export { createProviderId, sanitizeAndSerializeProviderData, updateAuthIdentityProviderData, deserializeAndSanitizeProviderData, findAuthIdentity, createUser, type ProviderId, type ProviderName, type EmailProviderData, type UsernameProviderData, type OAuthProviderData, } from '../../auth/utils.js'; export { ensurePasswordIsPresent, ensureValidPassword, ensureTokenIsPresent, } from '../../auth/validation.js'; -export type { OnBeforeSignupHook, OnAfterSignupHook, OnBeforeOAuthRedirectHook, OnBeforeLoginHook, OnAfterLoginHook, InternalAuthHookParams, } from './hooks.js'; +export type { OnBeforeSignupHook, OnAfterSignupHook, OnBeforeOAuthRedirectHook, OnBeforeLoginHook, OnAfterLoginHook, InternalAuthHookParams, OAuthData, } from './hooks.js'; +export * from './oauth/index.js'; diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.js b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.js index 66289fd100..7f489c9a62 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.js +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.js @@ -1,4 +1,5 @@ export { defineUserSignupFields, } from '../../auth/providers/types.js'; export { createProviderId, sanitizeAndSerializeProviderData, updateAuthIdentityProviderData, deserializeAndSanitizeProviderData, findAuthIdentity, createUser, } from '../../auth/utils.js'; export { ensurePasswordIsPresent, ensureValidPassword, ensureTokenIsPresent, } from '../../auth/validation.js'; +export * from './oauth/index.js'; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.js.map b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.js.map index 279d2fda3a..4fad2ccaeb 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.js.map +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../server/auth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,GACvB,MAAM,+BAA+B,CAAA;AAEtC,OAAO,EACL,gBAAgB,EAChB,gCAAgC,EAChC,8BAA8B,EAC9B,kCAAkC,EAClC,gBAAgB,EAChB,UAAU,GAMX,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EACL,uBAAuB,EACvB,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,0BAA0B,CAAA"} \ No newline at end of file +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../server/auth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,GACvB,MAAM,+BAA+B,CAAA;AAEtC,OAAO,EACL,gBAAgB,EAChB,gCAAgC,EAChC,8BAA8B,EAC9B,kCAAkC,EAClC,gBAAgB,EAChB,UAAU,GAMX,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EACL,uBAAuB,EACvB,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,0BAA0B,CAAA;AAYjC,cAAc,kBAAkB,CAAA"} \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/env.d.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/env.d.ts new file mode 100644 index 0000000000..08d2627b88 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/env.d.ts @@ -0,0 +1 @@ +export declare function ensureEnvVarsForProvider(envVarNames: EnvVarName[], providerName: string): Record; diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/env.js b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/env.js new file mode 100644 index 0000000000..56281b5e36 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/env.js @@ -0,0 +1,13 @@ +// PRIVATE API (SDK) +export function ensureEnvVarsForProvider(envVarNames, providerName) { + const result = {}; + for (const envVarName of envVarNames) { + const value = process.env[envVarName]; + if (!value) { + throw new Error(`${envVarName} env variable is required when using the ${providerName} auth provider.`); + } + result[envVarName] = value; + } + return result; +} +//# sourceMappingURL=env.js.map \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/env.js.map b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/env.js.map new file mode 100644 index 0000000000..b25f2f9870 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/env.js.map @@ -0,0 +1 @@ +{"version":3,"file":"env.js","sourceRoot":"","sources":["../../../../server/auth/oauth/env.ts"],"names":[],"mappings":"AAAA,oBAAoB;AACpB,MAAM,UAAU,wBAAwB,CACtC,WAAyB,EACzB,YAAoB;IAEpB,MAAM,MAAM,GAA2B,EAAE,CAAC;IAC1C,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE,CAAC;QACrC,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACtC,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,4CAA4C,YAAY,iBAAiB,CAAC,CAAC;QAC1G,CAAC;QACD,MAAM,CAAC,UAAU,CAAC,GAAG,KAAK,CAAC;IAC7B,CAAC;IACD,OAAO,MAAoC,CAAC;AAC9C,CAAC"} \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/index.d.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/index.d.ts new file mode 100644 index 0000000000..8e9db44404 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/index.d.ts @@ -0,0 +1,3 @@ +export { google } from './providers/google.js'; +export { loginPath, callbackPath, exchangeCodeForTokenPath, handleOAuthErrorAndGetRedirectUri, getRedirectUriForOneTimeCode, } from './redirect.js'; +export { tokenStore, } from './oneTimeCode.js'; diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/index.js b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/index.js new file mode 100644 index 0000000000..64a91e37b4 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/index.js @@ -0,0 +1,7 @@ +// PUBLIC API +export { google } from './providers/google.js'; +// PRIVATE API +export { loginPath, callbackPath, exchangeCodeForTokenPath, handleOAuthErrorAndGetRedirectUri, getRedirectUriForOneTimeCode, } from './redirect.js'; +// PRIVATE API +export { tokenStore, } from './oneTimeCode.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/index.js.map b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/index.js.map new file mode 100644 index 0000000000..0e31443824 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../server/auth/oauth/index.ts"],"names":[],"mappings":"AAAA,aAAa;AACb,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAE/C,cAAc;AACd,OAAO,EACL,SAAS,EACT,YAAY,EACZ,wBAAwB,EACxB,iCAAiC,EACjC,4BAA4B,GAC7B,MAAM,eAAe,CAAA;AAEtB,cAAc;AACd,OAAO,EACL,UAAU,GACX,MAAM,kBAAkB,CAAA"} \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/oneTimeCode.d.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/oneTimeCode.d.ts new file mode 100644 index 0000000000..6d3404f4a3 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/oneTimeCode.d.ts @@ -0,0 +1,8 @@ +export declare const tokenStore: { + createToken: (userId: string) => Promise; + verifyToken: (token: string) => Promise<{ + id: string; + }>; + isUsed: (token: string) => boolean; + markUsed: (token: string) => void; +}; diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/oneTimeCode.js b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/oneTimeCode.js new file mode 100644 index 0000000000..202551ec8a --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/oneTimeCode.js @@ -0,0 +1,39 @@ +import { createJWT, validateJWT, TimeSpan } from '../../../auth/jwt.js'; +export const tokenStore = createTokenStore(); +function createTokenStore() { + const usedTokens = new Map(); + const validFor = new TimeSpan(1, 'm'); // 1 minute + const cleanupAfter = 1000 * 60 * 60; // 1 hour + function createToken(userId) { + return createJWT({ + id: userId, + }, { + expiresIn: validFor, + }); + } + function verifyToken(token) { + return validateJWT(token); + } + function isUsed(token) { + return usedTokens.has(token); + } + function markUsed(token) { + usedTokens.set(token, Date.now()); + cleanUp(); + } + function cleanUp() { + const now = Date.now(); + for (const [token, timestamp] of usedTokens.entries()) { + if (now - timestamp > cleanupAfter) { + usedTokens.delete(token); + } + } + } + return { + createToken, + verifyToken, + isUsed, + markUsed, + }; +} +//# sourceMappingURL=oneTimeCode.js.map \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/oneTimeCode.js.map b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/oneTimeCode.js.map new file mode 100644 index 0000000000..9eea0cae38 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/oneTimeCode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"oneTimeCode.js","sourceRoot":"","sources":["../../../../server/auth/oauth/oneTimeCode.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AAEvE,MAAM,CAAC,MAAM,UAAU,GAAG,gBAAgB,EAAE,CAAC;AAE7C,SAAS,gBAAgB;IACvB,MAAM,UAAU,GAAG,IAAI,GAAG,EAAkB,CAAC;IAE7C,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAA,CAAC,WAAW;IACjD,MAAM,YAAY,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,SAAS;IAE9C,SAAS,WAAW,CAAC,MAAc;QACjC,OAAO,SAAS,CACd;YACE,EAAE,EAAE,MAAM;SACX,EACD;YACE,SAAS,EAAE,QAAQ;SACpB,CACF,CAAC;IACJ,CAAC;IAED,SAAS,WAAW,CAAC,KAAa;QAChC,OAAO,WAAW,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IAED,SAAS,MAAM,CAAC,KAAa;QAC3B,OAAO,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC/B,CAAC;IAED,SAAS,QAAQ,CAAC,KAAa;QAC7B,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QAClC,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,SAAS,OAAO;QACd,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,KAAK,MAAM,CAAC,KAAK,EAAE,SAAS,CAAC,IAAI,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC;YACtD,IAAI,GAAG,GAAG,SAAS,GAAG,YAAY,EAAE,CAAC;gBACnC,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC3B,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO;QACL,WAAW;QACX,WAAW;QACX,MAAM;QACN,QAAQ;KACT,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/provider.d.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/provider.d.ts new file mode 100644 index 0000000000..44d23b4952 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/provider.d.ts @@ -0,0 +1,12 @@ +import { OAuth2Provider, OAuth2ProviderWithPKCE } from "arctic"; +export declare function defineProvider>({ id, displayName, env, oAuthClient, }: { + id: string; + displayName: string; + env: Env; + oAuthClient: OAuthClient; +}): { + id: string; + displayName: string; + env: Env; + oAuthClient: OAuthClient; +}; diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/provider.js b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/provider.js new file mode 100644 index 0000000000..bc0d9a2fd8 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/provider.js @@ -0,0 +1,9 @@ +export function defineProvider({ id, displayName, env, oAuthClient, }) { + return { + id, + displayName, + env, + oAuthClient, + }; +} +//# sourceMappingURL=provider.js.map \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/provider.js.map b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/provider.js.map new file mode 100644 index 0000000000..02fe380099 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../../server/auth/oauth/provider.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,cAAc,CAG5B,EACA,EAAE,EACF,WAAW,EACX,GAAG,EACH,WAAW,GAMZ;IACC,OAAO;QACL,EAAE;QACF,WAAW;QACX,GAAG;QACH,WAAW;KACZ,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/providers/google.d.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/providers/google.d.ts new file mode 100644 index 0000000000..7910449649 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/providers/google.d.ts @@ -0,0 +1,7 @@ +import { Google } from "arctic"; +export declare const google: { + id: string; + displayName: string; + env: Record<"GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET", string>; + oAuthClient: Google; +}; diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/providers/google.js b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/providers/google.js new file mode 100644 index 0000000000..7a49678dec --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/providers/google.js @@ -0,0 +1,16 @@ +import { Google } from "arctic"; +import { ensureEnvVarsForProvider } from "../env.js"; +import { getRedirectUriForCallback } from "../redirect.js"; +import { defineProvider } from "../provider.js"; +const id = "google"; +const displayName = "Google"; +const env = ensureEnvVarsForProvider(["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"], displayName); +const oAuthClient = new Google(env.GOOGLE_CLIENT_ID, env.GOOGLE_CLIENT_SECRET, getRedirectUriForCallback(id).toString()); +// PUBLIC API +export const google = defineProvider({ + id, + displayName, + env, + oAuthClient, +}); +//# sourceMappingURL=google.js.map \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/providers/google.js.map b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/providers/google.js.map new file mode 100644 index 0000000000..1bebbd38aa --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/providers/google.js.map @@ -0,0 +1 @@ +{"version":3,"file":"google.js","sourceRoot":"","sources":["../../../../../server/auth/oauth/providers/google.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAG,MAAM,QAAQ,CAAC;AAEjC,OAAO,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEhD,MAAM,EAAE,GAAG,QAAQ,CAAC;AACpB,MAAM,WAAW,GAAG,QAAQ,CAAC;AAE7B,MAAM,GAAG,GAAG,wBAAwB,CAClC,CAAC,kBAAkB,EAAE,sBAAsB,CAAC,EAC5C,WAAW,CACZ,CAAC;AAEF,MAAM,WAAW,GAAG,IAAI,MAAM,CAC5B,GAAG,CAAC,gBAAgB,EACpB,GAAG,CAAC,oBAAoB,EACxB,yBAAyB,CAAC,EAAE,CAAC,CAAC,QAAQ,EAAE,CACzC,CAAC;AAEF,aAAa;AACb,MAAM,CAAC,MAAM,MAAM,GAAG,cAAc,CAAC;IACnC,EAAE;IACF,WAAW;IACX,GAAG;IACH,WAAW;CACZ,CAAC,CAAC"} \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/redirect.d.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/redirect.d.ts new file mode 100644 index 0000000000..cb65431704 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/redirect.d.ts @@ -0,0 +1,6 @@ +export declare const loginPath = "login"; +export declare const exchangeCodeForTokenPath = "exchange-code"; +export declare const callbackPath = "callback"; +export declare function getRedirectUriForOneTimeCode(oneTimeCode: string): URL; +export declare function handleOAuthErrorAndGetRedirectUri(error: unknown): URL; +export declare function getRedirectUriForCallback(providerName: string): URL; diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/redirect.js b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/redirect.js new file mode 100644 index 0000000000..c228948ef6 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/redirect.js @@ -0,0 +1,34 @@ +import { config, HttpError } from '../../index.js'; +// PRIVATE API (server) +export const loginPath = 'login'; +// PRIVATE API (server) +export const exchangeCodeForTokenPath = 'exchange-code'; +// PRIVATE API (server) +export const callbackPath = 'callback'; +const clientOAuthCallbackPath = '/oauth/callback'; +// PRIVATE API (server) +export function getRedirectUriForOneTimeCode(oneTimeCode) { + return new URL(`${config.frontendUrl}${clientOAuthCallbackPath}#${oneTimeCode}`); +} +// PRIVATE API (server) +export function handleOAuthErrorAndGetRedirectUri(error) { + if (error instanceof HttpError) { + const errorMessage = isHttpErrorWithExtraMessage(error) + ? `${error.message}: ${error.data.message}` + : error.message; + return getRedirectUriForError(errorMessage); + } + console.error("Unknown OAuth error:", error); + return getRedirectUriForError("An unknown error occurred while trying to log in with the OAuth provider."); +} +// PRIVATE API (SDK) +export function getRedirectUriForCallback(providerName) { + return new URL(`${config.serverUrl}/auth/${providerName}/${callbackPath}`); +} +function getRedirectUriForError(error) { + return new URL(`${config.frontendUrl}${clientOAuthCallbackPath}?error=${error}`); +} +function isHttpErrorWithExtraMessage(error) { + return error.data && typeof error.data.message === 'string'; +} +//# sourceMappingURL=redirect.js.map \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/redirect.js.map b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/redirect.js.map new file mode 100644 index 0000000000..d8e07016ca --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/dist/server/auth/oauth/redirect.js.map @@ -0,0 +1 @@ +{"version":3,"file":"redirect.js","sourceRoot":"","sources":["../../../../server/auth/oauth/redirect.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAElD,uBAAuB;AACvB,MAAM,CAAC,MAAM,SAAS,GAAG,OAAO,CAAA;AAEhC,uBAAuB;AACvB,MAAM,CAAC,MAAM,wBAAwB,GAAG,eAAe,CAAA;AAEvD,uBAAuB;AACvB,MAAM,CAAC,MAAM,YAAY,GAAG,UAAU,CAAA;AAEtC,MAAM,uBAAuB,GAAG,iBAAiB,CAAA;AAEjD,uBAAuB;AACvB,MAAM,UAAU,4BAA4B,CAAC,WAAmB;IAC9D,OAAO,IAAI,GAAG,CAAC,GAAG,MAAM,CAAC,WAAW,GAAG,uBAAuB,IAAI,WAAW,EAAE,CAAC,CAAC;AACnF,CAAC;AAED,uBAAuB;AACvB,MAAM,UAAU,iCAAiC,CAAC,KAAc;IAC9D,IAAI,KAAK,YAAY,SAAS,EAAE,CAAC;QAC/B,MAAM,YAAY,GAAG,2BAA2B,CAAC,KAAK,CAAC;YACrD,CAAC,CAAC,GAAG,KAAK,CAAC,OAAO,KAAK,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE;YAC3C,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC;QAClB,OAAO,sBAAsB,CAAC,YAAY,CAAC,CAAA;IAC7C,CAAC;IACD,OAAO,CAAC,KAAK,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;IAC7C,OAAO,sBAAsB,CAAC,2EAA2E,CAAC,CAAC;AAC7G,CAAC;AAED,oBAAoB;AACpB,MAAM,UAAU,yBAAyB,CAAC,YAAoB;IAC5D,OAAO,IAAI,GAAG,CAAC,GAAG,MAAM,CAAC,SAAS,SAAS,YAAY,IAAI,YAAY,EAAE,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,sBAAsB,CAAC,KAAa;IAC3C,OAAO,IAAI,GAAG,CAAC,GAAG,MAAM,CAAC,WAAW,GAAG,uBAAuB,UAAU,KAAK,EAAE,CAAC,CAAC;AACnF,CAAC;AAED,SAAS,2BAA2B,CAAC,KAAgB;IACnD,OAAO,KAAK,CAAC,IAAI,IAAI,OAAQ,KAAK,CAAC,IAAY,CAAC,OAAO,KAAK,QAAQ,CAAC;AACvE,CAAC"} \ No newline at end of file diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/package.json b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/package.json index e7f004defe..1c88afb5bf 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/package.json +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/package.json @@ -11,6 +11,7 @@ "@types/express-serve-static-core": "^4.17.13", "@types/react-router-dom": "^5.3.3", "@vitest/ui": "^1.2.1", + "arctic": "^1.2.1", "axios": "^1.4.0", "express": "~4.18.1", "jsdom": "^21.1.1", diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/hooks.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/hooks.ts index a3754e7f6a..bb61fe8b95 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/hooks.ts +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/hooks.ts @@ -35,7 +35,7 @@ export type OnAfterLoginHook = ( export type InternalAuthHookParams = { /** * Prisma instance that can be used to interact with the database. - */ + */ prisma: typeof prisma } @@ -48,86 +48,91 @@ export type InternalAuthHookParams = { type OnBeforeSignupHookParams = { /** * Provider ID object that contains the provider name and the provide user ID. - */ + */ providerId: ProviderId /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest } & InternalAuthHookParams type OnAfterSignupHookParams = { /** * Provider ID object that contains the provider name and the provide user ID. - */ + */ providerId: ProviderId /** * User object that was created during the signup process. - */ + */ user: Awaited> - oauth?: { - /** - * Access token that was received during the OAuth flow. - */ - accessToken: string - /** - * Unique request ID that was generated during the OAuth flow. - */ - uniqueRequestId: string - }, + /** + * OAuth flow data that was generated during the OAuth flow. This is only + * available if the user signed up using OAuth. + */ + oauth?: OAuthData /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest } & InternalAuthHookParams type OnBeforeOAuthRedirectHookParams = { /** * URL that the OAuth flow should redirect to. - */ + */ url: URL /** * Unique request ID that was generated during the OAuth flow. - */ - uniqueRequestId: string + */ + oauth: Pick /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest } & InternalAuthHookParams type OnBeforeLoginHookParams = { /** * Provider ID object that contains the provider name and the provide user ID. - */ + */ providerId: ProviderId + /** + * User that is trying to log in. + */ + user: Awaited>['user'] /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest } & InternalAuthHookParams type OnAfterLoginHookParams = { /** * Provider ID object that contains the provider name and the provide user ID. - */ + */ providerId: ProviderId - oauth?: { - /** - * Access token that was received during the OAuth flow. - */ - accessToken: string - /** - * Unique request ID that was generated during the OAuth flow. - */ - uniqueRequestId: string - }, /** * User that is logged in. - */ + */ user: Awaited>['user'] + /** + * OAuth flow data that was generated during the OAuth flow. This is only + * available if the user logged in using OAuth. + */ + oauth?: OAuthData /** * Request object that can be used to access the incoming request. - */ + */ req: ExpressRequest } & InternalAuthHookParams + +// PUBLIC API +export type OAuthData = { + /** + * Unique request ID that was generated during the OAuth flow. + */ + uniqueRequestId: string +} & ( + | { providerName: 'google'; tokens: import('arctic').GoogleTokens } + | never +) diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/index.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/index.ts index 15b3c36b07..117225dae7 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/index.ts +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/index.ts @@ -29,6 +29,9 @@ export type { OnBeforeLoginHook, OnAfterLoginHook, InternalAuthHookParams, + OAuthData, } from './hooks.js' +export * from './oauth/index.js' + diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/env.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/env.ts similarity index 74% rename from waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/env.ts rename to waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/env.ts index 24776c6dd3..ada2452b8e 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/env.ts +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/env.ts @@ -1,14 +1,13 @@ -import { type ProviderConfig } from "wasp/auth/providers/types"; - +// PRIVATE API (SDK) export function ensureEnvVarsForProvider( envVarNames: EnvVarName[], - provider: ProviderConfig, + providerName: string, ): Record { const result: Record = {}; for (const envVarName of envVarNames) { const value = process.env[envVarName]; if (!value) { - throw new Error(`${envVarName} env variable is required when using the ${provider.displayName} auth provider.`); + throw new Error(`${envVarName} env variable is required when using the ${providerName} auth provider.`); } result[envVarName] = value; } diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/index.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/index.ts new file mode 100644 index 0000000000..a63e4264fb --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/index.ts @@ -0,0 +1,16 @@ +// PUBLIC API +export { google } from './providers/google.js'; + +// PRIVATE API +export { + loginPath, + callbackPath, + exchangeCodeForTokenPath, + handleOAuthErrorAndGetRedirectUri, + getRedirectUriForOneTimeCode, +} from './redirect.js' + +// PRIVATE API +export { + tokenStore, +} from './oneTimeCode.js' diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/oneTimeCode.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/oneTimeCode.ts new file mode 100644 index 0000000000..4f2d8ebb08 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/oneTimeCode.ts @@ -0,0 +1,50 @@ +import { createJWT, validateJWT, TimeSpan } from '../../../auth/jwt.js' + +export const tokenStore = createTokenStore(); + +function createTokenStore() { + const usedTokens = new Map(); + + const validFor = new TimeSpan(1, 'm') // 1 minute + const cleanupAfter = 1000 * 60 * 60; // 1 hour + + function createToken(userId: string): Promise { + return createJWT( + { + id: userId, + }, + { + expiresIn: validFor, + } + ); + } + + function verifyToken(token: string): Promise<{ id: string }> { + return validateJWT(token); + } + + function isUsed(token: string): boolean { + return usedTokens.has(token); + } + + function markUsed(token: string): void { + usedTokens.set(token, Date.now()); + cleanUp(); + } + + function cleanUp(): void { + const now = Date.now(); + for (const [token, timestamp] of usedTokens.entries()) { + if (now - timestamp > cleanupAfter) { + usedTokens.delete(token); + } + } + } + + return { + createToken, + verifyToken, + isUsed, + markUsed, + }; +} diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/provider.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/provider.ts new file mode 100644 index 0000000000..c2aee70897 --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/provider.ts @@ -0,0 +1,23 @@ +import { OAuth2Provider, OAuth2ProviderWithPKCE } from "arctic"; + +export function defineProvider< + OAuthClient extends OAuth2Provider | OAuth2ProviderWithPKCE, + Env extends Record +>({ + id, + displayName, + env, + oAuthClient, +}: { + id: string; + displayName: string; + env: Env; + oAuthClient: OAuthClient; +}) { + return { + id, + displayName, + env, + oAuthClient, + }; +} diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/providers/google.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/providers/google.ts new file mode 100644 index 0000000000..9f6aaf216c --- /dev/null +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/providers/google.ts @@ -0,0 +1,27 @@ +import { Google } from "arctic"; + +import { ensureEnvVarsForProvider } from "../env.js"; +import { getRedirectUriForCallback } from "../redirect.js"; +import { defineProvider } from "../provider.js"; + +const id = "google"; +const displayName = "Google"; + +const env = ensureEnvVarsForProvider( + ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"], + displayName, +); + +const oAuthClient = new Google( + env.GOOGLE_CLIENT_ID, + env.GOOGLE_CLIENT_SECRET, + getRedirectUriForCallback(id).toString(), +); + +// PUBLIC API +export const google = defineProvider({ + id, + displayName, + env, + oAuthClient, +}); diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/redirect.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/redirect.ts similarity index 86% rename from waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/redirect.ts rename to waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/redirect.ts index be677f0ff6..1eac920af7 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/redirect.ts +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/sdk/wasp/server/auth/oauth/redirect.ts @@ -1,19 +1,22 @@ -import { config } from 'wasp/server' -import { HttpError } from 'wasp/server' +import { config, HttpError } from '../../index.js' +// PRIVATE API (server) export const loginPath = 'login' -export const callbackPath = 'callback' + +// PRIVATE API (server) export const exchangeCodeForTokenPath = 'exchange-code' -const clientOAuthCallbackPath = '/oauth/callback' -export function getRedirectUriForCallback(providerName: string): URL { - return new URL(`${config.serverUrl}/auth/${providerName}/${callbackPath}`); -} +// PRIVATE API (server) +export const callbackPath = 'callback' +const clientOAuthCallbackPath = '/oauth/callback' + +// PRIVATE API (server) export function getRedirectUriForOneTimeCode(oneTimeCode: string): URL { return new URL(`${config.frontendUrl}${clientOAuthCallbackPath}#${oneTimeCode}`); } +// PRIVATE API (server) export function handleOAuthErrorAndGetRedirectUri(error: unknown): URL { if (error instanceof HttpError) { const errorMessage = isHttpErrorWithExtraMessage(error) @@ -25,6 +28,11 @@ export function handleOAuthErrorAndGetRedirectUri(error: unknown): URL { return getRedirectUriForError("An unknown error occurred while trying to log in with the OAuth provider."); } +// PRIVATE API (SDK) +export function getRedirectUriForCallback(providerName: string): URL { + return new URL(`${config.serverUrl}/auth/${providerName}/${callbackPath}`); +} + function getRedirectUriForError(error: string): URL { return new URL(`${config.frontendUrl}${clientOAuthCallbackPath}?error=${error}`); } diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/package.json b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/package.json index c857d727d6..3a4ce1d6b9 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/package.json +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/package.json @@ -1,7 +1,6 @@ { "comment-filip": "The server.js location changed because we have now included client source files above .wasp/out/server/src.", "dependencies": { - "arctic": "^1.2.1", "cookie-parser": "~1.4.6", "cors": "^2.8.5", "dotenv": "16.0.2", diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/config/google.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/config/google.ts index dae5b818a6..3358c5ada4 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/config/google.ts +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/config/google.ts @@ -1,8 +1,6 @@ -import { Google } from "arctic"; - import type { ProviderConfig } from "wasp/auth/providers/types"; -import { getRedirectUriForCallback } from "../oauth/redirect.js"; -import { ensureEnvVarsForProvider } from "../oauth/env.js"; +import { google } from "wasp/server/auth"; + import { mergeDefaultAndUserConfig } from "../oauth/config.js"; import { createOAuthProviderRouter } from "../oauth/handler.js"; @@ -10,20 +8,9 @@ const _waspUserSignupFields = undefined const _waspUserDefinedConfigFn = undefined const _waspConfig: ProviderConfig = { - id: "google", - displayName: "Google", + id: google.id, + displayName: google.displayName, createRouter(provider) { - const env = ensureEnvVarsForProvider( - ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"], - provider - ); - - const google = new Google( - env.GOOGLE_CLIENT_ID, - env.GOOGLE_CLIENT_SECRET, - getRedirectUriForCallback(provider.id).toString(), - ); - const config = mergeDefaultAndUserConfig({ scopes: ['profile'], }, _waspUserDefinedConfigFn); @@ -55,8 +42,8 @@ const _waspConfig: ProviderConfig = { provider, oAuthType: 'OAuth2WithPKCE', userSignupFields: _waspUserSignupFields, - getAuthorizationUrl: ({ state, codeVerifier }) => google.createAuthorizationURL(state, codeVerifier, config), - getProviderTokens: ({ code, codeVerifier }) => google.validateAuthorizationCode(code, codeVerifier), + getAuthorizationUrl: ({ state, codeVerifier }) => google.oAuthClient.createAuthorizationURL(state, codeVerifier, config), + getProviderTokens: ({ code, codeVerifier }) => google.oAuthClient.validateAuthorizationCode(code, codeVerifier), getProviderInfo: ({ accessToken }) => getGoogleProfile(accessToken), }); }, diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/handler.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/handler.ts index 869052d7ac..ec02cf5a67 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/handler.ts +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/handler.ts @@ -6,7 +6,6 @@ import { type UserSignupFields, type ProviderConfig, } from 'wasp/auth/providers/types' - import { type OAuthType, type OAuthStateFor, @@ -19,10 +18,11 @@ import { callbackPath, loginPath, handleOAuthErrorAndGetRedirectUri, -} from './redirect.js' +} from 'wasp/server/auth' +import { OAuthData } from 'wasp/server/auth' import { onBeforeOAuthRedirectHook } from '../../hooks.js' -export function createOAuthProviderRouter({ +export function createOAuthProviderRouter({ provider, oAuthType, userSignupFields, @@ -51,14 +51,12 @@ export function createOAuthProviderRouter({ */ getProviderTokens: ( oAuthState: OAuthStateWithCodeFor, - ) => Promise<{ - accessToken: string - }> + ) => Promise /* The function that returns the user's profile and ID using the access token. */ - getProviderInfo: ({ accessToken }: { accessToken: string }) => Promise<{ + getProviderInfo: (tokens: Tokens) => Promise<{ providerUserId: string providerProfile: unknown }> @@ -77,7 +75,7 @@ export function createOAuthProviderRouter({ const { url: redirectUrlAfterHook } = await onBeforeOAuthRedirectHook({ req, url: redirectUrl, - uniqueRequestId: oAuthState.state, + oauth: { uniqueRequestId: oAuthState.state } }) return redirect(res, redirectUrlAfterHook.toString()) }), @@ -92,11 +90,9 @@ export function createOAuthProviderRouter({ provider, req, }) - const { accessToken } = await getProviderTokens(oAuthState) + const tokens = await getProviderTokens(oAuthState) - const { providerProfile, providerUserId } = await getProviderInfo({ - accessToken, - }) + const { providerProfile, providerUserId } = await getProviderInfo(tokens) try { const redirectUri = await finishOAuthFlowAndGetRedirectUri({ provider, @@ -104,8 +100,17 @@ export function createOAuthProviderRouter({ providerUserId, userSignupFields, req, - accessToken, - oAuthState, + oauth: { + uniqueRequestId: oAuthState.state, + // OAuth params are built as a discriminated union + // of provider names and their respective tokens. + // We are using a generic ProviderConfig and tokens type + // is inferred from the getProviderTokens function. + // Instead of building complex TS machinery to ensure that + // the providerName and tokens match, we are using any here. + providerName: provider.id as any, + tokens, + }, }) // Redirect to the client with the one time code return redirect(res, redirectUri.toString()) diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/oneTimeCode.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/oneTimeCode.ts index 0b98a1d879..cf1410c10f 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/oneTimeCode.ts +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/oneTimeCode.ts @@ -2,12 +2,9 @@ import { Router } from "express"; import { HttpError } from 'wasp/server'; import { handleRejection } from 'wasp/server/utils' -import { createJWT, validateJWT, TimeSpan } from 'wasp/auth/jwt' import { findAuthWithUserBy } from 'wasp/auth/utils' import { createSession } from 'wasp/auth/session' -import { exchangeCodeForTokenPath } from "./redirect.js"; - -export const tokenStore = createTokenStore(); +import { exchangeCodeForTokenPath, tokenStore } from "wasp/server/auth"; export function setupOneTimeCodeRoute(router: Router) { router.post( @@ -40,50 +37,3 @@ export function setupOneTimeCodeRoute(router: Router) { }) ); } - -function createTokenStore() { - const usedTokens = new Map(); - - const validFor = new TimeSpan(1, 'm') // 1 minute - const cleanupAfter = 1000 * 60 * 60; // 1 hour - - function createToken(userId: string): Promise { - return createJWT( - { - id: userId, - }, - { - expiresIn: validFor, - } - ); - } - - function verifyToken(token: string): Promise<{ id: string }> { - return validateJWT(token); - } - - function isUsed(token: string): boolean { - return usedTokens.has(token); - } - - function markUsed(token: string): void { - usedTokens.set(token, Date.now()); - cleanUp(); - } - - function cleanUp(): void { - const now = Date.now(); - for (const [token, timestamp] of usedTokens.entries()) { - if (now - timestamp > cleanupAfter) { - usedTokens.delete(token); - } - } - } - - return { - createToken, - verifyToken, - isUsed, - markUsed, - }; -} diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/user.ts b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/user.ts index ac7abc0121..c252b60f1a 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/user.ts +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/.wasp/out/server/src/auth/providers/oauth/user.ts @@ -10,8 +10,8 @@ import { import { type Auth } from 'wasp/entities' import { prisma } from 'wasp/server' import { type UserSignupFields, type ProviderConfig } from 'wasp/auth/providers/types' -import { getRedirectUriForOneTimeCode } from './redirect' -import { tokenStore } from './oneTimeCode' +import { type OAuthData } from 'wasp/server/auth' +import { getRedirectUriForOneTimeCode, tokenStore } from 'wasp/server/auth' import { onBeforeSignupHook, onAfterSignupHook, @@ -25,16 +25,14 @@ export async function finishOAuthFlowAndGetRedirectUri({ providerUserId, userSignupFields, req, - accessToken, - oAuthState, + oauth }: { provider: ProviderConfig; providerProfile: unknown; providerUserId: string; userSignupFields: UserSignupFields | undefined; req: ExpressRequest; - accessToken: string; - oAuthState: { state: string }; + oauth: OAuthData; }): Promise { const providerId = createProviderId(provider.id, providerUserId); @@ -43,8 +41,7 @@ export async function finishOAuthFlowAndGetRedirectUri({ providerProfile, userSignupFields, req, - accessToken, - oAuthState, + oauth, }); const oneTimeCode = await tokenStore.createToken(authId) @@ -59,15 +56,13 @@ async function getAuthIdFromProviderDetails({ providerProfile, userSignupFields, req, - accessToken, - oAuthState, + oauth, }: { providerId: ProviderId; providerProfile: any; userSignupFields: UserSignupFields | undefined; req: ExpressRequest; - accessToken: string; - oAuthState: { state: string }; + oauth: OAuthData; }): Promise { const existingAuthIdentity = await prisma.authIdentity.findUnique({ where: { @@ -85,26 +80,27 @@ async function getAuthIdFromProviderDetails({ if (existingAuthIdentity) { const authId = existingAuthIdentity.auth.id + // NOTE: Fetching the user to pass it to the login hooks - it's a bit wasteful + // but we wanted to keep the onAfterLoginHook params consistent for all auth providers. + const auth = await findAuthWithUserBy({ id: authId }) + // NOTE: We are calling login hooks here even though we didn't log in the user yet. // It's because we have access to the OAuth tokens here and we want to pass them to the hooks. // We could have stored the tokens temporarily and called the hooks after the session is created, // but this keeps the implementation simpler. // The downside of this approach is that we can't provide the session to the login hooks, but this is // an okay trade-off because OAuth tokens are more valuable to users than the session ID. - await onBeforeLoginHook({ req, providerId }) - - // NOTE: Fetching the user to pass it to the onAfterLoginHook - it's a bit wasteful - // but we wanted to keep the onAfterLoginHook params consistent for all auth providers. - const auth = await findAuthWithUserBy({ id: authId }) + await onBeforeLoginHook({ + req, + providerId, + user: auth.user, + }) // NOTE: check the comment above onBeforeLoginHook for the explanation why we call onAfterLoginHook here. await onAfterLoginHook({ req, providerId, - oauth: { - accessToken, - uniqueRequestId: oAuthState.state, - }, + oauth, user: auth.user, }) @@ -130,10 +126,7 @@ async function getAuthIdFromProviderDetails({ req, providerId, user, - oauth: { - accessToken, - uniqueRequestId: oAuthState.state, - }, + oauth, }) return user.auth.id diff --git a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/main.wasp b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/main.wasp index 91b9f55274..4148dd52a2 100644 --- a/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/main.wasp +++ b/waspc/e2e-test/test-outputs/waspComplexTest-golden/waspComplexTest/main.wasp @@ -1,6 +1,6 @@ app waspComplexTest { wasp: { - version: "^0.14.0" + version: "^0.14.1" }, auth: { userEntity: User, diff --git a/waspc/e2e-test/test-outputs/waspJob-golden/waspJob/main.wasp b/waspc/e2e-test/test-outputs/waspJob-golden/waspJob/main.wasp index 8e24bfcb6f..1deb5bca3a 100644 --- a/waspc/e2e-test/test-outputs/waspJob-golden/waspJob/main.wasp +++ b/waspc/e2e-test/test-outputs/waspJob-golden/waspJob/main.wasp @@ -1,6 +1,6 @@ app waspJob { wasp: { - version: "^0.14.0" + version: "^0.14.1" }, title: "waspJob" } diff --git a/waspc/e2e-test/test-outputs/waspMigrate-golden/waspMigrate/main.wasp b/waspc/e2e-test/test-outputs/waspMigrate-golden/waspMigrate/main.wasp index 79f0eb6743..d2692a3560 100644 --- a/waspc/e2e-test/test-outputs/waspMigrate-golden/waspMigrate/main.wasp +++ b/waspc/e2e-test/test-outputs/waspMigrate-golden/waspMigrate/main.wasp @@ -1,6 +1,6 @@ app waspMigrate { wasp: { - version: "^0.14.0" + version: "^0.14.1" }, title: "waspMigrate" } diff --git a/waspc/e2e-test/test-outputs/waspNew-golden/waspNew/main.wasp b/waspc/e2e-test/test-outputs/waspNew-golden/waspNew/main.wasp index 40033d108b..5ea5f45250 100644 --- a/waspc/e2e-test/test-outputs/waspNew-golden/waspNew/main.wasp +++ b/waspc/e2e-test/test-outputs/waspNew-golden/waspNew/main.wasp @@ -1,6 +1,6 @@ app waspNew { wasp: { - version: "^0.14.0" + version: "^0.14.1" }, title: "waspNew" } diff --git a/waspc/examples/todoApp/package-lock.json b/waspc/examples/todoApp/package-lock.json index 13fa2f5ee7..4a6b12809d 100644 --- a/waspc/examples/todoApp/package-lock.json +++ b/waspc/examples/todoApp/package-lock.json @@ -35,6 +35,7 @@ "@types/express-serve-static-core": "^4.17.13", "@types/react-router-dom": "^5.3.3", "@vitest/ui": "^1.2.1", + "arctic": "^1.2.1", "autoprefixer": "^10.4.13", "axios": "^1.4.0", "express": "~4.18.1", @@ -3042,6 +3043,501 @@ "node": ">= 8" } }, + "node_modules/arctic": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/arctic/-/arctic-1.9.2.tgz", + "integrity": "sha512-VTnGpYx+ypboJdNrWnK17WeD7zN/xSCHnpecd5QYsBfVZde/5i+7DJ1wrf/ioSDMiEjagXmyNWAE3V2C9f1hNg==", + "dependencies": { + "oslo": "1.2.0" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2/-/argon2-1.7.0.tgz", + "integrity": "sha512-zfULc+/tmcWcxn+nHkbyY8vP3+MpEqKORbszt4UkpqZgBgDAAIYvuDN/zukfTgdmo6tmJKKVfzigZOPk4LlIog==", + "engines": { + "node": ">= 10" + }, + "optionalDependencies": { + "@node-rs/argon2-android-arm-eabi": "1.7.0", + "@node-rs/argon2-android-arm64": "1.7.0", + "@node-rs/argon2-darwin-arm64": "1.7.0", + "@node-rs/argon2-darwin-x64": "1.7.0", + "@node-rs/argon2-freebsd-x64": "1.7.0", + "@node-rs/argon2-linux-arm-gnueabihf": "1.7.0", + "@node-rs/argon2-linux-arm64-gnu": "1.7.0", + "@node-rs/argon2-linux-arm64-musl": "1.7.0", + "@node-rs/argon2-linux-x64-gnu": "1.7.0", + "@node-rs/argon2-linux-x64-musl": "1.7.0", + "@node-rs/argon2-wasm32-wasi": "1.7.0", + "@node-rs/argon2-win32-arm64-msvc": "1.7.0", + "@node-rs/argon2-win32-ia32-msvc": "1.7.0", + "@node-rs/argon2-win32-x64-msvc": "1.7.0" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-android-arm-eabi": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-android-arm-eabi/-/argon2-android-arm-eabi-1.7.0.tgz", + "integrity": "sha512-udDqkr5P9E+wYX1SZwAVPdyfYvaF4ry9Tm+R9LkfSHbzWH0uhU6zjIwNRp7m+n4gx691rk+lqqDAIP8RLKwbhg==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-android-arm64": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-android-arm64/-/argon2-android-arm64-1.7.0.tgz", + "integrity": "sha512-s9j/G30xKUx8WU50WIhF0fIl1EdhBGq0RQ06lEhZ0Gi0ap8lhqbE2Bn5h3/G2D1k0Dx+yjeVVNmt/xOQIRG38A==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-darwin-arm64": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-darwin-arm64/-/argon2-darwin-arm64-1.7.0.tgz", + "integrity": "sha512-ZIz4L6HGOB9U1kW23g+m7anGNuTZ0RuTw0vNp3o+2DWpb8u8rODq6A8tH4JRL79S+Co/Nq608m9uackN2pe0Rw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-darwin-x64": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-darwin-x64/-/argon2-darwin-x64-1.7.0.tgz", + "integrity": "sha512-5oi/pxqVhODW/pj1+3zElMTn/YukQeywPHHYDbcAW3KsojFjKySfhcJMd1DjKTc+CHQI+4lOxZzSUzK7mI14Hw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-freebsd-x64": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-freebsd-x64/-/argon2-freebsd-x64-1.7.0.tgz", + "integrity": "sha512-Ify08683hA4QVXYoIm5SUWOY5DPIT/CMB0CQT+IdxQAg/F+qp342+lUkeAtD5bvStQuCx/dFO3bnnzoe2clMhA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-linux-arm-gnueabihf": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-arm-gnueabihf/-/argon2-linux-arm-gnueabihf-1.7.0.tgz", + "integrity": "sha512-7DjDZ1h5AUHAtRNjD19RnQatbhL+uuxBASuuXIBu4/w6Dx8n7YPxwTP4MXfsvuRgKuMWiOb/Ub/HJ3kXVCXRkg==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-linux-arm64-gnu": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-arm64-gnu/-/argon2-linux-arm64-gnu-1.7.0.tgz", + "integrity": "sha512-nJDoMP4Y3YcqGswE4DvP080w6O24RmnFEDnL0emdI8Nou17kNYBzP2546Nasx9GCyLzRcYQwZOUjrtUuQ+od2g==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-linux-arm64-musl": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-arm64-musl/-/argon2-linux-arm64-musl-1.7.0.tgz", + "integrity": "sha512-BKWS8iVconhE3jrb9mj6t1J9vwUqQPpzCbUKxfTGJfc+kNL58F1SXHBoe2cDYGnHrFEHTY0YochzXoAfm4Dm/A==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-linux-x64-gnu": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-x64-gnu/-/argon2-linux-x64-gnu-1.7.0.tgz", + "integrity": "sha512-EmgqZOlf4Jurk/szW1iTsVISx25bKksVC5uttJDUloTgsAgIGReCpUUO1R24pBhu9ESJa47iv8NSf3yAfGv6jQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-linux-x64-musl": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-x64-musl/-/argon2-linux-x64-musl-1.7.0.tgz", + "integrity": "sha512-/o1efYCYIxjfuoRYyBTi2Iy+1iFfhqHCvvVsnjNSgO1xWiWrX0Rrt/xXW5Zsl7vS2Y+yu8PL8KFWRzZhaVxfKA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-wasm32-wasi": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-wasm32-wasi/-/argon2-wasm32-wasi-1.7.0.tgz", + "integrity": "sha512-Evmk9VcxqnuwQftfAfYEr6YZYSPLzmKUsbFIMep5nTt9PT4XYRFAERj7wNYp+rOcBenF3X4xoB+LhwcOMTNE5w==", + "cpu": [ + "wasm32" + ], + "optional": true, + "dependencies": { + "@emnapi/core": "^0.45.0", + "@emnapi/runtime": "^0.45.0", + "@tybys/wasm-util": "^0.8.1", + "memfs-browser": "^3.4.13000" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-win32-arm64-msvc": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-win32-arm64-msvc/-/argon2-win32-arm64-msvc-1.7.0.tgz", + "integrity": "sha512-qgsU7T004COWWpSA0tppDqDxbPLgg8FaU09krIJ7FBl71Sz8SFO40h7fDIjfbTT5w7u6mcaINMQ5bSHu75PCaA==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-win32-ia32-msvc": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-win32-ia32-msvc/-/argon2-win32-ia32-msvc-1.7.0.tgz", + "integrity": "sha512-JGafwWYQ/HpZ3XSwP4adQ6W41pRvhcdXvpzIWtKvX+17+xEXAe2nmGWM6s27pVkg1iV2ZtoYLRDkOUoGqZkCcg==", + "cpu": [ + "ia32" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/argon2-win32-x64-msvc": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-win32-x64-msvc/-/argon2-win32-x64-msvc-1.7.0.tgz", + "integrity": "sha512-9oq4ShyFakw8AG3mRls0AoCpxBFcimYx7+jvXeAf2OqKNO+mSA6eZ9z7KQeVCi0+SOEUYxMGf5UiGiDb9R6+9Q==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt/-/bcrypt-1.9.0.tgz", + "integrity": "sha512-u2OlIxW264bFUfvbFqDz9HZKFjwe8FHFtn7T/U8mYjPZ7DWYpbUB+/dkW/QgYfMSfR0ejkyuWaBBe0coW7/7ig==", + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "optionalDependencies": { + "@node-rs/bcrypt-android-arm-eabi": "1.9.0", + "@node-rs/bcrypt-android-arm64": "1.9.0", + "@node-rs/bcrypt-darwin-arm64": "1.9.0", + "@node-rs/bcrypt-darwin-x64": "1.9.0", + "@node-rs/bcrypt-freebsd-x64": "1.9.0", + "@node-rs/bcrypt-linux-arm-gnueabihf": "1.9.0", + "@node-rs/bcrypt-linux-arm64-gnu": "1.9.0", + "@node-rs/bcrypt-linux-arm64-musl": "1.9.0", + "@node-rs/bcrypt-linux-x64-gnu": "1.9.0", + "@node-rs/bcrypt-linux-x64-musl": "1.9.0", + "@node-rs/bcrypt-wasm32-wasi": "1.9.0", + "@node-rs/bcrypt-win32-arm64-msvc": "1.9.0", + "@node-rs/bcrypt-win32-ia32-msvc": "1.9.0", + "@node-rs/bcrypt-win32-x64-msvc": "1.9.0" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-android-arm-eabi": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-android-arm-eabi/-/bcrypt-android-arm-eabi-1.9.0.tgz", + "integrity": "sha512-nOCFISGtnodGHNiLrG0WYLWr81qQzZKYfmwHc7muUeq+KY0sQXyHOwZk9OuNQAWv/lnntmtbwkwT0QNEmOyLvA==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-android-arm64": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-android-arm64/-/bcrypt-android-arm64-1.9.0.tgz", + "integrity": "sha512-+ZrIAtigVmjYkqZQTThHVlz0+TG6D+GDHWhVKvR2DifjtqJ0i+mb9gjo++hN+fWEQdWNGxKCiBBjwgT4EcXd6A==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-darwin-arm64": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-darwin-arm64/-/bcrypt-darwin-arm64-1.9.0.tgz", + "integrity": "sha512-CQiS+F9Pa0XozvkXR1g7uXE9QvBOPOplDg0iCCPRYTN9PqA5qYxhwe48G3o+v2UeQceNRrbnEtWuANm7JRqIhw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-darwin-x64": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-darwin-x64/-/bcrypt-darwin-x64-1.9.0.tgz", + "integrity": "sha512-4pTKGawYd7sNEjdJ7R/R67uwQH1VvwPZ0SSUMmeNHbxD5QlwAPXdDH11q22uzVXsvNFZ6nGQBg8No5OUGpx6Ug==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-freebsd-x64": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-freebsd-x64/-/bcrypt-freebsd-x64-1.9.0.tgz", + "integrity": "sha512-UmWzySX4BJhT/B8xmTru6iFif3h0Rpx3TqxRLCcbgmH43r7k5/9QuhpiyzpvKGpKHJCFNm4F3rC2wghvw5FCIg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-linux-arm-gnueabihf": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-linux-arm-gnueabihf/-/bcrypt-linux-arm-gnueabihf-1.9.0.tgz", + "integrity": "sha512-8qoX4PgBND2cVwsbajoAWo3NwdfJPEXgpCsZQZURz42oMjbGyhhSYbovBCskGU3EBLoC8RA2B1jFWooeYVn5BA==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-linux-arm64-gnu": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-linux-arm64-gnu/-/bcrypt-linux-arm64-gnu-1.9.0.tgz", + "integrity": "sha512-TuAC6kx0SbcIA4mSEWPi+OCcDjTQUMl213v5gMNlttF+D4ieIZx6pPDGTaMO6M2PDHTeCG0CBzZl0Lu+9b0c7Q==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-linux-arm64-musl": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-linux-arm64-musl/-/bcrypt-linux-arm64-musl-1.9.0.tgz", + "integrity": "sha512-/sIvKDABOI8QOEnLD7hIj02BVaNOuCIWBKvxcJOt8+TuwJ6zmY1UI5kSv9d99WbiHjTp97wtAUbZQwauU4b9ew==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-linux-x64-gnu": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-linux-x64-gnu/-/bcrypt-linux-x64-gnu-1.9.0.tgz", + "integrity": "sha512-DyyhDHDsLBsCKz1tZ1hLvUZSc1DK0FU0v52jK6IBQxrj24WscSU9zZe7ie/V9kdmA4Ep57BfpWX8Dsa2JxGdgQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-linux-x64-musl": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-linux-x64-musl/-/bcrypt-linux-x64-musl-1.9.0.tgz", + "integrity": "sha512-duIiuqQ+Lew8ASSAYm6ZRqcmfBGWwsi81XLUwz86a2HR7Qv6V4yc3ZAUQovAikhjCsIqe8C11JlAZSK6+PlXYg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-wasm32-wasi": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-wasm32-wasi/-/bcrypt-wasm32-wasi-1.9.0.tgz", + "integrity": "sha512-ylaGmn9Wjwv/D5lxtawttx3H6Uu2WTTR7lWlRHGT6Ga/MB1Vj4OjSGUW8G8zIVnKuXpGbZ92pgHlt4HUpSLctw==", + "cpu": [ + "wasm32" + ], + "optional": true, + "dependencies": { + "@emnapi/core": "^0.45.0", + "@emnapi/runtime": "^0.45.0", + "@tybys/wasm-util": "^0.8.1", + "memfs-browser": "^3.4.13000" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-win32-arm64-msvc": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-win32-arm64-msvc/-/bcrypt-win32-arm64-msvc-1.9.0.tgz", + "integrity": "sha512-2h86gF7QFyEzODuDFml/Dp1MSJoZjxJ4yyT2Erf4NkwsiA5MqowUhUsorRwZhX6+2CtlGa7orbwi13AKMsYndw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-win32-ia32-msvc": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-win32-ia32-msvc/-/bcrypt-win32-ia32-msvc-1.9.0.tgz", + "integrity": "sha512-kqxalCvhs4FkN0+gWWfa4Bdy2NQAkfiqq/CEf6mNXC13RSV673Ev9V8sRlQyNpCHCNkeXfOT9pgoBdJmMs9muA==", + "cpu": [ + "ia32" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/@node-rs/bcrypt-win32-x64-msvc": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@node-rs/bcrypt-win32-x64-msvc/-/bcrypt-win32-x64-msvc-1.9.0.tgz", + "integrity": "sha512-2y0Tuo6ZAT2Cz8V7DHulSlv1Bip3zbzeXyeur+uR25IRNYXKvI/P99Zl85Fbuu/zzYAZRLLlGTRe6/9IHofe/w==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/arctic/node_modules/oslo": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/oslo/-/oslo-1.2.0.tgz", + "integrity": "sha512-OoFX6rDsNcOQVAD2gQD/z03u4vEjWZLzJtwkmgfRF+KpQUXwdgEXErD7zNhyowmHwHefP+PM9Pw13pgpHMRlzw==", + "dependencies": { + "@node-rs/argon2": "1.7.0", + "@node-rs/bcrypt": "1.9.0" + } + }, "node_modules/arg": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", diff --git a/waspc/examples/todoApp/src/auth/hooks.ts b/waspc/examples/todoApp/src/auth/hooks.ts index 2bbbe416cd..8e4e6612a2 100644 --- a/waspc/examples/todoApp/src/auth/hooks.ts +++ b/waspc/examples/todoApp/src/auth/hooks.ts @@ -25,7 +25,7 @@ export const onAfterSignup: OnAfterSignupHook = async (args) => { // If this is a OAuth signup, we have access token and uniqueRequestId if (args.oauth) { - log('accessToken', args.oauth.accessToken) + log('accessToken', args.oauth.tokens.accessToken) log('uniqueRequestId', args.oauth.uniqueRequestId) const id = args.oauth.uniqueRequestId const query = oAuthQueryStore.get(id) @@ -43,7 +43,7 @@ export const onBeforeOAuthRedirect: OnBeforeOAuthRedirectHook = async ( log('query params before oAuth redirect', args.req.query) // Saving query params for later use in onAfterSignup hook - const id = args.uniqueRequestId + const id = args.oauth.uniqueRequestId oAuthQueryStore.set(id, args.req.query) return { url: args.url } @@ -58,8 +58,8 @@ export const onAfterLogin: OnAfterLoginHook = async (args) => { const log = createLoggerForHook('onAfterLogin') log('providerId object', args.providerId) log('user object', args.user) - if (args.oauth) { - log('accessToken', args.oauth.accessToken) + if (args.oauth && args.oauth.providerName === 'google') { + log('accessToken', args.oauth.tokens.accessToken) } } diff --git a/waspc/src/Wasp/Generator/SdkGenerator.hs b/waspc/src/Wasp/Generator/SdkGenerator.hs index eb066c1436..81a5f1f090 100644 --- a/waspc/src/Wasp/Generator/SdkGenerator.hs +++ b/waspc/src/Wasp/Generator/SdkGenerator.hs @@ -48,6 +48,7 @@ import Wasp.Generator.SdkGenerator.Server.AuthG (genNewServerApi) import Wasp.Generator.SdkGenerator.Server.CrudG (genNewServerCrudApi) import Wasp.Generator.SdkGenerator.Server.EmailSenderG (depsRequiredByEmail, genNewEmailSenderApi) import Wasp.Generator.SdkGenerator.Server.JobGenerator (depsRequiredByJobs, genNewJobsApi) +import Wasp.Generator.SdkGenerator.Server.OAuthG (depsRequiredByOAuth) import qualified Wasp.Generator.SdkGenerator.Server.OperationsGenerator as ServerOpsGen import Wasp.Generator.SdkGenerator.ServerApiG (genServerApi) import Wasp.Generator.SdkGenerator.WebSocketGenerator (depsRequiredByWebSockets, genWebSockets) @@ -196,6 +197,7 @@ npmDepsForSdk spec = ("@types/react-router-dom", "^5.3.3") ] ++ depsRequiredForAuth spec + ++ depsRequiredByOAuth spec -- This must be installed in the SDK because it lists prisma/client as a dependency. -- Installing it inside .wasp/out/server/node_modules would also -- install prisma/client in the same folder, which would cause our diff --git a/waspc/src/Wasp/Generator/SdkGenerator/AuthG.hs b/waspc/src/Wasp/Generator/SdkGenerator/AuthG.hs index 72712c70d8..40283b5ca1 100644 --- a/waspc/src/Wasp/Generator/SdkGenerator/AuthG.hs +++ b/waspc/src/Wasp/Generator/SdkGenerator/AuthG.hs @@ -19,6 +19,7 @@ import Wasp.Generator.SdkGenerator.Auth.EmailAuthG (genEmailAuth) import Wasp.Generator.SdkGenerator.Auth.LocalAuthG (genLocalAuth) import Wasp.Generator.SdkGenerator.Auth.OAuthAuthG (genOAuthAuth) import qualified Wasp.Generator.SdkGenerator.Common as C +import Wasp.Generator.SdkGenerator.Server.OAuthG (genOAuth) import Wasp.Generator.WebAppGenerator.Auth.Common (getOnAuthSucceededRedirectToOrDefault) import Wasp.Util ((<++>)) import qualified Wasp.Util as Util @@ -54,6 +55,7 @@ genAuth spec = genUtils auth, genProvidersTypes auth ] + <++> genOAuth auth <++> genIndexTs auth where maybeAuth = AS.App.auth $ snd $ getApp spec diff --git a/waspc/src/Wasp/Generator/SdkGenerator/Server/AuthG.hs b/waspc/src/Wasp/Generator/SdkGenerator/Server/AuthG.hs index 9689736115..4ca826c216 100644 --- a/waspc/src/Wasp/Generator/SdkGenerator/Server/AuthG.hs +++ b/waspc/src/Wasp/Generator/SdkGenerator/Server/AuthG.hs @@ -26,7 +26,7 @@ genNewServerApi spec = sequence [ genAuthIndex auth, genAuthUser auth, - genFileCopy [relfile|server/auth/hooks.ts|] + genHooks auth ] <++> genAuthEmail auth <++> genAuthUsername auth @@ -40,7 +40,12 @@ genAuthIndex auth = [relfile|server/auth/index.ts|] tmplData where - tmplData = AuthProviders.getEnabledAuthProvidersJson auth + tmplData = + object + [ "enabledProviders" .= AuthProviders.getEnabledAuthProvidersJson auth, + "isExternalAuthEnabled" .= isExternalAuthEnabled + ] + isExternalAuthEnabled = AS.Auth.isExternalAuthEnabled auth genAuthUser :: AS.Auth.Auth -> Generator FileDraft genAuthUser auth = @@ -61,6 +66,11 @@ genAuthUser auth = "enabledProviders" .= AuthProviders.getEnabledAuthProvidersJson auth ] +genHooks :: AS.Auth.Auth -> Generator FileDraft +genHooks auth = return $ C.mkTmplFdWithData [relfile|server/auth/hooks.ts|] tmplData + where + tmplData = object ["enabledProviders" .= AuthProviders.getEnabledAuthProvidersJson auth] + genAuthEmail :: AS.Auth.Auth -> Generator [FileDraft] genAuthEmail auth = if AS.Auth.isEmailAuthEnabled auth diff --git a/waspc/src/Wasp/Generator/SdkGenerator/Server/OAuthG.hs b/waspc/src/Wasp/Generator/SdkGenerator/Server/OAuthG.hs new file mode 100644 index 0000000000..fb533e22f1 --- /dev/null +++ b/waspc/src/Wasp/Generator/SdkGenerator/Server/OAuthG.hs @@ -0,0 +1,103 @@ +module Wasp.Generator.SdkGenerator.Server.OAuthG + ( genOAuth, + depsRequiredByOAuth, + ) +where + +import Data.Aeson (KeyValue ((.=)), object) +import Data.Maybe (fromJust, isJust) +import StrongPath (Dir', File', Path', Rel, reldir, relfile, ()) +import qualified StrongPath as SP +import Wasp.AppSpec (AppSpec) +import qualified Wasp.AppSpec.App as AS.App +import qualified Wasp.AppSpec.App.Auth as AS.App.Auth +import qualified Wasp.AppSpec.App.Auth as AS.Auth +import qualified Wasp.AppSpec.App.Dependency as AS.Dependency +import qualified Wasp.AppSpec.Valid as AS.Valid +import Wasp.Generator.AuthProviders (discordAuthProvider, getEnabledAuthProvidersJson, gitHubAuthProvider, googleAuthProvider, keycloakAuthProvider) +import Wasp.Generator.AuthProviders.OAuth + ( OAuthAuthProvider, + clientOAuthCallbackPath, + serverExchangeCodeForTokenHandlerPath, + serverOAuthCallbackHandlerPath, + serverOAuthLoginHandlerPath, + ) +import qualified Wasp.Generator.AuthProviders.OAuth as OAuth +import Wasp.Generator.FileDraft (FileDraft) +import Wasp.Generator.Monad (Generator) +import Wasp.Generator.SdkGenerator.Common (SdkTemplatesDir) +import qualified Wasp.Generator.SdkGenerator.Common as C +import Wasp.Util ((<++>)) + +genOAuth :: AS.Auth.Auth -> Generator [FileDraft] +genOAuth auth + | AS.Auth.isExternalAuthEnabled auth = + sequence + [ genIndexTs auth, + genRedirectHelper, + genFileCopy $ oauthDirInSdkTemplatesDir [relfile|env.ts|], + genFileCopy $ oauthDirInSdkTemplatesDir [relfile|oneTimeCode.ts|], + genFileCopy $ oauthDirInSdkTemplatesDir [relfile|provider.ts|] + ] + <++> genOAuthProvider discordAuthProvider (AS.Auth.discord . AS.Auth.methods $ auth) + <++> genOAuthProvider googleAuthProvider (AS.Auth.google . AS.Auth.methods $ auth) + <++> genOAuthProvider keycloakAuthProvider (AS.Auth.keycloak . AS.Auth.methods $ auth) + <++> genOAuthProvider gitHubAuthProvider (AS.Auth.gitHub . AS.Auth.methods $ auth) + | otherwise = return [] + where + genFileCopy = return . C.mkTmplFd + +genIndexTs :: AS.Auth.Auth -> Generator FileDraft +genIndexTs auth = return $ C.mkTmplFdWithData tmplFile tmplData + where + tmplFile = oauthDirInSdkTemplatesDir [relfile|index.ts|] + tmplData = + object + [ "enabledProviders" .= getEnabledAuthProvidersJson auth + ] + +genRedirectHelper :: Generator FileDraft +genRedirectHelper = return $ C.mkTmplFdWithData tmplFile tmplData + where + tmplFile = oauthDirInSdkTemplatesDir [relfile|redirect.ts|] + tmplData = + object + [ "serverOAuthCallbackHandlerPath" .= serverOAuthCallbackHandlerPath, + "clientOAuthCallbackPath" .= clientOAuthCallbackPath, + "serverOAuthLoginHandlerPath" .= serverOAuthLoginHandlerPath, + "serverExchangeCodeForTokenHandlerPath" .= serverExchangeCodeForTokenHandlerPath + ] + +genOAuthProvider :: + OAuthAuthProvider -> + Maybe AS.Auth.ExternalAuthConfig -> + Generator [FileDraft] +genOAuthProvider provider maybeUserConfig + | isJust maybeUserConfig = sequence [genOAuthConfig provider] + | otherwise = return [] + +genOAuthConfig :: + OAuthAuthProvider -> + Generator FileDraft +genOAuthConfig provider = return $ C.mkTmplFdWithData tmplFile tmplData + where + tmplFile = oauthDirInSdkTemplatesDir [reldir|providers|] providerTsFile + tmplData = + object + [ "providerId" .= OAuth.providerId provider, + "displayName" .= OAuth.displayName provider + ] + + providerTsFile :: Path' (Rel ()) File' + providerTsFile = fromJust $ SP.parseRelFile $ providerId ++ ".ts" + + providerId = OAuth.providerId provider + +depsRequiredByOAuth :: AppSpec -> [AS.Dependency.Dependency] +depsRequiredByOAuth spec = + [AS.Dependency.make ("arctic", "^1.2.1") | (AS.App.Auth.isExternalAuthEnabled <$> maybeAuth) == Just True] + where + maybeAuth = AS.App.auth $ snd $ AS.Valid.getApp spec + +oauthDirInSdkTemplatesDir :: Path' (Rel SdkTemplatesDir) Dir' +oauthDirInSdkTemplatesDir = [reldir|server/auth/oauth|] diff --git a/waspc/src/Wasp/Generator/ServerGenerator.hs b/waspc/src/Wasp/Generator/ServerGenerator.hs index 7705473b61..d35c0446eb 100644 --- a/waspc/src/Wasp/Generator/ServerGenerator.hs +++ b/waspc/src/Wasp/Generator/ServerGenerator.hs @@ -44,7 +44,6 @@ import Wasp.Generator.FileDraft (FileDraft, createTextFileDraft) import Wasp.Generator.Monad (Generator) import qualified Wasp.Generator.NpmDependencies as N import Wasp.Generator.ServerGenerator.ApiRoutesG (genApis) -import Wasp.Generator.ServerGenerator.Auth.OAuthAuthG (depsRequiredByOAuth) import Wasp.Generator.ServerGenerator.AuthG (genAuth) import qualified Wasp.Generator.ServerGenerator.Common as C import Wasp.Generator.ServerGenerator.CrudG (genCrud) @@ -153,7 +152,6 @@ npmDepsForWasp spec = ("rate-limiter-flexible", "^2.4.1"), ("superjson", "^1.12.2") ] - ++ depsRequiredByOAuth spec ++ depsRequiredByWebSockets spec, N.waspDevDependencies = AS.Dependency.fromList diff --git a/waspc/src/Wasp/Generator/ServerGenerator/Auth/OAuthAuthG.hs b/waspc/src/Wasp/Generator/ServerGenerator/Auth/OAuthAuthG.hs index 789a2a03bf..a44da128ce 100644 --- a/waspc/src/Wasp/Generator/ServerGenerator/Auth/OAuthAuthG.hs +++ b/waspc/src/Wasp/Generator/ServerGenerator/Auth/OAuthAuthG.hs @@ -1,6 +1,5 @@ module Wasp.Generator.ServerGenerator.Auth.OAuthAuthG ( genOAuthAuth, - depsRequiredByOAuth, ) where @@ -19,26 +18,15 @@ import StrongPath (), ) import qualified StrongPath as SP -import Wasp.AppSpec (AppSpec) import qualified Wasp.AppSpec as AS -import qualified Wasp.AppSpec.App as AS.App -import qualified Wasp.AppSpec.App.Auth as AS.App.Auth import qualified Wasp.AppSpec.App.Auth as AS.Auth -import qualified Wasp.AppSpec.App.Dependency as App.Dependency -import Wasp.AppSpec.Valid (getApp) import Wasp.Generator.AuthProviders ( discordAuthProvider, gitHubAuthProvider, googleAuthProvider, keycloakAuthProvider, ) -import Wasp.Generator.AuthProviders.OAuth - ( OAuthAuthProvider, - clientOAuthCallbackPath, - serverExchangeCodeForTokenHandlerPath, - serverOAuthCallbackHandlerPath, - serverOAuthLoginHandlerPath, - ) +import Wasp.Generator.AuthProviders.OAuth (OAuthAuthProvider) import qualified Wasp.Generator.AuthProviders.OAuth as OAuth import qualified Wasp.Generator.DbGenerator.Auth as DbAuth import Wasp.Generator.FileDraft (FileDraft) @@ -64,11 +52,9 @@ genOAuthHelpers auth = sequence [ genTypes auth, genUser, - genRedirectHelpers, return $ C.mkSrcTmplFd [relfile|auth/providers/oauth/handler.ts|], return $ C.mkSrcTmplFd [relfile|auth/providers/oauth/state.ts|], return $ C.mkSrcTmplFd [relfile|auth/providers/oauth/cookies.ts|], - return $ C.mkSrcTmplFd [relfile|auth/providers/oauth/env.ts|], return $ C.mkSrcTmplFd [relfile|auth/providers/oauth/config.ts|], return $ C.mkSrcTmplFd [relfile|auth/providers/oauth/oneTimeCode.ts|] ] @@ -85,18 +71,6 @@ genUser = return $ C.mkTmplFdWithData tmplFile (Just tmplData) "userFieldOnAuthEntityName" .= (DbAuth.userFieldOnAuthEntityName :: String) ] -genRedirectHelpers :: Generator FileDraft -genRedirectHelpers = return $ C.mkTmplFdWithData tmplFile (Just tmplData) - where - tmplFile = C.srcDirInServerTemplatesDir [relfile|auth/providers/oauth/redirect.ts|] - tmplData = - object - [ "clientOAuthCallbackPath" .= clientOAuthCallbackPath, - "serverOAuthLoginHandlerPath" .= serverOAuthLoginHandlerPath, - "serverOAuthCallbackHandlerPath" .= serverOAuthCallbackHandlerPath, - "serverExchangeCodeForTokenHandlerPath" .= serverExchangeCodeForTokenHandlerPath - ] - genTypes :: AS.Auth.Auth -> Generator FileDraft genTypes auth = return $ C.mkTmplFdWithData tmplFile (Just tmplData) where @@ -144,9 +118,3 @@ genOAuthConfig provider maybeUserConfig pathToConfigTmpl = return $ C.mkTmplFdWi relPathFromAuthConfigToServerSrcDir :: Path Posix (Rel importLocation) (Dir C.ServerSrcDir) relPathFromAuthConfigToServerSrcDir = [reldirP|../../../|] - -depsRequiredByOAuth :: AppSpec -> [App.Dependency.Dependency] -depsRequiredByOAuth spec = - [App.Dependency.make ("arctic", "^1.2.1") | (AS.App.Auth.isExternalAuthEnabled <$> maybeAuth) == Just True] - where - maybeAuth = AS.App.auth $ snd $ getApp spec diff --git a/waspc/waspc.cabal b/waspc/waspc.cabal index ed91e620cf..1560cc70c6 100644 --- a/waspc/waspc.cabal +++ b/waspc/waspc.cabal @@ -6,7 +6,7 @@ cabal-version: 2.4 -- Consider using hpack, or maybe even hpack-dhall. name: waspc -version: 0.14.0 +version: 0.14.1 description: Please see the README on GitHub at homepage: https://github.com/wasp-lang/wasp/waspc#readme bug-reports: https://github.com/wasp-lang/wasp/issues @@ -311,6 +311,7 @@ library Wasp.Generator.SdkGenerator.CrudG Wasp.Generator.SdkGenerator.EmailSender.Providers Wasp.Generator.SdkGenerator.Server.AuthG + Wasp.Generator.SdkGenerator.Server.OAuthG Wasp.Generator.SdkGenerator.Server.CrudG Wasp.Generator.SdkGenerator.Server.EmailSenderG Wasp.Generator.SdkGenerator.Server.JobGenerator diff --git a/web/blog/2024-08-13-how-to-add-auth-with-lucia-to-your-react-nextjs-app.md b/web/blog/2024-08-13-how-to-add-auth-with-lucia-to-your-react-nextjs-app.md new file mode 100644 index 0000000000..4cc9fc8110 --- /dev/null +++ b/web/blog/2024-08-13-how-to-add-auth-with-lucia-to-your-react-nextjs-app.md @@ -0,0 +1,609 @@ +--- +title: 'How to Add Auth with Lucia to Your React/Next.js App - A Step by Step Guide' +authors: [lucaslima] +image: /img/lua-auth/lucia-auth-banner.png +tags: [webdev, tech, react, nextjs, tutorial] +--- + +import Link from '@docusaurus/Link'; +import useBaseUrl from '@docusaurus/useBaseUrl'; + +import InBlogCta from './components/InBlogCta'; +import WaspIntro from './_wasp-intro.md'; +import ImgWithCaption from './components/ImgWithCaption' + + + +Although authentication is one of the most common web app features, there are so many different ways to go about it, which makes it a very non-trivial task. In this post, I will share my personal experience using Lucia - a modern, framework-agnostic authentication library that has been getting, deservedly so, a lot of love from the community in recent months. + +First, I will demonstrate how you can implement it within your Next.js application through a step-by-step guide you can follow. It will require a fair amount of code and configuration, but the process itself is quite straightforward. + +Secondly, we’ll see how to achieve the same with [Wasp](https://wasp-lang.dev/) in just a few lines of code. Wasp is a batteries-included, full-stack framework for React & Node.js that uses Lucia under the hood to implement authentication. It runs fully on your infrastructure and is 100% open-source and free. + +![auth with Wasp](/img/lua-auth/comparison.png) + +## Why Lucia? + +When it comes to adding authentication to your applications, there are several popular solutions available. For instance, [Clerk](https://clerk.com/) offers a paid service, while [NextAuth.js](https://next-auth.js.org/) is an open-source solution alongside [Lucia](https://lucia-auth.com/), which has become quite popular recently. + +These tools provide robust features, but committing to third-party services — which not only adds another layer of complexity but also have paid tiers you have to keep an eye on — might be an overkill for a small project. In-house solutions keep things centralized but leave it to a developer to implement some of the mentioned features. + +In our case, Lucia has proved to be a perfect middle ground - it’s not a third-party service and does not require a dedicated infrastructure, but it also provides a very solid foundation that’s easy to build upon. + +Now, let’s dive into a step-by-step guide on how to implement your own authentication with Next.js and Lucia. + +### Step 1: Setting up Next.js + +First, create a new Next.js project: + +```bash +npx create-next-app@latest my-nextjs-app +cd my-nextjs-app +npm install +``` + +### Step 2: Install Lucia + +Next, install Lucia: + +```bash +npm install lucia +``` + +### Step 3: Set up Authentication + +Create an `auth` file in your project and add the necessary files for Lucia to be imported and initialized. It has a bunch of adapters for different databases, and you can check them all [here](https://lucia-auth.com/database/). In this example, we’re going to use SQLite: + +```jsx +// lib/auth.ts +import { Lucia } from "lucia"; +import { BetterSqlite3Adapter } from "@lucia-auth/adapter-sqlite"; + +const adapter = new BetterSQLite3Adapter(db); // your adapter + +export const lucia = new Lucia(adapter, { + sessionCookie: { + // this sets cookies with super long expiration + // since Next.js doesn't allow Lucia to extend cookie expiration when rendering pages + expires: false, + attributes: { + // set to `true` when using HTTPS + secure: process.env.NODE_ENV === "production" + } + } +}); + +// To get some good Typescript support, add this! +declare module "lucia" { + interface Register { + Lucia: typeof lucia; + } +} +``` + +### Step 4: Add User to DB + +Let’s add a database file to contain our schemas for now: + +```tsx title="lib/db.ts" +import sqlite from "better-sqlite3"; + +export const db = sqlite("main.db"); + +db.exec(`CREATE TABLE IF NOT EXISTS user ( + id TEXT NOT NULL PRIMARY KEY, + github_id INTEGER UNIQUE, + username TEXT NOT NULL +)`); + +db.exec(`CREATE TABLE IF NOT EXISTS session ( + id TEXT NOT NULL PRIMARY KEY, + expires_at INTEGER NOT NULL, + user_id TEXT NOT NULL, + FOREIGN KEY (user_id) REFERENCES user(id) +)`); + +export interface DatabaseUser { + id: string; + username: string; + github_id: number; +} +``` + +### Step 5: Implement Login and Signup + +To make this happen, we firstly have to create a GitHub OAuth app. This is relatively simple, you create it, add the necessary ENVs and callback URLs into your application and you’re good to go. You can [follow GitHub docs](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app) to check how to do that. + +```tsx title=".env.local" +GITHUB_CLIENT_ID=your-github-client-id +GITHUB_CLIENT_SECRET=your-github-client-secret +``` + +After that, it’s a matter of adding login and signup functionalities to your pages, so, let’s do that real quick: + +```tsx title="login/page.tsx" +import { validateRequest } from "@/lib/auth"; +import { redirect } from "next/navigation"; + +export default async function Page() { + const { user } = await validateRequest(); + if (user) { + return redirect("/"); + } + return ( + <> +

Sign in

+ Sign in with GitHub + + ); +} +``` + +After adding the page, we also have to add the login redirect to GitHub and the callback that’s going to be called. Let’s first add the login redirect with the authorization URL: + +```tsx title="login/github/route.ts" +import { generateState } from "arctic"; +import { github } from "../../../lib/auth"; +import { cookies } from "next/headers"; + +export async function GET(): Promise { + const state = generateState(); + const url = await github.createAuthorizationURL(state); + + cookies().set("github_oauth_state", state, { + path: "/", + secure: process.env.NODE_ENV === "production", + httpOnly: true, + maxAge: 60 * 10, + sameSite: "lax" + }); + + return Response.redirect(url); +} +``` + + And finally, the callback (which is what we actually add in GitHub OAuth): + +```tsx title="login/github/callback/route.ts" +import { github, lucia } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { cookies } from "next/headers"; +import { OAuth2RequestError } from "arctic"; +import { generateId } from "lucia"; + +import type { DatabaseUser } from "@/lib/db"; + +export async function GET(request: Request): Promise { + const url = new URL(request.url); + const code = url.searchParams.get("code"); + const state = url.searchParams.get("state"); + const storedState = cookies().get("github_oauth_state")?.value ?? null; + if (!code || !state || !storedState || state !== storedState) { + return new Response(null, { + status: 400 + }); + } + + try { + const tokens = await github.validateAuthorizationCode(code); + const githubUserResponse = await fetch("https://api.github.com/user", { + headers: { + Authorization: `Bearer ${tokens.accessToken}` + } + }); + const githubUser: GitHubUser = await githubUserResponse.json(); + const existingUser = db.prepare("SELECT * FROM user WHERE github_id = ?").get(githubUser.id) as + | DatabaseUser + | undefined; + + if (existingUser) { + const session = await lucia.createSession(existingUser.id, {}); + const sessionCookie = lucia.createSessionCookie(session.id); + cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes); + return new Response(null, { + status: 302, + headers: { + Location: "/" + } + }); + } + + const userId = generateId(15); + db.prepare("INSERT INTO user (id, github_id, username) VALUES (?, ?, ?)").run( + userId, + githubUser.id, + githubUser.login + ); + const session = await lucia.createSession(userId, {}); + const sessionCookie = lucia.createSessionCookie(session.id); + cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes); + return new Response(null, { + status: 302, + headers: { + Location: "/" + } + }); + } catch (e) { + if (e instanceof OAuth2RequestError && e.message === "bad_verification_code") { + // invalid code + return new Response(null, { + status: 400 + }); + } + return new Response(null, { + status: 500 + }); + } +} + +interface GitHubUser { + id: string; + login: string; +} +``` + +Other important thing here is that, now, we’re going with GitHub OAuth, but, generally, these libraries contain a bunch of different login providers (including simple username and password), so it’s usually just a pick and choose if you want to add other providers. + +```tsx title="lib/auth.ts" +import { Lucia } from "lucia"; +import { BetterSqlite3Adapter } from "@lucia-auth/adapter-sqlite"; +import { db } from "./db"; +import { cookies } from "next/headers"; +import { cache } from "react"; +import { GitHub } from "arctic"; + +import type { Session, User } from "lucia"; +import type { DatabaseUser } from "./db"; + +// these two lines here might be important if you have node.js 18 or lower. +// you can check Lucia's documentation in more detail if that's the case +// (https://lucia-auth.com/getting-started/nextjs-app#polyfill) +// import { webcrypto } from "crypto"; +// globalThis.crypto = webcrypto as Crypto; + +const adapter = new BetterSqlite3Adapter(db, { + user: "user", + session: "session" +}); + +export const lucia = new Lucia(adapter, { + sessionCookie: { + attributes: { + secure: process.env.NODE_ENV === "production" + } + }, + getUserAttributes: (attributes) => { + return { + githubId: attributes.github_id, + username: attributes.username + }; + } +}); + +declare module "lucia" { + interface Register { + Lucia: typeof lucia; + DatabaseUserAttributes: Omit; + } +} + +export const validateRequest = cache( + async (): Promise<{ user: User; session: Session } | { user: null; session: null }> => { + const sessionId = cookies().get(lucia.sessionCookieName)?.value ?? null; + if (!sessionId) { + return { + user: null, + session: null + }; + } + + const result = await lucia.validateSession(sessionId); + // next.js throws when you attempt to set cookie when rendering page + try { + if (result.session && result.session.fresh) { + const sessionCookie = lucia.createSessionCookie(result.session.id); + cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes); + } + if (!result.session) { + const sessionCookie = lucia.createBlankSessionCookie(); + cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes); + } + } catch {} + return result; + } +); + +export const github = new GitHub(process.env.GITHUB_CLIENT_ID!, process.env.GITHUB_CLIENT_SECRET!); +``` + +### Step 6: Protect Routes + +After adding all that stuff to make the login properly work, we just have to ensure that routes are protected by checking authentication status — in this case, this is a simple page that shows username, id and a button in case signed in, and redirects to /login, where the user will complete the login above through a form. + +```tsx title="profile/page.tsx" +import { lucia, validateRequest } from "@/lib/auth"; +import { redirect } from "next/navigation"; +import { cookies } from "next/headers"; + +export default async function Page() { + const { user } = await validateRequest(); + if (!user) { + return redirect("/login"); + } + return ( + <> +

Hi, {user.username}!

+

Your user ID is {user.id}.

+
+ +
+ + ); +} + +async function logout(): Promise { + "use server"; + const { session } = await validateRequest(); + if (!session) { + return { + error: "Unauthorized" + }; + } + + await lucia.invalidateSession(session.id); + + const sessionCookie = lucia.createBlankSessionCookie(); + cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes); + return redirect("/login"); +} + +interface ActionResult { + error: string | null; +} +``` + +Piece of cake, isn’t it? Well, not really. + +Let’s recap which steps were necessary to actually make this happen: + +- Set up your app. +- Add Lucia. +- Set up authentication. +- Add User to DB. +- Obtain GitHub OAuth credentials and configure your environment variables. +- Create some util functions. +- Add Login and Sign up routes, with custom made components. +- Finally, create a protected route. + +![https://media2.giphy.com/media/3ofSBnYbEPePeigIMg/giphy.gif?cid=7941fdc6x77sivlvr6hs2yu5aztvwjvhgugv6b718mjanr2h&ep=v1_gifs_search&rid=giphy.gif&ct=g](https://media2.giphy.com/media/3ofSBnYbEPePeigIMg/giphy.gif?cid=7941fdc6x77sivlvr6hs2yu5aztvwjvhgugv6b718mjanr2h&ep=v1_gifs_search&rid=giphy.gif&ct=g) + +Honestly, when trying to create something cool **FAST**, repeating these steps and debugging a few logical problems here and there that always occur can feel a little bit frustrating. Soon, we’ll take a look at Wasp’s approach to solving that same problem and we’ll be able to compare how much easier Wasp’s auth implementation process is. + +In case you want to check the whole code for this part, [Lucia has an example repo](https://github.com/lucia-auth/examples/tree/main/nextjs-app/github-oauth) (that is the source of most of the code shown), so, you can check it out if you’d like. + +## Wasp Implementation + +Now, let’s go through how we can achieve the same things with Wasp 🐝. Although it still uses Lucia in the background, Wasp takes care of all the heavy-lifting for you, making the process much quicker and simpler. Let’s check out the developer experience for ourselves. + +Before we just into it, in case you’re more of a visual learner, here’s a 1-minute video showcasing auth with wasp. + +
+ +
+ +As seen in the video, Wasp is a framework for building apps with the benefits of using a configuration file to make development easier. It handles many repetitive tasks, allowing you to focus on creating unique features. In this tutorial, we’ll also learn more about the Wasp config file and see how it makes setting up authentication simpler. + +### Step 1: Create a Wasp Project + +```bash +curl -sSL https://get.wasp-lang.dev/installer.sh | sh +wasp new my-wasp-app +cd my-wasp-app +``` + +### Step 2: Add the User entity into our DB + +As simple as defining the `app.auth.userEntity` entity in the `schema.prisma` file and running some migrations: + +```prisma +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + // Add your own fields below + // ... +} +``` + +### Step 3: Define Authentication + +In your main Wasp configuration, add the authentication provider you want for your app + +```wasp title="main.wasp" +app myApp { + wasp: { + version: "^0.14.0" + }, + title: "My App", + auth: { + userEntity: User, + methods: { + // 2. Enable Github Auth + gitHub: {} + }, + onAuthFailedRedirectTo: "/login" + }, +} +``` + +And after that, just run in your terminal: + +```bash +wasp db migrate-dev +``` + +### Step 4: Get your GitHub OAuth credentials and app running + +This part is similar for both frameworks, you can follow the documentation GitHub provides here to do so: [Creating an OAuth app - GitHub Docs](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app). For wasp app, the callback urls are: + +- While developing: `http://localhost:3001/auth/github/callback` +- After deploying: `https://your-server-url.com/auth/github/callback` + +After that, get your secrets and add it to the env file: + +```tsx title=".env.server" +GITHUB_CLIENT_ID=your-github-client-id +GITHUB_CLIENT_SECRET=your-github-client-secret +``` + +### Step 5: Add the routes and pages + +Now, let’s simply add some routing and the page necessary for login — the process is way easier since Wasp has pre-built Login and Signup Forms, we can simply add those directly: + +```wasp title="main.wasp" +route SignupRoute { path: "/signup", to: SignupPage } +page SignupPage { + component: import { SignupPage } from "@src/SignupPage" +} + +route LoginRoute { path: "/login", to: LoginPage } +page LoginPage { + component: import { LoginPage } from "@src/LoginPage" +} +``` + +```tsx title="src/LoginPage.jsx" +import { Link } from 'react-router-dom' +import { LoginForm } from 'wasp/client/auth' + +export const LoginPage = () => { + return ( +
+ +
+ + I don't have an account yet (go to signup). + +
+ ) +} +``` + +```tsx title="src/SignupPage.jsx" +import { Link } from 'react-router-dom' +import { SignupForm } from 'wasp/client/auth' + +export const SignupPage = () => { + return ( +
+ +
+ + I already have an account (go to login). + +
+ ) +} +``` + +And finally, for protecting routes, is as simple as changing it in `main.wasp` adding **`authRequired: true`** , so, we can simply add it like this: + +```wasp title="main.wasp" +page MainPage { + component: import Main from "@src/pages/Main", + authRequired: true +} +``` + +If you’d like to check this example in more depth, feel free to check this repo here: [wasp/examples/todo-typescript at release · wasp-lang/wasp (github.com)](https://github.com/wasp-lang/wasp/tree/release/examples/todo-typescript). +Other great place to check is their documentation, which can be found [here](https://wasp-lang.dev/docs/auth/overview). It covers most of what I said here, and even more (e.g. the awesome new [hooks](https://wasp-lang.dev/docs/auth/auth-hooks) that came with Wasp v0.14) + +![https://media4.giphy.com/media/nDSlfqf0gn5g4/giphy.gif?cid=7941fdc6oxsddr7p8rjsuavcyq7ugiad8iqdu1ei25urcge4&ep=v1_gifs_search&rid=giphy.gif&ct=g](https://media4.giphy.com/media/nDSlfqf0gn5g4/giphy.gif?cid=7941fdc6oxsddr7p8rjsuavcyq7ugiad8iqdu1ei25urcge4&ep=v1_gifs_search&rid=giphy.gif&ct=g) + +Way easier, isn’t it? Let’s review the steps we took to get here: + +- Set up the project. +- Add the User entity to the database. +- Define authentication in the main Wasp configuration. +- Obtain GitHub OAuth credentials and configure your environment variables. +- Add routes and pages for login and signup with pre-built, easy-to-use components. +- Protect routes by specifying `authRequired` in your configuration. + +### Customizing Wasp Auth + +If you need more control and customization over the authentication flow, Wasp provides Auth hooks that allow you to tailor the experience to your app's specific needs. These hooks enable you to execute custom code during various stages of the authentication process, ensuring that you can implement any required custom behavior. + +For more detailed information on using Auth hooks with Wasp, visit the [Wasp documentation](https://wasp-lang.dev/docs/auth/auth-hooks). + +### Bonus Section: Adding Email/Password Login with Wasp and Customizing Auth + +Now let’s imagine we want to add email and password authentication — with all the usual features we’d expect that would follow this login method (e.g. reset password, email verification, etc.). + +With Wasp, all we have to do is add a few lines to your main.wasp file, so, simply updating your Wasp configuration to include email/password authentication makes it work straight out of the box! + +![https://wasp-lang.dev/img/auth-ui/auth-demo-compiler.gif](https://wasp-lang.dev/img/auth-ui/auth-demo-compiler.gif) + +Wasp will handle the rest, also updating UI components and ensuring a smooth and secure authentication flow. + +```wasp title="main.wasp" +app myApp { + wasp: { + version: "^0.14.0" + }, + title: "My App", + auth: { + // 1. Specify the User entity + userEntity: User, + methods: { + // 2. Enable Github Auth + gitHub: {}, + email: { + // 3. Specify the email from field + fromField: { + name: "My App Postman", + email: "hello@itsme.com" + }, + // 4. Specify the email verification and password reset options + emailVerification: { + clientRoute: EmailVerificationRoute, //this route/page should be created + }, + passwordReset: { + clientRoute: PasswordResetRoute, //this route/page should be created + }, + // Add an emailSender -- Dummy just logs to console for dev purposes + // but there are a ton of supported providers :D + emailSender: { + provider: Dummy, + }, + }, + }, + onAuthFailedRedirectTo: "/login" + }, +} +``` + +Implementing this in Next.js with Lucia would take a lot more work, involving a bunch of different stuff from actually sending the emails, to generating the verification tokens and more. They reference this [here](https://lucia-auth.com/guides/email-and-password/email-verification-links), but again, Wasp’s Auth makes the whole process way easier, handling a bunch of the complexity for us while also giving a bunch of other UI components, ready to use, to ease the UI details (e.g. `VerifyEmailForm`, `ForgotPasswordForm` and, `ResetPasswordForm`). + +The whole point here is the difference in time and developer experience in order to implement the same scenarios. For the Next.js project with Lucia, you will spend at least a few hours implementing everything if you’re going all by yourself. That same experience translates to no more than 1 hour with Wasp. What to do with the rest of the time? **Implement the important stuff your particular business requires!** + + +## Can you show us your support? + +![https://media2.giphy.com/media/l0MYAs5E2oIDCq9So/giphy.gif?cid=7941fdc6l6i66eq1dc7i5rz05nkl4mgjltyv206syb0o304g&ep=v1_gifs_search&rid=giphy.gif&ct=g](https://media2.giphy.com/media/l0MYAs5E2oIDCq9So/giphy.gif?cid=7941fdc6l6i66eq1dc7i5rz05nkl4mgjltyv206syb0o304g&ep=v1_gifs_search&rid=giphy.gif&ct=g) + +Are you interested in more content like this? Sign up for [our newsletter](https://wasp-lang.dev/#signup) and give us [a star on GitHub](https://www.github.com/wasp-lang/wasp)! We need your support to keep pushing our projects forward 😀 + +### Conclusion + +![https://media2.giphy.com/media/l1AsKaVNyNXHKUkUw/giphy.gif?cid=7941fdc6u6vp4j2gpjfuizupxlvfdzskl03ncci2e7jq17zr&ep=v1_gifs_search&rid=giphy.gif&ct=g](https://media2.giphy.com/media/l1AsKaVNyNXHKUkUw/giphy.gif?cid=7941fdc6u6vp4j2gpjfuizupxlvfdzskl03ncci2e7jq17zr&ep=v1_gifs_search&rid=giphy.gif&ct=g) + +I think that if you’re a developer who wants to get things done, you probably noted the significant difference in complexity levels of both of those implementations. + +By reducing boilerplate and abstracting repetitive tasks, Wasp allows developers to focus more on building unique features rather than getting bogged down by authentication details. This can be especially beneficial for small teams or individual developers aiming to launch products quickly. + +Of course, generally when we talk abstractions, it always comes with the downside of losing the finesse of a more personal implementation. In this case, Wasp provides a bunch of stuff for you to implement around and uses Lucia on the background, so the scenario where there’s a mismatch of content implementation is highly unlikable to happen. + +In summary, while implementing your own authentication with Next.js and Lucia provides complete control and customization, it can be complex and time-consuming. On the other hand, using a solution like Wasp simplifies the process, reduces code length, and speeds up development. \ No newline at end of file diff --git a/web/blog/2024-08-20-django-vs-wasp.md b/web/blog/2024-08-20-django-vs-wasp.md new file mode 100644 index 0000000000..5ce9c35d6a --- /dev/null +++ b/web/blog/2024-08-20-django-vs-wasp.md @@ -0,0 +1,755 @@ +--- +title: 'Wasp: The JavaScript Answer to Django for Web Development' +authors: [sam] +image: /img/django-vs-wasp/wasp-django-banner.png +tags: [webdev, auth, react, django, tutorial, full-stack] +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import ImgWithCaption from './components/ImgWithCaption' + +![a django dev tries wasp](/img/django-vs-wasp/wasp-django-banner.png) + +## Wasp vs Django: Building a full stack application just got a lot easier + +Hey, I’m Sam, a backend engineer with a lot of experience with Django. I wanted to make the jump and learn some frontend for a full stack app. I quickly experienced the arduous nature of a React-with-Django project and thought the pain was just part of the development process. However, I came across a very cool new full stack framework called [Wasp](https://wasp-lang.dev/). + +Wasp is an amazing dev tool for full stack applications. Combining things like React, Node.js and Prisma, Wasp allows for development to be expedited in ways never before seen. + +In this article, I am going to walk through creating a full stack application in Django versus Wasp to prove the simplicity of Wasp against a very conventional full-stack technology. I am also going to make a React frontend connected to Django. The point is to highlight the inefficiencies, difficulties, and issues that can (and will) arise with Django/React that are made vastly simpler when working with Wasp. + +This article is not intended as a how-to, but I do provide code snippets to give you a feel for their differences. Also note that in order to give a side-by-side comparison, I'll use tabs which you can switch back and forth between, like this: + + + + Django info will go here... + + + ...and the Wasp comparison here. + + + + + + +## Part 1: Let There Be Light! + +### Let’s create some projects and set things up + +This part is about the only part where there is significant overlap between Django and Wasp. Both starting from the terminal, let’s make a simple task app (I am assuming you have Django and [Wasp installed](https://wasp-lang.dev/docs/quick-start) and in your path). + + + + + +```sh title="terminal" +django-admin startproject +python manage.py starapp Todo +``` + + + + +```sh title="terminal" +wasp new Todo +wasp +``` + + + + +Now Wasp starts hot out of the gate. After running `wasp new` you'll see a menu, as shown below. Wasp can either start a basic app for you, or you can select from a multitude of pre-made templates (including a [fully functioning SaaS app](https://opensaas.sh)) or even use an AI-generated app based on your description! + +![wasp cli menu](/img/django-vs-wasp/wasp-cli-menu.png) + +Meanwhile, Django works as a project with apps within the project (again, this is essentially all for backend operations) and there can be many apps to one Django project. Thus, you have to register each app in the Django project settings. + +```sh title="terminal" +python `manage.py` startapp todo +``` + +```py title="settings.py" +INSTALLED_APPS [ +... +'Todo' +] +``` + +### Database Time + +So now we need a database, and this is another area where Wasp really shines. With Django, we need to create a model in the `models.py` file. Wasp, meanwhile, uses Prisma as it's ORM which allows us to clearly define necessary fields and make database creation simple in an easy to understand way. + + + + +```py title="models.py" +from django.db import models + +class Task(models.Model): + title = models.CharField(max_length=200) + completed = models.BooleanField(default=False) + + def __str__(self): + return self.title +``` + + + + +```jsx title="schema.prisma" +model Task { + id Int @id @default(autoincrement()) + description String + isDone Boolean @default(false) +} +``` + + + + +Django and Wasp do share similar ways to migrate databases: + + + + +```sh +python manage.py makemigrations +python manage.py migrate +``` + + + + +```sh +wasp db migrate-dev +``` + + + + +But with Wasp, you can also do some pretty nifty database stuff that Django can't. + +Right now we're using SQLite, but how about instantly setting up a development Posgres database? Wasp can do that with: + +```sh +wasp db start +``` + +That's it! With that you've got a docker container running a Postgres instance and it's instantly connected to your Wasp app. 🤯 + +Or what if you want to see your database in real time via Prisma’s database studio UI, something not possible without third party extensions with Django. For that, just run: + +```sh +wasp db studio +``` + +Are you starting to see what I mean now? + +### Routes + +Routes in Django and Wasp follow a shomewhat similar pattern. However, if you're familiar with React, then Wasp’s system is far superior. + +- Django works through the backend (`views.py`, which I will get to later in this article) which do all the CRUD operations. Those view functions are associated to a specific route within an app within a project (I know, a lot), and it can get more complicated if you start using primary keys and IDs. You need to create a `urls.py` file and direct your specific views file and functions to a route. Those app urls are then connected to the project urls. Phew. +- Wasp’s way: define a route and direct it to a component. + + + + +```py title="todo/urls.py" +from django.urls import path +from . import views + +urlpatterns = [ + path('', views.index, name='index'), + path('update//', views.updateTask, name='update_task'), + path('delete//', views.deleteTask, name='delete_task'), +``` + +```py title="./urls.py" +from django.contrib import admin +from django.urls import path, include + +urlpatterns = [ + path('admin/', admin.site.urls), + path('', include('todo.urls')), +] +``` + + + + +```jsx title="main.wasp" +route TaskRoute { path: "/", to: TaskPage } +page TaskPage { + component: import { TaskPage } from "@src/TaskPage" +} +``` + + + + + +### CRUD + +Ok, this is where the benefits of Wasp are about to become even more apparent. + +Firstly, I am going to revisit the `views.py` file. This is where magic is going to happen for Django backend. Here is a simple version of what the create, update, and delete functions could look like for our Task/Todo example: + + + + +```py title="todo/views.py" +from django.shortcuts import render, redirect +from .models import Task +from .forms import TaskForm + +def index(request): + tasks = Task.objects.all() + form = TaskForm() + if request.method == 'POST': + form = TaskForm(request.POST) + if form.is_valid(): + form.save() + return redirect('/') + context = {'tasks': tasks, 'form': form} + return render(request, 'todo/index.html', context) + +def updateTask(request, pk): + task = Task.objects.get(id=pk) + form = TaskForm(instance=task) + if request.method == 'POST': + form = TaskForm(request.POST, instance=task) + if form.is_valid(): + form.save() + return redirect('/') + context = {'form': form} + return render(request, 'todo/update_task.html', context) + +def deleteTask(request, pk): + task = Task.objects.get(id=pk) + if request.method == 'POST': + task.delete() + return redirect('/') + context = {'task': task} + return render(request, 'todo/delete.html', context) +``` + +```py title="app/forms.py" +from django import forms +from .models import Task + +class TaskForm(forms.ModelForm): + class Meta: + model = Task + fields = ['title', 'completed'] +``` + + + + +```jsx title="main.wasp" +query getTasks { + fn: import { getTasks } from "@src/operations", + // Tell Wasp that this operation affects the `Task` entity. Wasp will automatically + // refresh the client (cache) with the results of the operation when tasks are modified. + entities: [Task] +} + +action updateTask { + fn: import { updateTask } from "@src/operations", + entities: [Task] +} + +action deleteTask { + fn: import { deleteTask } from "@src/operations", + entities: [Task] +} +``` + +```jsx title="operations.js" +export const getTasks = async (args, context) => { + return context.entities.Task.findMany({ + orderBy: { id: 'asc' }, + }) +} + +export const updateTask = async ({ id, data }, context) => { + return context.entities.Task.update({ + where: { id }, + data + }) +} + +export const deleteTask = async ({ id }, context) => { + return context.entities.Task.delete({ + where: { id } + }) +} +``` + + + + +So right now, Wasp has a fully functioning backend with middleware configured for you. At this point we can create some React components, and then import and call these operations from the client. That is not the case with Django, unfortunately there is still a lot we need to do to configure React in our app and get things working together, which we will look at below. + +## Part 2: So you want to use React with Django? + + + +At this point we could just create a simple client with HTML and CSS to go with our Django app, but then this wouldn't be a fair comparison, as Wasp is a true full-stack framework and gives you a managed React-NodeJS-Prisma app out-of-the-box. So let's see what we'd have to do to get the same thing set up with Django. + +Note that this section is going to highlight Django, so keep in mind that you can skip all the following steps if you just use Wasp. :) + +**Django** 🟢 + +First thing’s first. Django needs a REST framework and CORS (Cross Origin Resource Sharing): + +```sh title="terminal" +pip install djangorestframework +pip install django-cors-headers +``` + +Include Rest Framework and Cors Header as installed apps, CORS headers as middleware, and then also set a local host for the React frontend to be able to communicate with the backend (Django) server (again, there is no need to do any of this initial setup in Wasp as it's all handled for you): + +```py title="settings.py" +INSTALLED_APPS = [ + ... + 'corsheaders', +] + +MIDDLEWARE = [ + ... + 'corsheaders.middleware.CorsMiddleware', + ... +] + +CORS_ALLOWED_ORIGINS = [ + 'http://localhost:3000', +] +``` + +And now a very important step, which is to serialize all the data from Django to be able to work in json format for React frontend + +```py title="app/serializers.py" +from rest_framework import serializers +from .models import Task + +class TaskSerializer(serializers.ModelSerializer): + class Meta: + model = Task + fields = '__all__' +``` + +Now, since we are handling CRUD on the React side, we can change the views.py file: + +```py title="app/views.py" +from rest_framework import viewsets +from .models import Task +from .serializers import TaskSerializer + +class TaskViewSet(viewsets.ModelViewSet): + queryset = Task.objects.all() + serializer_class = TaskSerializer +``` +And now we need to change both app and project URLS since we have a frontend application on a different url than our backend. + +```py title="urls.py" +from django.contrib import admin +from django.urls import path, include + +urlpatterns = [ + path('admin/', admin.site.urls), + path('api/', include('todo.urls')), # Add this line +] +``` + +```py title="todo/urls.py" +from django.urls import path, include +from rest_framework.routers import DefaultRouter +from .views import TaskViewSet + +router = DefaultRouter() +router.register(r'tasks', TaskViewSet) + +urlpatterns = [ + path('', include(router.urls)), +] +``` + +By now you should be understanding why I've made the switch to using Wasp when building full-stack apps. Anyways, now we are actually able to make a React component with a Django backend 🙃 + +### React time + +Ok, so now we can actually get back to comparing Wasp and Django. + + + + +To start, lets create our React app in our Django project: + +```sh title="terminal" +npx create-react-app frontend +``` + +Finally, we can make a component in React. A few things: + +- I am using axios in the Django project here. Wasp comes bundled with [React-Query (aka Tanstack Query)](https://tanstack.com/query/v3), so the execution of (CRUD) operations is a lot more elegant and powerful. +- The api call is to my local server, obviously this will change in development. +- You can make this many different ways, I tried to keep it simple. + +```jsx title="main.jsx" +import React, { useEffect, useState } from 'react'; +import axios from 'axios'; + +const TaskList = () => { + const [tasks, setTasks] = useState([]); + const [newTask, setNewTask] = useState(''); + const [editingTask, setEditingTask] = useState(null); + + useEffect(() => { + fetchTasks(); + }, []); + + const fetchTasks = () => { + axios.get('http://127.0.0.1:8000/api/tasks/') + .then(response => { + setTasks(response.data); + }) + .catch(error => { + console.error('There was an error fetching the tasks!', error); + }); + }; + + const handleAddTask = () => { + if (newTask.trim()) { + axios.post('http://127.0.0.1:8000/api/tasks/', { title: newTask, completed: false }) + .then(() => { + setNewTask(''); + fetchTasks(); + }) + .catch(error => { + console.error('There was an error adding the task!', error); + }); + } + }; + + const handleUpdateTask = (task) => { + axios.put(`http://127.0.0.1:8000/api/tasks/${task.id}/`, task) + .then(() => { + fetchTasks(); + setEditingTask(null); + }) + .catch(error => { + console.error('There was an error updating the task!', error); + }); + }; + + const handleDeleteTask = (taskId) => { + axios.delete(`http://127.0.0.1:8000/api/tasks/${taskId}/`) + .then(() => { + fetchTasks(); + }) + .catch(error => { + console.error('There was an error deleting the task!', error); + }); + }; + + const handleEditTask = (task) => { + setEditingTask(task); + }; + + const handleChange = (e) => { + setNewTask(e.target.value); + }; + + const handleEditChange = (e) => { + setEditingTask({ ...editingTask, title: e.target.value }); + }; + + const handleEditCompleteToggle = () => { + setEditingTask({ ...editingTask, completed: !editingTask.completed }); + }; + + return ( +
+

To-Do List

+ + +
    + {tasks.map(task => ( +
  • + {editingTask && editingTask.id === task.id ? ( +
    + + + + +
    + ) : ( +
    + {task.title} - {task.completed ? 'Completed' : 'Incomplete'} + + +
    + )} +
  • + ))} +
+
+ ); +}; + +export default TaskList; +``` + +
+ + +And here's the Wasp React client for comparison. Take note how we're able to import the operations we defined earlier and call them here easily on the client with less configuration than the Django app. We also get the built-in caching power of the `useQuery` hook, as well as the ability to pass in our authenticated user as a prop (we'll get into this more below): + +```jsx title="Main.jsx" +import React, { FormEventHandler, FormEvent } from "react"; +import { type Task } from "wasp/entities"; +import { type AuthUser, getUsername } from "wasp/auth"; +import { logout } from "wasp/client/auth"; +import { createTask, updateTask, deleteTasks, useQuery, getTasks } from "wasp/client/operations"; +import waspLogo from "./waspLogo.png"; + +import "./Main.css"; + +export const MainPage = ({ user }) => { + const { data: tasks, isLoading, error } = useQuery(getTasks); + + if (isLoading) return "Loading..."; + if (error) return "Error: " + error; + + const completed = tasks?.filter((task) => task.isDone).map((task) => task.id); + + return ( +
+ wasp logo + {user && user.identities.username && ( +

+ {user.identities.username.id} + {`'s tasks :)`} +

+ )} + + {tasks && } +
+ + +
+
+ ); +}; + +function Todo({ id, isDone, description }) { + const handleIsDoneChange = async ( + event + ) => { + try { + await updateTask({ + id, + isDone: event.currentTarget.checked, + }); + } catch (err: any) { + window.alert("Error while updating task " + err?.message); + } + }; + + return ( +
  • + + + {description} + + +
  • + ); +} + +function TasksList({ tasks }) { + if (tasks.length === 0) return

    No tasks yet.

    ; + return ( +
      + {tasks.map((task, idx) => ( + + ))} +
    + ); +} + +function NewTaskForm() { + const handleSubmit = async (event) => { + event.preventDefault(); + + try { + const description = event.currentTarget.description.value; + console.log(description); + event.currentTarget.reset(); + await createTask({ description }); + } catch (err: any) { + window.alert("Error: " + err?.message); + } + }; + + return ( +
    + + +
    + ); +} +``` + +
    +
    + + + +In the Wasp app you can see how much easier it is to call the server-side code via Wasp operations. Plus, Wasp gives you the added benefit of refreshing the client-side cache for the Entity that's referenced in the operation definition (in this case `Task`). And the cherry on top is how easy it is to pass the authenticated user to the component, something we haven't even touched on in the Django app, and which we will talk about more below. + +## Part 3: Auth with Django? No way, José + + + +So we already started to get a feel in the above code for how simple it is to pass an authenticated user around in Wasp. But how do we actually go about implementing full-stack Authentication in Wasp and Django. + +This is one of Wasp’s biggest advantages. It couldn't be easier or more intuitive. On the other hand, the Django implementation is so long and complicated I'm not going to even bother showing you the code and I'll just list out the stps instead. Let's also look at Wasp first this time. + + + + +```jsx title="main.wasp" +app TodoApp { + wasp: { + version: "^0.14.0" + }, + + title: "Todo App", + + auth: { + userEntity: User, + methods: { + usernameAndPassword: {} + } + } + + //... +``` + +That's it! + + + + + + +Let's check out what it takes to add a simple username and password auth implementation to a Django app (remember, this isn't even the code, just a checklist!): + +1. **Install Necessary Packages:** + - Use `pip` to install `djangorestframework`, `djoser`, and `djangorestframework-simplejwt` for Django. + - Use `npm` to install `axios` and `jwt-decode` for React. +2. **Update Django Settings:** + - Add required apps (`rest_framework`, `djoser`, `corsheaders`, and your Django app) to `INSTALLED_APPS`. + - Configure middleware to include `CorsMiddleware`. + - Set up Django REST Framework settings for authentication and permissions. + - Configure SimpleJWT settings for token expiration and authorization header types. +3. **Set Up URL Routing:** + - Include the `djoser` URLs for authentication and JWT endpoints in Django’s `urls.py`. +4. **Implement Authentication Context in React:** + - Create an authentication context in React to manage login state and tokens. + - Provide methods for logging in and out, and store tokens in local storage. +5. **Create Login Component in React:** + - Build a login form component in React that allows users to enter their credentials and authenticate using the Django backend. +6. **Protect React Routes and Components:** + - Use React Router to protect routes that require authentication. + - Ensure that API requests include the JWT token for authenticated endpoints. +7. **Implement Task Update and Delete Functionality:** + - Add methods in the React components to handle updating and deleting tasks. + - Use `axios` to make PUT and DELETE requests to the Django API. +8. **Add Authentication to Django Views:** + - Ensure that Django views and endpoints require authentication. + - Use Django REST Framework permissions to protect API endpoints. + + + + + + +And that's all it takes to implement full-stack [Auth with Wasp](https://wasp-lang.dev/docs/auth/overview)! But that's just one example, you can also add other auth methods easily, like `google: {}`, `gitHub: {}` and `discord: {}` social auth, after configuring the apps and adding your environment variables. + +Wasp allows you to get building without worrying about so many things. I don’t need to worry about password hashing, multiple projects and apps, CORS headers, etc. I just need to add a couple lines of code. + +**Wasp just makes sense.** + +## One Final Thing + +I just want to highlight one more aspect of Wasp that I really love. In Django, we're completely responsible for dealing with all the boilerplate code when setting up a new app. In other words, we have to set up new apps from scratch every time (even if it's been done before a million times by us and other devs). But with Wasp we can scaffold a new app template in a number of ways to *really* jump start the development process. + +Let's check out these other ways to get a full-stack app started in Wasp. + +### Way #1: Straight Outta Terminal + +A simple **wasp new** in the terminal shows numerous starting options and app templates. If I really want to make a todo app for example, well there you have it, option 2. + +Right out of the box you have a to-do application with authentication, CRUD functionality, and some basic styling. All of this is ready to be amended for your specific use case. + +Or what if you want to turn code into money? Well, you can also get a [fully functioning SaaS app](https://opensaas.sh). Interested in the latest AI offereings? You also have a vector embeddings template, or an AI full-stack app protoyper! 5 options that save you from having to write a ton of boilerplate code. + +![wasp cli menu](/img/django-vs-wasp/wasp-cli-menu.png) + +### Way #2: [Mage.ai](https://usemage.ai/) (Free!) + +Just throw a name, prompt, and select a few of your desired settings and boom, you get a fully functioning prototype app. From here you can use other other AI tools, like [Cursor's AI code editor](https://www.cursor.com/), to generate new features and help you debug! + +![mage](/img/django-vs-wasp/usemage.png) + +:::note +💡 The Mage functionality is also achievable via the terminal (`wasp new -> ai-generated`), but you need to provide your own OpenAI api key for it to work. +::: + +## Can you show us your support? + +![https://media2.giphy.com/media/l0MYAs5E2oIDCq9So/giphy.gif?cid=7941fdc6l6i66eq1dc7i5rz05nkl4mgjltyv206syb0o304g&ep=v1_gifs_search&rid=giphy.gif&ct=g](https://media2.giphy.com/media/l0MYAs5E2oIDCq9So/giphy.gif?cid=7941fdc6l6i66eq1dc7i5rz05nkl4mgjltyv206syb0o304g&ep=v1_gifs_search&rid=giphy.gif&ct=g) + +Are you interested in more content like this? Sign up for [our newsletter](https://wasp-lang.dev/#signup) and give us [a star on GitHub](https://www.github.com/wasp-lang/wasp)! We need your support to keep pushing our projects forward 😀 + +### Conclusion + +So there you have it. As I said in the beginning, coming from Django I was amazed how easy it was to build full-stack apps with Wasp, which is what inspired me to write this article. + +Hopefully I was able to show you why breaking away from Django in favor of Wasp can be beneficial in time, energy, and emotion. diff --git a/web/blog/authors.yml b/web/blog/authors.yml index e03e5c1642..c850441814 100644 --- a/web/blog/authors.yml +++ b/web/blog/authors.yml @@ -54,3 +54,15 @@ martinovicdev: title: Contributor @ Wasp url: https://martinovic.dev image_url: https://github.com/martinovicdev.png + +lucaslima: + name: Lucas Lima do Nascimento + title: Content contributor + url: https://github.com/LLxD + image_url: https://github.com/LLxD.png + +sam: + name: Sam Jakshtis + title: Content contributor + url: https://samjakshtis.com + image_url: https://samjakshtis.com/static/media/profile.0cff8a5a83086bb3b00b.jpg \ No newline at end of file diff --git a/web/docs/auth/auth-hooks.md b/web/docs/auth/auth-hooks.md index a5de3c0839..69937590ef 100644 --- a/web/docs/auth/auth-hooks.md +++ b/web/docs/auth/auth-hooks.md @@ -4,12 +4,14 @@ title: Auth Hooks import { EmailPill, UsernameAndPasswordPill, GithubPill, GooglePill, KeycloakPill, DiscordPill } from "./Pills"; import ImgWithCaption from '@site/blog/components/ImgWithCaption' +import { ShowForTs } from '@site/src/components/TsJsHelpers' Auth hooks allow you to "hook into" the auth process at various stages and run your custom code. For example, if you want to forbid certain emails from signing up, or if you wish to send a welcome email to the user after they sign up, auth hooks are the way to go. ## Supported hooks The following auth hooks are available in Wasp: + - [`onBeforeSignup`](#executing-code-before-the-user-signs-up) - [`onAfterSignup`](#executing-code-after-the-user-signs-up) - [`onBeforeOAuthRedirect`](#executing-code-before-the-oauth-redirect) @@ -35,7 +37,6 @@ We'll go through each of these hooks in detail. But first, let's see how the hoo \* When using the OAuth auth providers, the login hooks are both called before the session is created but the session is created quickly afterward, so it shouldn't make any difference in practice. - If you are using OAuth, the flow includes extra steps before the auth flow: ```wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, auth: { userEntity: User, @@ -90,6 +92,7 @@ app myApp { }, } ``` + @@ -123,11 +126,7 @@ app myApp { ```js title="src/auth/hooks.js" import { HttpError } from 'wasp/server' -export const onBeforeSignup = async ({ - providerId, - prisma, - req, -}) => { +export const onBeforeSignup = async ({ providerId, prisma, req }) => { const count = await prisma.user.count() console.log('number of users before', count) console.log('provider name', providerId.providerName) @@ -137,7 +136,10 @@ export const onBeforeSignup = async ({ throw new HttpError(403, 'Too many users') } - if (providerId.providerName === 'email' && providerId.providerUserId === 'some@email.com') { + if ( + providerId.providerName === 'email' && + providerId.providerUserId === 'some@email.com' + ) { throw new HttpError(403, 'This email is not allowed') } } @@ -174,7 +176,10 @@ export const onBeforeSignup: OnBeforeSignupHook = async ({ throw new HttpError(403, 'Too many users') } - if (providerId.providerName === 'email' && providerId.providerUserId === 'some@email.com') { + if ( + providerId.providerName === 'email' && + providerId.providerUserId === 'some@email.com' + ) { throw new HttpError(403, 'This email is not allowed') } } @@ -191,7 +196,7 @@ Wasp calls the `onAfterSignup` hook after the user is created. The `onAfterSignup` hook can be useful if you want to send the user a welcome email or perform some other action after the user signs up like syncing the user with a third-party service. -Since the `onAfterSignup` hook receives the OAuth access token, it can also be used to store the OAuth access token for the user in your database. +Since the `onAfterSignup` hook receives the OAuth tokens, you can use this hook to store the OAuth access token and/or [refresh token](#refreshing-the-oauth-access-token) in your database. Works with @@ -220,9 +225,9 @@ export const onAfterSignup = async ({ console.log('number of users after', count) console.log('user object', user) - // If this is an OAuth signup, we have the access token and uniqueRequestId + // If this is an OAuth signup, you have access to the OAuth tokens and the uniqueRequestId if (oauth) { - console.log('accessToken', oauth.accessToken) + console.log('accessToken', oauth.tokens.accessToken) console.log('uniqueRequestId', oauth.uniqueRequestId) const id = oauth.uniqueRequestId @@ -262,9 +267,9 @@ export const onAfterSignup: OnAfterSignupHook = async ({ console.log('number of users after', count) console.log('user object', user) - // If this is an OAuth signup, we have the access token and uniqueRequestId + // If this is an OAuth signup, you have access to the OAuth tokens and the uniqueRequestId if (oauth) { - console.log('accessToken', oauth.accessToken) + console.log('accessToken', oauth.tokens.accessToken) console.log('uniqueRequestId', oauth.uniqueRequestId) const id = oauth.uniqueRequestId @@ -304,16 +309,11 @@ app myApp { ``` ```js title="src/auth/hooks.js" -export const onBeforeOAuthRedirect = async ({ - url, - uniqueRequestId, - prisma, - req, -}) => { +export const onBeforeOAuthRedirect = async ({ url, oauth, prisma, req }) => { console.log('query params before oAuth redirect', req.query) // Saving query params for later use in onAfterSignup or onAfterLogin hooks - const id = uniqueRequestId + const id = oauth.uniqueRequestId someKindOfStore.set(id, req.query) return { url } @@ -338,14 +338,14 @@ import type { OnBeforeOAuthRedirectHook } from 'wasp/server/auth' export const onBeforeOAuthRedirect: OnBeforeOAuthRedirectHook = async ({ url, - uniqueRequestId, + oauth, prisma, req, }) => { console.log('query params before oAuth redirect', req.query) // Saving query params for later use in onAfterSignup or onAfterLogin hooks - const id = uniqueRequestId + const id = oauth.uniqueRequestId someKindOfStore.set(id, req.query) return { url } @@ -383,12 +383,11 @@ app myApp { ```js title="src/auth/hooks.js" import { HttpError } from 'wasp/server' -export const onBeforeLogin = async ({ - providerId, - prisma, - req, -}) => { - if (providerId.providerName === 'email' && providerId.providerUserId === 'some@email.com') { +export const onBeforeLogin = async ({ providerId, user, prisma, req }) => { + if ( + providerId.providerName === 'email' && + providerId.providerUserId === 'some@email.com' + ) { throw new HttpError(403, 'You cannot log in with this email') } } @@ -413,10 +412,14 @@ import type { OnBeforeLoginHook } from 'wasp/server/auth' export const onBeforeLogin: OnBeforeLoginHook = async ({ providerId, + user, prisma, req, }) => { - if (providerId.providerName === 'email' && providerId.providerUserId === 'some@email.com') { + if ( + providerId.providerName === 'email' && + providerId.providerUserId === 'some@email.com' + ) { throw new HttpError(403, 'You cannot log in with this email') } } @@ -433,7 +436,7 @@ Wasp calls the `onAfterLogin` hook after the user logs in. The `onAfterLogin` hook can be useful if you want to perform some action after the user logs in, like syncing the user with a third-party service. -Since the `onAfterLogin` hook receives the OAuth access token, it can also be used to update the OAuth access token for the user in your database. +Since the `onAfterLogin` hook receives the OAuth tokens, you can use it to update the OAuth access token for the user in your database. You can also use it to [refresh the OAuth access token](#refreshing-the-oauth-access-token) if the provider supports it. Works with @@ -460,9 +463,9 @@ export const onAfterLogin = async ({ }) => { console.log('user object', user) - // If this is an OAuth signup, we have the access token and uniqueRequestId + // If this is an OAuth signup, you have access to the OAuth tokens and the uniqueRequestId if (oauth) { - console.log('accessToken', oauth.accessToken) + console.log('accessToken', oauth.tokens.accessToken) console.log('uniqueRequestId', oauth.uniqueRequestId) const id = oauth.uniqueRequestId @@ -500,9 +503,9 @@ export const onAfterLogin: OnAfterLoginHook = async ({ }) => { console.log('user object', user) - // If this is an OAuth signup, we have the access token and uniqueRequestId + // If this is an OAuth signup, you have access to the OAuth tokens and the uniqueRequestId if (oauth) { - console.log('accessToken', oauth.accessToken) + console.log('accessToken', oauth.tokens.accessToken) console.log('uniqueRequestId', oauth.uniqueRequestId) const id = oauth.uniqueRequestId @@ -520,6 +523,58 @@ export const onAfterLogin: OnAfterLoginHook = async ({ Read more about the data the `onAfterLogin` hook receives in the [API Reference](#the-onafterlogin-hook). +### Refreshing the OAuth access token + +Some OAuth providers support refreshing the access token when it expires. To refresh the access token, you need the OAuth **refresh token**. + +Wasp exposes the OAuth refresh token in the `onAfterSignup` and `onAfterLogin` hooks. You can store the refresh token in your database and use it to refresh the access token when it expires. + +Import the provider object with the OAuth client from the `wasp/server/oauth` module. For example, to refresh the Google OAuth access token, import the `google` object from the `wasp/server/oauth` module. You use the `refreshAccessToken` method of the OAuth client to refresh the access token. + +Here's an example of how you can refresh the access token for Google OAuth: + + + + + +```js title="src/auth/hooks.js" +import { google } from 'wasp/server/oauth' + +export const onAfterLogin = async ({ oauth }) => { + if (oauth.provider === 'google' && oauth.tokens.refreshToken !== null) { + const newTokens = await google.oAuthClient.refreshAccessToken( + oauth.tokens.refreshToken + ) + log('new tokens', newTokens) + } +} +``` + + + + + +```ts title="src/auth/hooks.ts" +import type { OnAfterLoginHook } from 'wasp/server/auth' +import { google } from 'wasp/server/oauth' + +export const onAfterLogin: OnAfterLoginHook = async ({ oauth }) => { + if (oauth.provider === 'google' && oauth.tokens.refreshToken !== null) { + const newTokens = await google.oAuthClient.refreshAccessToken( + oauth.tokens.refreshToken + ) + log('new tokens', newTokens) + } +} +``` + + + + +Google exposes the `accessTokenExpiresAt` field in the `oauth.tokens` object. You can use this field to determine when the access token expires. + +If you want to refresh the token periodically, use a [Wasp Job](../advanced/jobs.md). + ## API Reference @@ -528,7 +583,7 @@ Read more about the data the `onAfterLogin` hook receives in the [API Reference] ```wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, auth: { userEntity: User, @@ -543,13 +598,14 @@ app myApp { }, } ``` + ```wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, auth: { userEntity: User, @@ -564,6 +620,7 @@ app myApp { }, } ``` + @@ -585,11 +642,7 @@ The following properties are available in all auth hooks: ```js title="src/auth/hooks.js" -export const onBeforeSignup = async ({ - providerId, - prisma, - req, -}) => { +export const onBeforeSignup = async ({ providerId, prisma, req }) => { // Hook code goes here } ``` @@ -658,11 +711,12 @@ export const onAfterSignup: OnAfterSignupHook = async ({ The hook receives an object as **input** with the following properties: + - [`providerId: ProviderId`](#providerid-fields) - - `user: User` - + The user object that was created. + - [`oauth?: OAuthFields`](#oauth-fields) - Plus the [common hook input](#common-hook-input) @@ -675,12 +729,7 @@ Wasp ignores this hook's **return value**. ```js title="src/auth/hooks.js" -export const onBeforeOAuthRedirect = async ({ - url, - uniqueRequestId, - prisma, - req, -}) => { +export const onBeforeOAuthRedirect = async ({ url, oauth, prisma, req }) => { // Hook code goes here return { url } @@ -695,7 +744,7 @@ import type { OnBeforeOAuthRedirectHook } from 'wasp/server/auth' export const onBeforeOAuthRedirect: OnBeforeOAuthRedirectHook = async ({ url, - uniqueRequestId, + oauth, prisma, req, }) => { @@ -709,14 +758,21 @@ export const onBeforeOAuthRedirect: OnBeforeOAuthRedirectHook = async ({ The hook receives an object as **input** with the following properties: + - `url: URL` - Wasp uses the URL for the OAuth redirect. -- `uniqueRequestId: string` + Wasp uses the URL for the OAuth redirect. + +- `oauth: { uniqueRequestId: string }` + + The `oauth` object has the following fields: + + - `uniqueRequestId: string` The unique request ID for the OAuth flow (you might know it as the `state` parameter in OAuth.) You can use the unique request ID to save data (e.g. request query params) that you can later use in the `onAfterSignup` or `onAfterLogin` hooks. + - Plus the [common hook input](#common-hook-input) This hook's return value must be an object that looks like this: `{ url: URL }`. Wasp uses the URL to redirect the user to the OAuth provider. @@ -727,19 +783,16 @@ This hook's return value must be an object that looks like this: `{ url: URL }`. ```js title="src/auth/hooks.js" -export const onBeforeLogin = async ({ - providerId, - prisma, - req, -}) => { +export const onBeforeLogin = async ({ providerId, prisma, req }) => { // Hook code goes here } ``` + ```ts title="src/auth/hooks.ts" -import type { OnBeforeLoginHook } from 'wasp/server/auth' +import type { OnBeforeLoginHook } from 'wasp/server/auth' export const onBeforeLogin: OnBeforeLoginHook = async ({ providerId, @@ -749,12 +802,18 @@ export const onBeforeLogin: OnBeforeLoginHook = async ({ // Hook code goes here } ``` + The hook receives an object as **input** with the following properties: + - [`providerId: ProviderId`](#providerid-fields) +- `user: User` + + The user that is trying to log in. + - Plus the [common hook input](#common-hook-input) Wasp ignores this hook's **return value**. @@ -776,6 +835,7 @@ export const onAfterLogin = async ({ // Hook code goes here } ``` + @@ -792,10 +852,12 @@ export const onAfterLogin: OnAfterLoginHook = async ({ // Hook code goes here } ``` + The hook receives an object as **input** with the following properties: + - [`providerId: ProviderId`](#providerid-fields) - `user: User` @@ -828,9 +890,31 @@ Wasp passes the `oauth` object to the `onAfterSignup` and `onAfterLogin` hooks o It has the following fields: -- `accessToken: string` +- `providerName: string` + + The name of the OAuth provider the user authenticated with (e.g. `'google'`, `'github'`). + +- `tokens: Tokens` + + You can use the OAuth tokens to make requests to the provider's API on the user's behalf. + + Depending on the OAuth provider, the `tokens` object might have different fields. For example, Google has the fields `accessToken`, `refreshToken`, `idToken`, and `accessTokenExpiresAt`. + + + + To access the provider-specific fields, you must first narrow down the `oauth.tokens` object type to the specific OAuth provider type. + + ```ts + if (oauth && oauth.providerName === 'google') { + console.log(oauth.tokens.accessToken) + // ^ Google specific tokens are available here + console.log(oauth.tokens.refreshToken) + console.log(oauth.tokens.idToken) + console.log(oauth.tokens.accessTokenExpiresAt) + } + ``` - You can use the OAuth access token to make requests to the provider's API on the user's behalf. + - `uniqueRequestId: string` diff --git a/web/docs/auth/email.md b/web/docs/auth/email.md index c5e48fcf48..90feb806ce 100644 --- a/web/docs/auth/email.md +++ b/web/docs/auth/email.md @@ -49,7 +49,7 @@ Let's start with adding the following to our `main.wasp` file: ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -83,7 +83,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { diff --git a/web/docs/auth/social-auth/github.md b/web/docs/auth/social-auth/github.md index 17df1f516a..bdb54c83ed 100644 --- a/web/docs/auth/social-auth/github.md +++ b/web/docs/auth/social-auth/github.md @@ -43,7 +43,7 @@ Let's start by properly configuring the Auth object: ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -68,7 +68,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -276,7 +276,7 @@ Add `gitHub: {}` to the `auth.methods` dictionary to use it with default setting ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -296,7 +296,7 @@ app myApp { ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -374,7 +374,7 @@ For an up to date info about the data received from GitHub, please refer to the ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -421,7 +421,7 @@ export function getConfig() { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -489,7 +489,7 @@ When you receive the `user` object [on the client or the server](../overview.md# ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -513,7 +513,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { diff --git a/web/docs/auth/social-auth/google.md b/web/docs/auth/social-auth/google.md index 9be2c97150..69a7fbeaac 100644 --- a/web/docs/auth/social-auth/google.md +++ b/web/docs/auth/social-auth/google.md @@ -43,7 +43,7 @@ Let's start by properly configuring the Auth object: ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -66,7 +66,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -317,7 +317,7 @@ Add `google: {}` to the `auth.methods` dictionary to use it with default setting ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -337,7 +337,7 @@ app myApp { ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -400,7 +400,7 @@ For an up to date info about the data received from Google, please refer to the ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -447,7 +447,7 @@ export function getConfig() { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -515,7 +515,7 @@ When you receive the `user` object [on the client or the server](../overview.md# ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -539,7 +539,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { diff --git a/web/docs/auth/social-auth/keycloak.md b/web/docs/auth/social-auth/keycloak.md index d576b00ce1..ef241a1d96 100644 --- a/web/docs/auth/social-auth/keycloak.md +++ b/web/docs/auth/social-auth/keycloak.md @@ -42,7 +42,7 @@ Let's start by properly configuring the Auth object: ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -65,7 +65,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -283,7 +283,7 @@ Add `keycloak: {}` to the `auth.methods` dictionary to use it with default setti ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -303,7 +303,7 @@ app myApp { ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -359,7 +359,7 @@ For up-to-date info about the data received from Keycloak, please refer to the [ ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -406,7 +406,7 @@ export function getConfig() { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -474,7 +474,7 @@ When you receive the `user` object [on the client or the server](../overview.md# ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -498,7 +498,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { diff --git a/web/docs/auth/social-auth/overview.md b/web/docs/auth/social-auth/overview.md index 1244c91d16..35987b1d6d 100644 --- a/web/docs/auth/social-auth/overview.md +++ b/web/docs/auth/social-auth/overview.md @@ -36,7 +36,7 @@ Here's what the full setup looks like: ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -63,7 +63,7 @@ model User { ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -148,7 +148,7 @@ Declare an import under `app.auth.methods.google.userSignupFields` (the example ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -180,7 +180,7 @@ export const userSignupFields = { ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { diff --git a/web/docs/auth/username-and-pass.md b/web/docs/auth/username-and-pass.md index a797cb2be5..5418f66e1a 100644 --- a/web/docs/auth/username-and-pass.md +++ b/web/docs/auth/username-and-pass.md @@ -44,7 +44,7 @@ Let's start with adding the following to our `main.wasp` file: ```wasp title="main.wasp" {11} app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -64,7 +64,7 @@ app myApp { ```wasp title="main.wasp" {11} app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -623,7 +623,7 @@ When you receive the `user` object [on the client or the server](./overview.md#a ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -647,7 +647,7 @@ model User { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -678,7 +678,7 @@ model User { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -699,7 +699,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { diff --git a/web/docs/data-model/crud.md b/web/docs/data-model/crud.md index 122aaca18b..a2d62de2df 100644 --- a/web/docs/data-model/crud.md +++ b/web/docs/data-model/crud.md @@ -73,7 +73,7 @@ We can start by running `wasp new tasksCrudApp` and then adding the following to ```wasp title="main.wasp" app tasksCrudApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "Tasks Crud App", diff --git a/web/docs/data-model/entities.md b/web/docs/data-model/entities.md index 77994e92fc..37b2b5a1c4 100644 --- a/web/docs/data-model/entities.md +++ b/web/docs/data-model/entities.md @@ -99,7 +99,7 @@ Entity types are available everywhere, including the client code: ```ts import { Task } from "wasp/entities" -export function ExamplePage() {} +export function ExamplePage() { const task: Task = { id: 123, description: "Some random task", diff --git a/web/docs/introduction/introduction.md b/web/docs/introduction/introduction.md index a4a229eebc..43da634178 100644 --- a/web/docs/introduction/introduction.md +++ b/web/docs/introduction/introduction.md @@ -55,7 +55,7 @@ Let's give our app a title and let's immediately turn on the full-stack authenti ```wasp title="main.wasp" app RecipeApp { title: "My Recipes", - wasp: { version: "^0.13.0" }, + wasp: { version: "^0.14.0" }, auth: { methods: { usernameAndPassword: {} }, onAuthFailedRedirectTo: "/login", diff --git a/web/docs/migrate-from-0-13-to-0-14.md b/web/docs/migrate-from-0-13-to-0-14.md index a49503fd7e..97bd5fd064 100644 --- a/web/docs/migrate-from-0-13-to-0-14.md +++ b/web/docs/migrate-from-0-13-to-0-14.md @@ -50,7 +50,7 @@ psl=} ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "MyApp", } diff --git a/web/docs/project/customizing-app.md b/web/docs/project/customizing-app.md index 1d569a4329..31c262f8e6 100644 --- a/web/docs/project/customizing-app.md +++ b/web/docs/project/customizing-app.md @@ -9,7 +9,7 @@ Each Wasp project can have only one `app` type declaration. It is used to config ```wasp app todoApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "ToDo App", head: [ @@ -27,7 +27,7 @@ You may want to change the title of your app, which appears in the browser tab, ```wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "BookFace" } @@ -42,7 +42,7 @@ An example of adding extra style sheets and scripts: ```wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", head: [ // optional @@ -58,7 +58,7 @@ app myApp { ```wasp app todoApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "ToDo App", head: [ diff --git a/web/docs/tutorial/03-pages.md b/web/docs/tutorial/03-pages.md index bfd25672ae..bfea88d2ec 100644 --- a/web/docs/tutorial/03-pages.md +++ b/web/docs/tutorial/03-pages.md @@ -194,7 +194,7 @@ Your Wasp file should now look like this: ```wasp title="main.wasp" app TodoApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "TodoApp" } @@ -211,7 +211,7 @@ page MainPage { ```wasp title="main.wasp" app TodoApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "TodoApp" } diff --git a/web/docs/tutorial/07-auth.md b/web/docs/tutorial/07-auth.md index 9f40d819ca..d4736bf0d5 100644 --- a/web/docs/tutorial/07-auth.md +++ b/web/docs/tutorial/07-auth.md @@ -38,7 +38,7 @@ Next, tell Wasp to use full-stack [authentication](../auth/overview): ```wasp title="main.wasp" app TodoApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, // highlight-start title: "TodoApp", diff --git a/web/static/img/django-vs-wasp/mindblown.gif b/web/static/img/django-vs-wasp/mindblown.gif new file mode 100644 index 0000000000..53fab01df9 Binary files /dev/null and b/web/static/img/django-vs-wasp/mindblown.gif differ diff --git a/web/static/img/django-vs-wasp/usemage.png b/web/static/img/django-vs-wasp/usemage.png new file mode 100644 index 0000000000..d0993e68f2 Binary files /dev/null and b/web/static/img/django-vs-wasp/usemage.png differ diff --git a/web/static/img/django-vs-wasp/wasp-cli-menu.png b/web/static/img/django-vs-wasp/wasp-cli-menu.png new file mode 100644 index 0000000000..8d85275e94 Binary files /dev/null and b/web/static/img/django-vs-wasp/wasp-cli-menu.png differ diff --git a/web/static/img/django-vs-wasp/wasp-django-banner.png b/web/static/img/django-vs-wasp/wasp-django-banner.png new file mode 100644 index 0000000000..1629a4b00d Binary files /dev/null and b/web/static/img/django-vs-wasp/wasp-django-banner.png differ diff --git a/web/static/img/django-vs-wasp/wasp-todo-app.gif b/web/static/img/django-vs-wasp/wasp-todo-app.gif new file mode 100644 index 0000000000..9859b223d1 Binary files /dev/null and b/web/static/img/django-vs-wasp/wasp-todo-app.gif differ diff --git a/web/static/img/lua-auth/comparison.png b/web/static/img/lua-auth/comparison.png new file mode 100644 index 0000000000..22ea75aa64 Binary files /dev/null and b/web/static/img/lua-auth/comparison.png differ diff --git a/web/static/img/lua-auth/lucia-auth-banner.png b/web/static/img/lua-auth/lucia-auth-banner.png new file mode 100644 index 0000000000..67830d7959 Binary files /dev/null and b/web/static/img/lua-auth/lucia-auth-banner.png differ diff --git a/web/versioned_docs/version-0.14.0/auth/auth-hooks.md b/web/versioned_docs/version-0.14.0/auth/auth-hooks.md index 86476ad28f..69937590ef 100644 --- a/web/versioned_docs/version-0.14.0/auth/auth-hooks.md +++ b/web/versioned_docs/version-0.14.0/auth/auth-hooks.md @@ -4,17 +4,21 @@ title: Auth Hooks import { EmailPill, UsernameAndPasswordPill, GithubPill, GooglePill, KeycloakPill, DiscordPill } from "./Pills"; import ImgWithCaption from '@site/blog/components/ImgWithCaption' +import { ShowForTs } from '@site/src/components/TsJsHelpers' Auth hooks allow you to "hook into" the auth process at various stages and run your custom code. For example, if you want to forbid certain emails from signing up, or if you wish to send a welcome email to the user after they sign up, auth hooks are the way to go. ## Supported hooks The following auth hooks are available in Wasp: + - [`onBeforeSignup`](#executing-code-before-the-user-signs-up) - [`onAfterSignup`](#executing-code-after-the-user-signs-up) - [`onBeforeOAuthRedirect`](#executing-code-before-the-oauth-redirect) +- [`onBeforeLogin`](#executing-code-before-the-user-logs-in) +- [`onAfterLogin`](#executing-code-after-the-user-logs-in) -We'll go through each of these hooks in detail. But first, let's see how the hooks fit into the signup flow: +We'll go through each of these hooks in detail. But first, let's see how the hooks fit into the auth flows: -If you are using OAuth, the flow includes extra steps before the signup flow: + + + + +\* When using the OAuth auth providers, the login hooks are both called before the session is created but the session is created quickly afterward, so it shouldn't make any difference in practice. + + +If you are using OAuth, the flow includes extra steps before the auth flow: ```wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, auth: { userEntity: User, @@ -69,9 +87,12 @@ app myApp { onBeforeSignup: import { onBeforeSignup } from "@src/auth/hooks", onAfterSignup: import { onAfterSignup } from "@src/auth/hooks", onBeforeOAuthRedirect: import { onBeforeOAuthRedirect } from "@src/auth/hooks", + onBeforeLogin: import { onBeforeLogin } from "@src/auth/hooks", + onAfterLogin: import { onAfterLogin } from "@src/auth/hooks", }, } ``` + @@ -105,11 +126,7 @@ app myApp { ```js title="src/auth/hooks.js" import { HttpError } from 'wasp/server' -export const onBeforeSignup = async ({ - providerId, - prisma, - req, -}) => { +export const onBeforeSignup = async ({ providerId, prisma, req }) => { const count = await prisma.user.count() console.log('number of users before', count) console.log('provider name', providerId.providerName) @@ -119,7 +136,10 @@ export const onBeforeSignup = async ({ throw new HttpError(403, 'Too many users') } - if (providerId.providerName === 'email' && providerId.providerUserId === 'some@email.com') { + if ( + providerId.providerName === 'email' && + providerId.providerUserId === 'some@email.com' + ) { throw new HttpError(403, 'This email is not allowed') } } @@ -156,7 +176,10 @@ export const onBeforeSignup: OnBeforeSignupHook = async ({ throw new HttpError(403, 'Too many users') } - if (providerId.providerName === 'email' && providerId.providerUserId === 'some@email.com') { + if ( + providerId.providerName === 'email' && + providerId.providerUserId === 'some@email.com' + ) { throw new HttpError(403, 'This email is not allowed') } } @@ -173,7 +196,7 @@ Wasp calls the `onAfterSignup` hook after the user is created. The `onAfterSignup` hook can be useful if you want to send the user a welcome email or perform some other action after the user signs up like syncing the user with a third-party service. -Since the `onAfterSignup` hook receives the OAuth access token, it can also be used to store the OAuth access token for the user in your database. +Since the `onAfterSignup` hook receives the OAuth tokens, you can use this hook to store the OAuth access token and/or [refresh token](#refreshing-the-oauth-access-token) in your database. Works with @@ -202,9 +225,9 @@ export const onAfterSignup = async ({ console.log('number of users after', count) console.log('user object', user) - // If this is an OAuth signup, we have the access token and uniqueRequestId + // If this is an OAuth signup, you have access to the OAuth tokens and the uniqueRequestId if (oauth) { - console.log('accessToken', oauth.accessToken) + console.log('accessToken', oauth.tokens.accessToken) console.log('uniqueRequestId', oauth.uniqueRequestId) const id = oauth.uniqueRequestId @@ -244,9 +267,9 @@ export const onAfterSignup: OnAfterSignupHook = async ({ console.log('number of users after', count) console.log('user object', user) - // If this is an OAuth signup, we have the access token and uniqueRequestId + // If this is an OAuth signup, you have access to the OAuth tokens and the uniqueRequestId if (oauth) { - console.log('accessToken', oauth.accessToken) + console.log('accessToken', oauth.tokens.accessToken) console.log('uniqueRequestId', oauth.uniqueRequestId) const id = oauth.uniqueRequestId @@ -268,7 +291,7 @@ Read more about the data the `onAfterSignup` hook receives in the [API Reference Wasp calls the `onBeforeOAuthRedirect` hook after the OAuth redirect URL is generated but before redirecting the user. This hook can access the request object sent from the client at the start of the OAuth process. -The `onBeforeOAuthRedirect` hook can be useful if you want to save some data (e.g. request query parameters) that can be used later in the OAuth flow. You can use the `uniqueRequestId` parameter to reference this data later in the `onAfterSignup` hook. +The `onBeforeOAuthRedirect` hook can be useful if you want to save some data (e.g. request query parameters) that you can use later in the OAuth flow. You can use the `uniqueRequestId` parameter to reference this data later in the `onAfterSignup` or `onAfterLogin` hooks. Works with @@ -286,16 +309,11 @@ app myApp { ``` ```js title="src/auth/hooks.js" -export const onBeforeOAuthRedirect = async ({ - url, - uniqueRequestId, - prisma, - req, -}) => { +export const onBeforeOAuthRedirect = async ({ url, oauth, prisma, req }) => { console.log('query params before oAuth redirect', req.query) - // Saving query params for later use in the onAfterSignup hook - const id = uniqueRequestId + // Saving query params for later use in onAfterSignup or onAfterLogin hooks + const id = oauth.uniqueRequestId someKindOfStore.set(id, req.query) return { url } @@ -320,14 +338,14 @@ import type { OnBeforeOAuthRedirectHook } from 'wasp/server/auth' export const onBeforeOAuthRedirect: OnBeforeOAuthRedirectHook = async ({ url, - uniqueRequestId, + oauth, prisma, req, }) => { console.log('query params before oAuth redirect', req.query) - // Saving query params for later use in the onAfterSignup hook - const id = uniqueRequestId + // Saving query params for later use in onAfterSignup or onAfterLogin hooks + const id = oauth.uniqueRequestId someKindOfStore.set(id, req.query) return { url } @@ -341,6 +359,222 @@ This hook's return value must be an object that looks like this: `{ url: URL }`. Read more about the data the `onBeforeOAuthRedirect` hook receives in the [API Reference](#the-onbeforeoauthredirect-hook). +### Executing code before the user logs in + +Wasp calls the `onBeforeLogin` hook before the user is logged in. + +The `onBeforeLogin` hook can be useful if you want to reject a user based on some criteria before they log in. + +Works with + + + + +```wasp title="main.wasp" +app myApp { + ... + auth: { + ... + onBeforeLogin: import { onBeforeLogin } from "@src/auth/hooks", + }, +} +``` + +```js title="src/auth/hooks.js" +import { HttpError } from 'wasp/server' + +export const onBeforeLogin = async ({ providerId, user, prisma, req }) => { + if ( + providerId.providerName === 'email' && + providerId.providerUserId === 'some@email.com' + ) { + throw new HttpError(403, 'You cannot log in with this email') + } +} +``` + + + + +```wasp title="main.wasp" +app myApp { + ... + auth: { + ... + onBeforeLogin: import { onBeforeLogin } from "@src/auth/hooks", + }, +} +``` + +```ts title="src/auth/hooks.ts" +import { HttpError } from 'wasp/server' +import type { OnBeforeLoginHook } from 'wasp/server/auth' + +export const onBeforeLogin: OnBeforeLoginHook = async ({ + providerId, + user, + prisma, + req, +}) => { + if ( + providerId.providerName === 'email' && + providerId.providerUserId === 'some@email.com' + ) { + throw new HttpError(403, 'You cannot log in with this email') + } +} +``` + + + + +Read more about the data the `onBeforeLogin` hook receives in the [API Reference](#the-onbeforelogin-hook). + +### Executing code after the user logs in + +Wasp calls the `onAfterLogin` hook after the user logs in. + +The `onAfterLogin` hook can be useful if you want to perform some action after the user logs in, like syncing the user with a third-party service. + +Since the `onAfterLogin` hook receives the OAuth tokens, you can use it to update the OAuth access token for the user in your database. You can also use it to [refresh the OAuth access token](#refreshing-the-oauth-access-token) if the provider supports it. + +Works with + + + + +```wasp title="main.wasp" +app myApp { + ... + auth: { + ... + onAfterLogin: import { onAfterLogin } from "@src/auth/hooks", + }, +} +``` + +```js title="src/auth/hooks.js" +export const onAfterLogin = async ({ + providerId, + user, + oauth, + prisma, + req, +}) => { + console.log('user object', user) + + // If this is an OAuth signup, you have access to the OAuth tokens and the uniqueRequestId + if (oauth) { + console.log('accessToken', oauth.tokens.accessToken) + console.log('uniqueRequestId', oauth.uniqueRequestId) + + const id = oauth.uniqueRequestId + const data = someKindOfStore.get(id) + if (data) { + console.log('saved data for the ID', data) + } + someKindOfStore.delete(id) + } +} +``` + + + + +```wasp title="main.wasp" +app myApp { + ... + auth: { + ... + onAfterLogin: import { onAfterLogin } from "@src/auth/hooks", + }, +} +``` + +```ts title="src/auth/hooks.ts" +import type { OnAfterLoginHook } from 'wasp/server/auth' + +export const onAfterLogin: OnAfterLoginHook = async ({ + providerId, + user, + oauth, + prisma, + req, +}) => { + console.log('user object', user) + + // If this is an OAuth signup, you have access to the OAuth tokens and the uniqueRequestId + if (oauth) { + console.log('accessToken', oauth.tokens.accessToken) + console.log('uniqueRequestId', oauth.uniqueRequestId) + + const id = oauth.uniqueRequestId + const data = someKindOfStore.get(id) + if (data) { + console.log('saved data for the ID', data) + } + someKindOfStore.delete(id) + } +} +``` + + + + +Read more about the data the `onAfterLogin` hook receives in the [API Reference](#the-onafterlogin-hook). + +### Refreshing the OAuth access token + +Some OAuth providers support refreshing the access token when it expires. To refresh the access token, you need the OAuth **refresh token**. + +Wasp exposes the OAuth refresh token in the `onAfterSignup` and `onAfterLogin` hooks. You can store the refresh token in your database and use it to refresh the access token when it expires. + +Import the provider object with the OAuth client from the `wasp/server/oauth` module. For example, to refresh the Google OAuth access token, import the `google` object from the `wasp/server/oauth` module. You use the `refreshAccessToken` method of the OAuth client to refresh the access token. + +Here's an example of how you can refresh the access token for Google OAuth: + + + + + +```js title="src/auth/hooks.js" +import { google } from 'wasp/server/oauth' + +export const onAfterLogin = async ({ oauth }) => { + if (oauth.provider === 'google' && oauth.tokens.refreshToken !== null) { + const newTokens = await google.oAuthClient.refreshAccessToken( + oauth.tokens.refreshToken + ) + log('new tokens', newTokens) + } +} +``` + + + + + +```ts title="src/auth/hooks.ts" +import type { OnAfterLoginHook } from 'wasp/server/auth' +import { google } from 'wasp/server/oauth' + +export const onAfterLogin: OnAfterLoginHook = async ({ oauth }) => { + if (oauth.provider === 'google' && oauth.tokens.refreshToken !== null) { + const newTokens = await google.oAuthClient.refreshAccessToken( + oauth.tokens.refreshToken + ) + log('new tokens', newTokens) + } +} +``` + + + + +Google exposes the `accessTokenExpiresAt` field in the `oauth.tokens` object. You can use this field to determine when the access token expires. + +If you want to refresh the token periodically, use a [Wasp Job](../advanced/jobs.md). + ## API Reference @@ -349,7 +583,7 @@ Read more about the data the `onBeforeOAuthRedirect` hook receives in the [API R ```wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, auth: { userEntity: User, @@ -359,16 +593,19 @@ app myApp { onBeforeSignup: import { onBeforeSignup } from "@src/auth/hooks", onAfterSignup: import { onAfterSignup } from "@src/auth/hooks", onBeforeOAuthRedirect: import { onBeforeOAuthRedirect } from "@src/auth/hooks", + onBeforeLogin: import { onBeforeLogin } from "@src/auth/hooks", + onAfterLogin: import { onAfterLogin } from "@src/auth/hooks", }, } ``` + ```wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, auth: { userEntity: User, @@ -378,26 +615,35 @@ app myApp { onBeforeSignup: import { onBeforeSignup } from "@src/auth/hooks", onAfterSignup: import { onAfterSignup } from "@src/auth/hooks", onBeforeOAuthRedirect: import { onBeforeOAuthRedirect } from "@src/auth/hooks", + onBeforeLogin: import { onBeforeLogin } from "@src/auth/hooks", + onAfterLogin: import { onAfterLogin } from "@src/auth/hooks", }, } ``` + +### Common hook input + +The following properties are available in all auth hooks: + +- `prisma: PrismaClient` + + The Prisma client instance which you can use to query your database. + +- `req: Request` + + The [Express request object](https://expressjs.com/en/api.html#req) from which you can access the request headers, cookies, etc. + ### The `onBeforeSignup` hook ```js title="src/auth/hooks.js" -import { HttpError } from 'wasp/server' - -export const onBeforeSignup = async ({ - providerId, - prisma, - req, -}) => { - // Hook code here +export const onBeforeSignup = async ({ providerId, prisma, req }) => { + // Hook code goes here } ``` @@ -405,7 +651,6 @@ export const onBeforeSignup = async ({ ```ts title="src/auth/hooks.ts" -import { HttpError } from 'wasp/server' import type { OnBeforeSignupHook } from 'wasp/server/auth' export const onBeforeSignup: OnBeforeSignupHook = async ({ @@ -413,7 +658,7 @@ export const onBeforeSignup: OnBeforeSignupHook = async ({ prisma, req, }) => { - // Hook code here + // Hook code goes here } ``` @@ -422,21 +667,9 @@ export const onBeforeSignup: OnBeforeSignupHook = async ({ The hook receives an object as **input** with the following properties: -- `providerId: ProviderId` - - The user's provider ID is an object with two properties: - - `providerName: string` - - The provider's name (e.g. `'email'`, `'google'`, `'github'`) - - `providerUserId: string` - - The user's unique ID in the provider's system (e.g. email, Google ID, GitHub ID) -- `prisma: PrismaClient` - - The Prisma client instance which you can use to query your database. -- `req: Request` +- [`providerId: ProviderId`](#providerid-fields) - The [Express request object](https://expressjs.com/en/api.html#req) from which you can access the request headers, cookies, etc. +- Plus the [common hook input](#common-hook-input) Wasp ignores this hook's **return value**. @@ -453,7 +686,7 @@ export const onAfterSignup = async ({ prisma, req, }) => { - // Hook code here + // Hook code goes here } ``` @@ -470,7 +703,7 @@ export const onAfterSignup: OnAfterSignupHook = async ({ prisma, req, }) => { - // Hook code here + // Hook code goes here } ``` @@ -478,36 +711,15 @@ export const onAfterSignup: OnAfterSignupHook = async ({ The hook receives an object as **input** with the following properties: -- `providerId: ProviderId` - - The user's provider ID is an object with two properties: - - `providerName: string` - - The provider's name (e.g. `'email'`, `'google'`, `'github'`) - - `providerUserId: string` - - The user's unique ID in the provider's system (e.g. email, Google ID, GitHub ID) + +- [`providerId: ProviderId`](#providerid-fields) - `user: User` - - The user object that was created. -- `oauth?: OAuthFields` - This object is present only when the user is created using [Social Auth](./social-auth/overview.md). - It contains the following fields: - - `accessToken: string` + The user object that was created. - You can use the OAuth access token to use the provider's API on user's behalf. - - `uniqueRequestId: string` - - The unique request ID for the OAuth flow (you might know it as the `state` parameter in OAuth.) - - You can use the unique request ID to get the data saved in the `onBeforeOAuthRedirect` hook. -- `prisma: PrismaClient` +- [`oauth?: OAuthFields`](#oauth-fields) - The Prisma client instance which you can use to query your database. -- `req: Request` - - The [Express request object](https://expressjs.com/en/api.html#req) from which you can access the request headers, cookies, etc. +- Plus the [common hook input](#common-hook-input) Wasp ignores this hook's **return value**. @@ -517,13 +729,8 @@ Wasp ignores this hook's **return value**. ```js title="src/auth/hooks.js" -export const onBeforeOAuthRedirect = async ({ - url, - uniqueRequestId, - prisma, - req, -}) => { - // Hook code here +export const onBeforeOAuthRedirect = async ({ url, oauth, prisma, req }) => { + // Hook code goes here return { url } } @@ -537,11 +744,11 @@ import type { OnBeforeOAuthRedirectHook } from 'wasp/server/auth' export const onBeforeOAuthRedirect: OnBeforeOAuthRedirectHook = async ({ url, - uniqueRequestId, + oauth, prisma, req, }) => { - // Hook code here + // Hook code goes here return { url } } @@ -551,19 +758,166 @@ export const onBeforeOAuthRedirect: OnBeforeOAuthRedirectHook = async ({ The hook receives an object as **input** with the following properties: + - `url: URL` - Wasp uses the URL for the OAuth redirect. -- `uniqueRequestId: string` + Wasp uses the URL for the OAuth redirect. + +- `oauth: { uniqueRequestId: string }` + + The `oauth` object has the following fields: + + - `uniqueRequestId: string` The unique request ID for the OAuth flow (you might know it as the `state` parameter in OAuth.) - You can use the unique request ID to save data (e.g. request query params) that you can later use in the `onAfterSignup` hook. -- `prisma: PrismaClient` - - The Prisma client instance which you can use to query your database. -- `req: Request` + You can use the unique request ID to save data (e.g. request query params) that you can later use in the `onAfterSignup` or `onAfterLogin` hooks. - The [Express request object](https://expressjs.com/en/api.html#req) from which you can access the request headers, cookies, etc. +- Plus the [common hook input](#common-hook-input) This hook's return value must be an object that looks like this: `{ url: URL }`. Wasp uses the URL to redirect the user to the OAuth provider. + +### The `onBeforeLogin` hook + + + + +```js title="src/auth/hooks.js" +export const onBeforeLogin = async ({ providerId, prisma, req }) => { + // Hook code goes here +} +``` + + + + +```ts title="src/auth/hooks.ts" +import type { OnBeforeLoginHook } from 'wasp/server/auth' + +export const onBeforeLogin: OnBeforeLoginHook = async ({ + providerId, + prisma, + req, +}) => { + // Hook code goes here +} +``` + + + + +The hook receives an object as **input** with the following properties: + +- [`providerId: ProviderId`](#providerid-fields) + +- `user: User` + + The user that is trying to log in. + +- Plus the [common hook input](#common-hook-input) + +Wasp ignores this hook's **return value**. + +### The `onAfterLogin` hook + + + + + +```js title="src/auth/hooks.js" +export const onAfterLogin = async ({ + providerId, + user, + oauth, + prisma, + req, +}) => { + // Hook code goes here +} +``` + + + + +```ts title="src/auth/hooks.ts" +import type { OnAfterLoginHook } from 'wasp/server/auth' + +export const onAfterLogin: OnAfterLoginHook = async ({ + providerId, + user, + oauth, + prisma, + req, +}) => { + // Hook code goes here +} +``` + + + + +The hook receives an object as **input** with the following properties: + +- [`providerId: ProviderId`](#providerid-fields) + +- `user: User` + + The logged-in user's object. + +- [`oauth?: OAuthFields`](#oauth-fields) + +- Plus the [common hook input](#common-hook-input) + +Wasp ignores this hook's **return value**. + +### ProviderId fields + +The `providerId` object represents the user for the current authentication method. Wasp passes it to the `onBeforeSignup`, `onAfterSignup`, `onBeforeLogin`, and `onAfterLogin` hooks. + +It has the following fields: + +- `providerName: string` + + The provider's name (e.g. `'email'`, `'google'`, `'github`) + +- `providerUserId: string` + + The user's unique ID in the provider's system (e.g. email, Google ID, GitHub ID) + +### OAuth fields + +Wasp passes the `oauth` object to the `onAfterSignup` and `onAfterLogin` hooks only when the user is authenticated with [Social Auth](./social-auth/overview.md). + +It has the following fields: + +- `providerName: string` + + The name of the OAuth provider the user authenticated with (e.g. `'google'`, `'github'`). + +- `tokens: Tokens` + + You can use the OAuth tokens to make requests to the provider's API on the user's behalf. + + Depending on the OAuth provider, the `tokens` object might have different fields. For example, Google has the fields `accessToken`, `refreshToken`, `idToken`, and `accessTokenExpiresAt`. + + + + To access the provider-specific fields, you must first narrow down the `oauth.tokens` object type to the specific OAuth provider type. + + ```ts + if (oauth && oauth.providerName === 'google') { + console.log(oauth.tokens.accessToken) + // ^ Google specific tokens are available here + console.log(oauth.tokens.refreshToken) + console.log(oauth.tokens.idToken) + console.log(oauth.tokens.accessTokenExpiresAt) + } + ``` + + + +- `uniqueRequestId: string` + + The unique request ID for the OAuth flow (you might know it as the `state` parameter in OAuth.) + + You can use the unique request ID to get the data that was saved in the `onBeforeOAuthRedirect` hook. diff --git a/web/versioned_docs/version-0.14.0/auth/email.md b/web/versioned_docs/version-0.14.0/auth/email.md index c5e48fcf48..90feb806ce 100644 --- a/web/versioned_docs/version-0.14.0/auth/email.md +++ b/web/versioned_docs/version-0.14.0/auth/email.md @@ -49,7 +49,7 @@ Let's start with adding the following to our `main.wasp` file: ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -83,7 +83,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { diff --git a/web/versioned_docs/version-0.14.0/auth/social-auth/github.md b/web/versioned_docs/version-0.14.0/auth/social-auth/github.md index 17df1f516a..bdb54c83ed 100644 --- a/web/versioned_docs/version-0.14.0/auth/social-auth/github.md +++ b/web/versioned_docs/version-0.14.0/auth/social-auth/github.md @@ -43,7 +43,7 @@ Let's start by properly configuring the Auth object: ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -68,7 +68,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -276,7 +276,7 @@ Add `gitHub: {}` to the `auth.methods` dictionary to use it with default setting ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -296,7 +296,7 @@ app myApp { ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -374,7 +374,7 @@ For an up to date info about the data received from GitHub, please refer to the ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -421,7 +421,7 @@ export function getConfig() { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -489,7 +489,7 @@ When you receive the `user` object [on the client or the server](../overview.md# ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -513,7 +513,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { diff --git a/web/versioned_docs/version-0.14.0/auth/social-auth/google.md b/web/versioned_docs/version-0.14.0/auth/social-auth/google.md index 9be2c97150..69a7fbeaac 100644 --- a/web/versioned_docs/version-0.14.0/auth/social-auth/google.md +++ b/web/versioned_docs/version-0.14.0/auth/social-auth/google.md @@ -43,7 +43,7 @@ Let's start by properly configuring the Auth object: ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -66,7 +66,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -317,7 +317,7 @@ Add `google: {}` to the `auth.methods` dictionary to use it with default setting ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -337,7 +337,7 @@ app myApp { ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -400,7 +400,7 @@ For an up to date info about the data received from Google, please refer to the ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -447,7 +447,7 @@ export function getConfig() { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -515,7 +515,7 @@ When you receive the `user` object [on the client or the server](../overview.md# ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -539,7 +539,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { diff --git a/web/versioned_docs/version-0.14.0/auth/social-auth/keycloak.md b/web/versioned_docs/version-0.14.0/auth/social-auth/keycloak.md index d576b00ce1..ef241a1d96 100644 --- a/web/versioned_docs/version-0.14.0/auth/social-auth/keycloak.md +++ b/web/versioned_docs/version-0.14.0/auth/social-auth/keycloak.md @@ -42,7 +42,7 @@ Let's start by properly configuring the Auth object: ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -65,7 +65,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -283,7 +283,7 @@ Add `keycloak: {}` to the `auth.methods` dictionary to use it with default setti ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -303,7 +303,7 @@ app myApp { ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -359,7 +359,7 @@ For up-to-date info about the data received from Keycloak, please refer to the [ ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -406,7 +406,7 @@ export function getConfig() { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -474,7 +474,7 @@ When you receive the `user` object [on the client or the server](../overview.md# ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -498,7 +498,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { diff --git a/web/versioned_docs/version-0.14.0/auth/social-auth/overview.md b/web/versioned_docs/version-0.14.0/auth/social-auth/overview.md index 1244c91d16..35987b1d6d 100644 --- a/web/versioned_docs/version-0.14.0/auth/social-auth/overview.md +++ b/web/versioned_docs/version-0.14.0/auth/social-auth/overview.md @@ -36,7 +36,7 @@ Here's what the full setup looks like: ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -63,7 +63,7 @@ model User { ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -148,7 +148,7 @@ Declare an import under `app.auth.methods.google.userSignupFields` (the example ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -180,7 +180,7 @@ export const userSignupFields = { ```wasp title=main.wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { diff --git a/web/versioned_docs/version-0.14.0/auth/username-and-pass.md b/web/versioned_docs/version-0.14.0/auth/username-and-pass.md index 89f40ae925..5418f66e1a 100644 --- a/web/versioned_docs/version-0.14.0/auth/username-and-pass.md +++ b/web/versioned_docs/version-0.14.0/auth/username-and-pass.md @@ -44,7 +44,7 @@ Let's start with adding the following to our `main.wasp` file: ```wasp title="main.wasp" {11} app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -64,7 +64,7 @@ app myApp { ```wasp title="main.wasp" {11} app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -522,7 +522,7 @@ export const signup = async (args, _context) => { // ... action customSignup { - fn: import { signup } from "@src/auth/signup.js", + fn: import { signup } from "@src/auth/signup", } ``` @@ -623,7 +623,7 @@ When you receive the `user` object [on the client or the server](./overview.md#a ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -647,7 +647,7 @@ model User { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -678,7 +678,7 @@ model User { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { @@ -699,7 +699,7 @@ app myApp { ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", auth: { diff --git a/web/versioned_docs/version-0.14.0/data-model/crud.md b/web/versioned_docs/version-0.14.0/data-model/crud.md index 122aaca18b..a2d62de2df 100644 --- a/web/versioned_docs/version-0.14.0/data-model/crud.md +++ b/web/versioned_docs/version-0.14.0/data-model/crud.md @@ -73,7 +73,7 @@ We can start by running `wasp new tasksCrudApp` and then adding the following to ```wasp title="main.wasp" app tasksCrudApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "Tasks Crud App", diff --git a/web/versioned_docs/version-0.14.0/introduction/introduction.md b/web/versioned_docs/version-0.14.0/introduction/introduction.md index a4a229eebc..43da634178 100644 --- a/web/versioned_docs/version-0.14.0/introduction/introduction.md +++ b/web/versioned_docs/version-0.14.0/introduction/introduction.md @@ -55,7 +55,7 @@ Let's give our app a title and let's immediately turn on the full-stack authenti ```wasp title="main.wasp" app RecipeApp { title: "My Recipes", - wasp: { version: "^0.13.0" }, + wasp: { version: "^0.14.0" }, auth: { methods: { usernameAndPassword: {} }, onAuthFailedRedirectTo: "/login", diff --git a/web/versioned_docs/version-0.14.0/migrate-from-0-13-to-0-14.md b/web/versioned_docs/version-0.14.0/migrate-from-0-13-to-0-14.md index a49503fd7e..97bd5fd064 100644 --- a/web/versioned_docs/version-0.14.0/migrate-from-0-13-to-0-14.md +++ b/web/versioned_docs/version-0.14.0/migrate-from-0-13-to-0-14.md @@ -50,7 +50,7 @@ psl=} ```wasp title="main.wasp" app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "MyApp", } diff --git a/web/versioned_docs/version-0.14.0/project/customizing-app.md b/web/versioned_docs/version-0.14.0/project/customizing-app.md index 1d569a4329..31c262f8e6 100644 --- a/web/versioned_docs/version-0.14.0/project/customizing-app.md +++ b/web/versioned_docs/version-0.14.0/project/customizing-app.md @@ -9,7 +9,7 @@ Each Wasp project can have only one `app` type declaration. It is used to config ```wasp app todoApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "ToDo App", head: [ @@ -27,7 +27,7 @@ You may want to change the title of your app, which appears in the browser tab, ```wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "BookFace" } @@ -42,7 +42,7 @@ An example of adding extra style sheets and scripts: ```wasp app myApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "My App", head: [ // optional @@ -58,7 +58,7 @@ app myApp { ```wasp app todoApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "ToDo App", head: [ diff --git a/web/versioned_docs/version-0.14.0/tutorial/03-pages.md b/web/versioned_docs/version-0.14.0/tutorial/03-pages.md index bfd25672ae..bfea88d2ec 100644 --- a/web/versioned_docs/version-0.14.0/tutorial/03-pages.md +++ b/web/versioned_docs/version-0.14.0/tutorial/03-pages.md @@ -194,7 +194,7 @@ Your Wasp file should now look like this: ```wasp title="main.wasp" app TodoApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "TodoApp" } @@ -211,7 +211,7 @@ page MainPage { ```wasp title="main.wasp" app TodoApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, title: "TodoApp" } diff --git a/web/versioned_docs/version-0.14.0/tutorial/07-auth.md b/web/versioned_docs/version-0.14.0/tutorial/07-auth.md index 9f40d819ca..d4736bf0d5 100644 --- a/web/versioned_docs/version-0.14.0/tutorial/07-auth.md +++ b/web/versioned_docs/version-0.14.0/tutorial/07-auth.md @@ -38,7 +38,7 @@ Next, tell Wasp to use full-stack [authentication](../auth/overview): ```wasp title="main.wasp" app TodoApp { wasp: { - version: "^0.13.0" + version: "^0.14.0" }, // highlight-start title: "TodoApp",