|
| 1 | +--- |
| 2 | +description: |
| 3 | +globs: |
| 4 | +alwaysApply: true |
| 5 | +--- |
| 6 | +# 4. Authentication |
| 7 | + |
| 8 | +This document gives a quick rundown on how authentication is configured and used within the Wasp application. |
| 9 | + |
| 10 | +See the Wasp Auth docs for available methods and complete guides [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc) |
| 11 | + |
| 12 | +## Wasp Auth Setup |
| 13 | + |
| 14 | +- Wasp provides built-in authentication with minimal configuration via the Wasp config file. |
| 15 | +- Wasp generates all necessary auth routes, middleware, and UI components based on the configuration. |
| 16 | +- Example auth configuration in [main.wasp](mdc:main.wasp): |
| 17 | + ```wasp |
| 18 | + app myApp { |
| 19 | + // ... other config |
| 20 | + auth: { |
| 21 | + // Links Wasp auth to your User model in @schema.prisma |
| 22 | + userEntity: User, |
| 23 | + methods: { |
| 24 | + // Enable username/password login |
| 25 | + usernameAndPassword: {}, |
| 26 | + // Enable Google OAuth login |
| 27 | + // Requires setting GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET env vars |
| 28 | + google: {}, |
| 29 | + // Enable email/password login with verification |
| 30 | + email: { |
| 31 | + // Set up an email sender (Dummy prints to console) |
| 32 | + // See https://wasp-lang.com/docs/auth/email-auth#email-sending |
| 33 | + fromField: { |
| 34 | + name: "Budgeting Vibe", |
| 35 | + |
| 36 | + }, |
| 37 | + emailVerification: { |
| 38 | + clientRoute: EmailVerificationRoute |
| 39 | + }, |
| 40 | + passwordReset: { |
| 41 | + clientRoute: PasswordResetRoute |
| 42 | + } |
| 43 | + } |
| 44 | + }, |
| 45 | + // Route to redirect to if auth fails |
| 46 | + onAuthFailedRedirectTo: "/login", |
| 47 | + // Optional: Route after successful signup/login |
| 48 | + // onAuthSucceededRedirectTo: "/dashboard" |
| 49 | + } |
| 50 | + emailSender: { |
| 51 | + provider: Dummy // Use Dummy for local dev (prints emails to console) |
| 52 | + // provider: SMTP // For production, configure SMTP |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + // Define the routes needed by email auth methods |
| 57 | + route EmailVerificationRoute { path: "/auth/verify-email", to: EmailVerificationPage } |
| 58 | + page EmailVerificationPage { component: import { EmailVerification } from "@src/features/auth/EmailVerificationPage.tsx" } |
| 59 | + |
| 60 | + route PasswordResetRoute { path: "/auth/reset-password", to: PasswordResetPage } |
| 61 | + page PasswordResetPage { component: import { PasswordReset } from "@src/features/auth/PasswordResetPage.tsx" } |
| 62 | + ``` |
| 63 | + |
| 64 | +- **Dummy Email Provider Note:** When `emailSender: { provider: Dummy }` is configured in [main.wasp](mdc:main.wasp), Wasp does not send actual emails. Instead, the content of verification/password reset emails, including the clickable link, will be printed directly to the server console where `wasp start` is running. |
| 65 | + |
| 66 | +## Wasp Auth Rules |
| 67 | + |
| 68 | +- **User Model ( [schema.prisma](mdc:schema.prisma) ):** |
| 69 | + - Wasp Auth methods handle essential identity fields (like `email`, `password hash`, `provider IDs`, `isVerified`) internally. These are stored in separate Prisma models managed by Wasp (`AuthProvider`, `AuthProviderData`). |
| 70 | + - Your Prisma `User` model (specified in [main.wasp](mdc:main.wasp) as `auth.userEntity`) typically **only needs the `id` field** for Wasp to link the auth identity. |
| 71 | + ```prisma |
| 72 | + // Minimal User model in @schema.prisma |
| 73 | + model User { |
| 74 | + id Int @id @default(autoincrement()) |
| 75 | + // Add other *non-auth* related fields as needed |
| 76 | + // e.g., profile info, preferences, relations to other models |
| 77 | + // profileImageUrl String? |
| 78 | + // timeZone String? @default("UTC") |
| 79 | + } |
| 80 | + ``` |
| 81 | + - **Avoid adding** `email`, `emailVerified`, `password`, `username`, or provider-specific ID fields directly to *your* `User` model in [schema.prisma](mdc:schema.prisma) unless you have very specific customization needs that require overriding Wasp's default behavior and managing these fields manually. |
| 82 | + - If you need frequent access to an identity field like `email` or `username` for *any* user (not just the logged-in one), see the **Recommendation** in the "Wasp Auth User Fields" section below. |
| 83 | + |
| 84 | +- **Auth Pages:** |
| 85 | + - When initially creating Auth pages (Login, Signup), use the pre-built components provided by Wasp for simplicity: |
| 86 | + - `import { LoginForm, SignupForm } from 'wasp/client/auth';` |
| 87 | + - These components work with the configured auth methods in [main.wasp](mdc:main.wasp). |
| 88 | + - You can customize their appearance or build completely custom forms if needed. |
| 89 | + |
| 90 | +- **Protected Routes/Pages:** |
| 91 | + - Use the `useAuth` hook from `wasp/client/auth` to access the current user's data and check authentication status. |
| 92 | + - Redirect or show alternative content if the user is not authenticated. |
| 93 | + ```typescript |
| 94 | + import { useAuth } from 'wasp/client/auth'; |
| 95 | + import { Redirect } from 'wasp/client/router'; // Or use Link |
| 96 | + |
| 97 | + const MyProtectedPage = () => { |
| 98 | + const { data: user, isLoading, error } = useAuth(); // Returns AuthUser | null |
| 99 | + |
| 100 | + if (isLoading) return <div>Loading...</div>; |
| 101 | + // If error, it likely means the auth session is invalid/expired |
| 102 | + if (error || !user) { |
| 103 | + // Redirect to login page defined in main.wasp (auth.onAuthFailedRedirectTo) |
| 104 | + // Or return <Redirect to="/login" />; |
| 105 | + return <div>Please log in to access this page.</div>; |
| 106 | + } |
| 107 | + |
| 108 | + // User is authenticated, render the page content |
| 109 | + // Use helpers like getEmail(user) or getUsername(user) if needed |
| 110 | + return <div>Welcome back!</div>; // Access user.id if needed |
| 111 | + }; |
| 112 | + ``` |
| 113 | + |
| 114 | +## Wasp Auth User Fields (`AuthUser`) |
| 115 | + |
| 116 | +- The `user` object returned by `useAuth()` hook on the client, or accessed via `context.user` in server operations/APIs, is an `AuthUser` object (type imported from `wasp/auth`). |
| 117 | +- **Auth-specific fields** (email, username, verification status, provider IDs) live under the nested `identities` property based on the auth method used. |
| 118 | + - e.g., `user.identities.email?.email` |
| 119 | + - e.g., `user.identities.username?.username` |
| 120 | + - e.g., `user.identities.google?.providerUserId` |
| 121 | + - **Always check for `null` or `undefined`** before accessing these nested properties, as a user might not have used all configured auth methods. |
| 122 | +- **Helpers:** Wasp provides helper functions from `wasp/auth` for easier access to common identity fields on the `AuthUser` object: |
| 123 | + - `import { getEmail, getUsername } from 'wasp/auth';` |
| 124 | + - `const email = getEmail(user); // Returns string | null` |
| 125 | + - `const username = getUsername(user); // Returns string | null` |
| 126 | +- **Standard User Entities:** Remember that standard `User` entities fetched via `context.entities.User.findMany()` or similar in server code **DO NOT** automatically include these auth identity fields (`email`, `username`, etc.) by default. They only contain the fields defined directly in your [schema.prisma](mdc:schema.prisma) `User` model. |
| 127 | +- **Recommendation:** |
| 128 | + - If you need *frequent* access to an identity field like `email` or `username` for *any* user (not just the currently logged-in one accessed via `context.user` or `useAuth`) and want to query it easily via `context.entities.User`, consider this approach: |
| 129 | + 1. **Add the field directly** to your `User` model in [schema.prisma](mdc:schema.prisma). |
| 130 | + ```prisma |
| 131 | + model User { |
| 132 | + id Int @id @default(autoincrement()) |
| 133 | + email String? @unique // Add if needed frequently |
| 134 | + // other fields... |
| 135 | + } |
| 136 | + ``` |
| 137 | + 2. **Ensure this field is populated correctly** when the user signs up or updates their profile. You can do this through the `userSignupFields` property in the wasp config file for each auth method. |
| 138 | + ```wasp |
| 139 | + //main.wasp |
| 140 | + auth: { |
| 141 | + userEntity: User, |
| 142 | + methods: { |
| 143 | + email: { |
| 144 | + //... |
| 145 | + userSignupFields: import { getEmailUserFields } from "@src/auth/userSignupFields" |
| 146 | + }, |
| 147 | + } |
| 148 | + } |
| 149 | + ``` |
| 150 | + ```ts |
| 151 | + //userSignupFields.ts |
| 152 | + import { defineUserSignupFields } from 'wasp/auth/providers/types'; |
| 153 | + |
| 154 | + const userDataSchema = z.object({ |
| 155 | + email: z.string(), |
| 156 | + }); |
| 157 | + |
| 158 | + export const getEmailUserFields = defineUserSignupFields({ |
| 159 | + email: (data) => { |
| 160 | + const userData = userDataSchema.parse(data); |
| 161 | + return userData.email; |
| 162 | + } |
| 163 | + }) |
| 164 | + ``` |
| 165 | + 3. This makes the field (`email` in this example) a standard, queryable field on your `User` entity, accessible via `context.entities.User`, separate from the `AuthUser`'s identity structure. |
| 166 | + |
| 167 | +- **Common Issue:** If auth isn't working, first verify the `auth` configuration in [main.wasp](mdc:main.wasp) is correct and matches your intent (correct `userEntity`, enabled `methods`, `onAuthFailedRedirectTo`). Ensure environment variables for social providers are set if applicable. Check the Wasp server logs for errors. |
0 commit comments