Helpers
user
model
Gadget by default sets the following fields within your user
model:
resetPasswordTokenExpiration
resetPasswordToken
emailVerificationTokenExpiration
emailVerificationToken
password
googleProfileId
googleImageUrl
emailVerified
email
lastName
firstName
lastSignedIn
roles
Google OAuth Sign Up trigger
This trigger executes when a new user signs up using Google OAuth. The entire profile payload from Google is included in the trigger.
Google OAuth Sign In trigger
This trigger executes when an existing user signs in using Google OAuth. The entire profile payload from Google is included in the trigger.
Email Password Sign Up trigger
This trigger executes when a new user signs up using Email-Password authentication. This trigger exposes the signUp
action to your API.
Email Password Sign In trigger
This trigger executes when an existing user signs in using Email-Password authentication. This trigger exposes the signIn
action to your API.
Verify Email trigger
This trigger executes the verifyEmail
action. It finds a user record by emailVerificationToken
and checks emailVerificationTokenExpiration
to see if the token is still valid. If it is the trigger sets emailVerified
to be true.
Send Verify Email trigger
This trigger executes the sendVerifyEmail
action. When the sendVerifyEmail
action is called from your API, this trigger finds a user record by email and checks that emailVerified
is false. It generates a random code and provides it to the action in params.user.emailVerificationCode
. The user record then has emailVerificationToken
set to the SHA256 hash of this code.
Reset Password trigger
This trigger executes the resetPassword
action. It finds a user record by resetPasswordToken
and checks resetPasswordTokenExpiration
to see if the token is still valid. If it is the trigger sets the new password.
Send Reset Password trigger
This trigger executes the sendResetPassword
action. When the sendResetPassword
action is called from your API, this trigger finds a user record by email. It then generates a random code and provides it to the action in params.user.resetPasswordCode
. The user record then has resetPasswordToken
set to the SHA256 hash of this code.
Change Password trigger
This trigger executes the changePassword
action. It checks that the currentPassword
matches the user's current password and then sets the new password.
signUp
action
A user
model's signUp
action is a create action by default.
Its run
function includes setting the lastSignedIn
field of the user record to the current date and time. This indicates when the user last signed in or, in this context, when the user created their account.
In addition, it associates the current user record with the active session.
api/models/user/actions/signUp.jsJavaScript1import {2 applyParams,3 save,4 ActionOptions,5 SignUpUserActionContext,6} from "gadget-server";7/**8 * @param { SignUpUserActionContext } context9 */10export async function run({ params, record, logger, api, session }) {11 applyParams(params, record);12 record.lastSignedIn = new Date();13 await save(record);14 // associate the current user record with the active session15 if (record.emailVerified) {16 session?.set("user", { _link: record.id });17 }18 return {19 result: "ok",20 };21}22/**23 * @param { SignUpUserActionContext } context24 */25export async function onSuccess({ params, record, logger, api }) {26 // sends the user a verification email if they have not yet verified27 if (!record.emailVerified) {28 await api.user.sendVerifyEmail({ email: record.email });29 }30}31/** @type { ActionOptions } */32export const options = {33 actionType: "create",34 returnType: true,35};
signIn
action
A user
model's signIn
action is an update action by default.
It updates the lastSignedIn
field of the user
record to the current date and time and associates the current user record with the active session.
api/models/user/actions/signIn.jsJavaScript1import {2 save,3 ActionOptions,4 SignInUserActionContext,5 applyParams,6} from "gadget-server";7/**8 * @param { SignInUserActionContext } context9 */10export async function run({ params, record, logger, api, session }) {11 applyParams(params, record);12 record.lastSignedIn = new Date();13 await save(record);14 // associate the current user record with the active session15 session?.set("user", { _link: record.id });16}17/**18 * @param { SignInUserActionContext } context19 */20export async function onSuccess({ params, record, logger, api }) {21 // Your logic goes here22}23/** @type { ActionOptions } */24export const options = {25 actionType: "update",26};
signOut
action
A user
model's signOut
action is an update action by default.
It unsets the associated user on the active session, causing the session to be unauthenticated.
user/signOut.jsJavaScript1import { ActionOptions, SignOutUserActionContext } from "gadget-server";2/**3 * @param { SignOutUserActionContext } context4 */5export async function run({ params, record, logger, api, session }) {6 // unset the associated user on the active session7 session?.set("user", null);8}9/**10 * @param { SignOutUserActionContext } context11 */12export async function onSuccess({ params, record, logger, api }) {13 // Your logic goes here14}15/** @type { ActionOptions } */16export const options = {17 actionType: "update",18};
verifyEmail
and sendVerifyEmail
actions
A user
model's verifyEmail
action is a default action file upon app creation, that is designated to handle email verification scenarios for users, as determined by the Gadget developer.
api/models/user/actions/verifyEmail.jsJavaScript1import {2 applyParams,3 save,4 ActionOptions,5 VerifyEmailUserActionContext,6} from "gadget-server";78/**9 * @param { VerifyEmailUserActionContext } context10 */11export async function run({ params, record, logger, api, session }) {12 applyParams(params, record);13 await save(record);14 return {15 result: "ok",16 };17}1819/**20 * @param { VerifyEmailUserActionContext } context21 */22export async function onSuccess({ params, record, logger, api, emails }) {23 // Your logic goes here24}2526/** @type { ActionOptions } */27export const options = {28 actionType: "custom",29 returnType: true,30};
The sendVerifyEmail
action, is a custom action that updates the user
record with the provided parameters and then, if successful, it sends an email to the user containing a reset password link.
api/models/user/actions/sendVerifyEmail.jsJavaScript1import {2 applyParams,3 save,4 ActionOptions,5 SendVerifyEmailUserActionContext,6 DefaultEmailTemplates,7 Config,8} from "gadget-server";910/**11 * @param { SendVerifyEmailUserActionContext } context12 */13export async function run({ params, record, logger, api, session }) {14 applyParams(params, record);15 await save(record);16 return {17 result: "ok",18 };19}2021/**22 * @param { SendVerifyEmailUserActionContext } context23 */24export async function onSuccess({ params, record, logger, api, emails }) {25 if (26 !record.emailVerified &&27 record.emailVerificationToken &&28 params.user?.emailVerificationCode29 ) {30 const url = new URL("/verify-email", Config.appUrl);31 url.searchParams.append("code", params.user?.emailVerificationCode);32 // sends the verification email33 await emails.sendMail({34 to: record.email,35 subject: `Verify your email with ${Config.appName}`,36 html: DefaultEmailTemplates.renderVerifyEmailTemplate({ url: url.toString() }),37 });38 }39}4041/** @type { ActionOptions } */42export const options = {43 actionType: "custom",44 returnType: true,45};
resetPassword
and sendResetPassword
actions
A user
model's resetPassword
action is a default action file upon app creation, that is designated to handle password reset scenarios for users, as determined by the Gadget developer.
api/models/user/actions/resetPassword.jsJavaScript1import {2 applyParams,3 save,4 ActionOptions,5 ResetPasswordUserActionContext,6} from "gadget-server";78/**9 * @param { ResetPasswordUserActionContext } context10 */11export async function run({ params, record, logger, api, session }) {12 applyParams(params, record);13 await save(record);14 return {15 result: "ok",16 };17}1819/**20 * @param { ResetPasswordUserActionContext } context21 */22export async function onSuccess({ params, record, logger, api, emails }) {23 // Your logic goes here24}2526/** @type { ActionOptions } */27export const options = {28 actionType: "custom",29 returnType: true,30};
The sendResetPassword
action, is a custom action that updates the user
record with the provided parameters and then, if successful, the action will send a verification email containing a unique link for the user to verify their email.
api/models/user/actions/sendResetPassword.jsJavaScript1import {2 applyParams,3 save,4 ActionOptions,5 ResetPasswordUserActionContext,6 DefaultEmailTemplates,7 Config,8} from "gadget-server";910/**11 * @param { ResetPasswordUserActionContext } context12 */13export async function run({ params, record, logger, api, session }) {14 applyParams(params, record);15 await save(record);16 return {17 result: "ok",18 };19}2021/**22 * @param { ResetPasswordUserActionContext } context23 */24export async function onSuccess({ params, record, logger, api, emails }) {25 if (record.resetPasswordToken && params.user?.resetPasswordCode) {26 const url = new URL("/reset-password", Config.appUrl);27 url.searchParams.append("code", params.user?.resetPasswordCode);28 // sends a reset password email with a link generated internally by Gadget29 await emails.sendMail({30 to: record.email,31 subject: `Reset password request from ${Config.appName}`,32 html: DefaultEmailTemplates.renderResetPasswordTemplate({33 url: url.toString(),34 }),35 });36 }37}3839/** @type { ActionOptions } */40export const options = {41 actionType: "custom",42 returnType: true,43};
changePassword
action
A user
model's changePassword
action is a default action file upon app creation, that is designated to handle scenarios for users where they have to change/update their password, as determined by the Gadget developer.
api/models/user/actions/changePassword.jsJavaScript1import {2 applyParams,3 save,4 ActionOptions,5 ChangePasswordUserActionContext,6} from "gadget-server";78/**9 * @param { ChangePasswordUserActionContext } context10 */11export async function run({ params, record, logger, api, session }) {12 applyParams(params, record);13 await save(record);14}1516/**17 * @param { ChangePasswordUserActionContext } context18 */19export async function onSuccess({ params, record, logger, api, emails }) {20 // Your logic goes here21}2223/** @type { ActionOptions } */24export const options = {25 actionType: "update",26};
session
model
All Gadget apps have a session
model that is used to power session management. The current session is always available in Gadget actions and route handlers:
api/actions/someAction.jsJavaScriptexport async function run({ params, record, logger, api, session }) {logger.info({ session }, "the session associated with the current request");}
csrfToken
All session
records have a special csrfToken
property that can be used to prevent cross-site request forgery (CSRF) attacks.
Gadget automatically checks CSRF tokens for all form submission requests. To submit a form as an authenticated user you must include the CSRF token in the form data.
api/routes/GET-a-form.jsJavaScript1export async function run({ params, record, logger, api, session }) {2 // send an HTML response with a form that has a CSRF token3 await reply.send(`4 <html>5 <body>6 <form method="POST" action="/submit-form">7 <input type="hidden" name="csrfToken" value="${session.csrfToken}" />8 <button type="submit">Submit</button>9 </form>10 </body>11 </html>12 `);13}
Hooks and components
When working with Gadget authentication, there are several hooks and components from our @gadgetinc/react
package that can help you manage the authentication state of your application.
The hooks use the Gadget client's suspense: true
option, making it easier to manage the async nature of the hooks without having to deal with loading state.
Hooks | Description |
---|---|
useSession() | Retrieves the current user session within the app. |
useUser() | If a user is present in the session, it returns the current user; otherwise, it returns null for unauthenticated sessions. |
useAuth() | Returns an object representing the current authentication state of the session. |
useSignOut() | Returns a callback that you can call to sign out your current Gadget User from the current Session . This calls the configured signOutActionApiIdentifier action, which is the User signOut action by default. |
Components | Description |
---|---|
<SignedIn /> | Conditionally renders its children if the current session has a user associated with it, similar to the isSignedIn property of the useAuth() hook. |
<SignedOut /> | Conditionally renders its children if the current session does not have a user associated with it. |
<SignedInOrRedirect /> | Conditionally renders its children based on the user's sign-in status. If a user is currently signed in, it displays its children; otherwise, it redirects the browser using window.location.assign . This functionality is valuable for securing frontend routes. |
<SignedOutOrRedirect /> | Conditionally renders its children when there is no user associated with the current session. However, if the user is signed in, it redirects the browser using window.location.assign . Its purpose is to facilitate redirection of frontend routes based on the user's sign-in status. |