Next.js API Routes Reference
Installation
$ npm install --save @propelauth/node
Initialize
To initialize the PropelAuth library in lib/propelauth.js
, enter the code
below, making sure to include the newline characters in your verifierKey:
import { initBaseAuth } from "@propelauth/node";
const propelauth = initBaseAuth({
// If true, error messages returned to the user will be detailed.
// It's useful for debugging, but a good idea to turn off in production.
debugMode: true,
// You can find the rest of the fields under the Backend Integration section for your project in PropelAuth.
authUrl: "YOUR_AUTH_URL",
apiKey: "YOUR_API_KEY",
manualTokenVerificationMetadata: {
verifierKey: `YOUR
MULTILINE
KEY`,
issuer: "YOUR_ISSUER_URL",
},
});
You can then import what you need from propelauth in your routes:
import { validateAccessTokenAndGetUser } from "../../lib/propelauth";
Protect API routes
validateAccessTokenAndGetUser
This function takes in the Authorization
HTTP header and verifies the request was made by a valid user.
It expects the header to be in the format Bearer ACCESS_TOKEN
.
If the Authorization
HTTP header is malformed or doesn’t contain a valid access token, an UnauthorizedException
is thrown.
import { validateAccessTokenAndGetUser } from "../../lib/propelauth";
export default async function handler(req, res) {
try {
const authHeader = req.headers.authorization
const user = await validateAccessTokenAndGetUser(authHeader)
res.status(200).json(user)
} catch (e) {
res.status(401).send("Unauthorized")
}
}
The user object looks like:
The id of the user
A dictionary of org ids to metadata about the org. Includes all orgs that the user is in
The original ID of the user, if the user was migrated from an external source
If someone on your team is impersonating another user, this will be set to the employee’s ID. By default, user impersonation is turned off and this will be undefined
The values of orgIdToOrgMemberInfo are OrgMemberInfo’s, with the following fields/functions:
The id of the org
The name of the org
A URL-safe version of the name of the org
A function that returns the user’s role within the organization. See Roles and Permissions for more details.
A function that returns the user’s permissions within the organization. See Roles and Permissions
Returns True if the user’s role within the organization matches the role
passed in
Returns True if the user’s role within the organization is at least the role
passed in. If the hierarchy of roles is Owner => Admin => Member, specifying “Admin” will return True for Admins and Owners, but False for Members
Return True if the user has a specific permission. The users’ permissions are derived from their role within this organization.
Return True if the user has all the specified permissions. The users’ permissions are derived from their role within this organization.
validateAccessTokenAndGetUserWithOrgInfo
This function will verify that a request was made by a valid user AND that user is in an organization.
import { validateAccessTokenAndGetUserWithOrgInfo } from "../../lib/propelauth";
export default async function handler(req, res) {
try {
const authHeader = req.headers.authorization
const orgId = req.query.orgId
const {user, orgMemberInfo} = await validateAccessTokenAndGetUserWithOrgInfo(
authHeader,
{orgId: orgId}
)
res.status(200).json(user)
} catch (e) {
res.status(401).send("Unauthorized")
}
}
Argument | Description |
---|---|
Authorization HTTP Header | It expects the header to be in the format Bearer ACCESS_TOKEN . If the Authorization HTTP header is malformed or doesn’t contain a valid access token, an UnauthorizedException is thrown. |
Required Org Info | An object with optional fields orgId and/or orgName . This function will make sure the user who made the request is a member of an organization with the specified orgId and orgName . If the user is NOT a member of the specified organization, a ForbiddenException is thrown. |
It returns an object with two fields:
{
user: //...
orgMemberInfo: //...
}
You can see the structure of the user
and orgMemberInfo
objects above: validateAccessTokenAndGetUser.
Roles and Permissions
A user has a Role within an organization. By default, the available roles are Owner, Admin, or Member, but these can be configured. These roles are also hierarchical, so Owner > Admin > Member.
Roles allow you to control what different users can do within your product. If you want to check a user’s role, you can use validateAccessTokenAndGetUserWithOrgInfoWithExactRole or validateAccessTokenAndGetUserWithOrgInfoWithMinimumRole.
Permissions are arbitrary strings associated with a role. For example, can_view_billing, ProductA::CanCreate, and ReadOnly are all valid permissions. The PropelAuth dashboard allows you to set up these permissions.
You can use validateAccessTokenAndGetUserWithOrgInfoWithPermission or validateAccessTokenAndGetUserWithOrgInfoWithAllPermissions to check for a given permission.
All of these functions, just like validateAccessTokenAndGetUserWithOrgInfo, will take in an authorization header and an organization ID. The last parameter is either a role, permission, or list of permissions depending on the function.
Fetching functions
Fetch user metadata by id
function fetchUserMetadataByUserId(userId, includeOrgs)
Parameters
The id of the user
Whether to return an orgIdToOrgInfo object, default value is false
Successful response (UserMetadata):
{
userId: "e9d3520f-836e-403c-82c2-09843517e1ce",
email: "user@example.com",
emailConfirmed: true,
hasPassword: true,
username: "example",
firstName: "first",
lastName: "last",
pictureUrl: "https://...",
// True if the user's account is locked for security purposes.
locked: false,
enabled: true,
mfaEnabled: false,
createdAt: 1645131680,
lastActiveAt: 1650654711,
// Only returned if includeOrgs = true
orgIdToOrgInfo: {
"2ef0e1fc-234f-4dc0-a50c-35adb1bbb7e4" : {
orgId: "2ef0e1fc-234f-4dc0-a50c-35adb1bbb7e4",
orgName: "ExampleOrganization",
userAssignedRole: "Owner",
}
},
// Only returned if user was migrated from an external system
legacyUserId: "507f191e810c19729de860ea"
}
Fetch user metadata by email
function fetchUserMetadataByEmail(email, includeOrgs)
Parameters
The email of the user
Whether to return an orgIdToOrgInfo object, default value is false
Successful response is the same as Fetch user metadata by id.
Fetch user metadata by username
function fetchUserMetadataByUsername(username, includeOrgs)
Parameters
The username of the user
Whether to return an orgIdToOrgInfo object, default value is false
Successful response is the same as Fetch user metadata by id.
Batch fetch users by ids
function fetchBatchUserMetadataByUserIds(userIds, includeOrgs)
Parameters
List of userIds
Whether to return an orgIdToOrgInfo object, default value is false
Any IDs that don’t have a match are not returned. Duplicate users are only returned once.
A successful response will be a map of the user objects set to keys of the userIds you passed in. For example:
{
"e9d3520f-836e-403c-82c2-09843517e1ce": {
userId: "e9d3520f-836e-403c-82c2-09843517e1ce",
email: "user@example.com",
emailConfirmed: true,
hasPassword: true,
username: "example",
firstName: "first",
lastName: "last",
pictureUrl: "https://...",
// True if the user's account is locked for security purposes.
locked: false,
enabled: true,
mfaEnabled: false,
createdAt: 1645131680,
lastActiveAt: 1650654711,
// Only returned if includeOrgs = true
orgIdToOrgInfo: {
"2ef0e1fc-234f-4dc0-a50c-35adb1bbb7e4" : {
orgId: "2ef0e1fc-234f-4dc0-a50c-35adb1bbb7e4",
orgName: "ExampleOrganization",
userAssignedRole: "Owner",
}
},
// Only returned if user was migrated from an external system
legacyUserId: "507f191e810c19729de860ea"
},
// other user_ids
}
Batch fetch users by emails
function fetchBatchUserMetadataByEmails(emails, includeOrgs)
Parameters
List of user emails
Whether to return an orgIdToOrgInfo object, default value is false
Successful response is the same as Batch fetch users by ids, but the keys are matching email addresses.
Batch fetch users by usernames
function fetchBatchUserMetadataByUsernames(usernames, includeOrgs)
Parameters
List of user usernames
Whether to return an orgIdToOrgInfo object, default value is false
Successful response is the same as Batch fetch users by ids, but the keys are matching usernames.
Search for users
function fetchUsersByQuery(usersQuery)
Searches for users through a customizable query object, usersQuery
. The possible parameters for this query are as follows.
usersQuery
Parameters
The number of results to return at a time. Must be between 1 and 100, default 10.
Used to page over results
How to order the results. Must be one of: CREATED_AT_ASC, CREATED_AT_DESC, LAST_ACTIVE_AT_ASC, LAST_ACTIVE_AT_DESC, EMAIL, USERNAME
Searches for partial matches within email addresses or usernames. port would match a user with email address support@propelauth.com.
Whether to return an orgIdToOrgInfo object, default value is false
Successful response:
{
"totalUsers": 103,
"currentPage": 0,
"pageSize": 10,
"hasMoreResults": true,
"users": [{
// See (1) for example users
}, {
// There will be 10 users in this response
}]
}
Fetch an organization
function fetchOrg(orgId)
Id for the organization
Successful response:
{
"orgId": "d488996d-8ccc-4101-b5f2-131f5f09ddb6"
"name": "OneOfYourCustomers"
}
Fetch all organizations
function fetchOrgsByQuery(orgQuery)
orgQuery
Parameters
The number of results to return at a time. Must be between 1 and 100, default 10.
Used to page over results
How to order the results. Must be one of: CREATED_AT_ASC, CREATED_AT_DESC, NAME
Successful response:
{
"totalOrgs": 21,
"currentPage": 0,
"pageSize": 10,
"hasMoreResults": true,
"orgs": [{
"orgId": "d488996d-8ccc-4101-b5f2-131f5f09ddb6",
"name": "OneOfYourCustomers"
}, {
// There will be 10 orgs in this response
}]
}
Fetch users in organization
function fetchUsersInOrg(usersInOrgQuery)
Searches for users in a specified organization through a customizable query object. The possible parameters for this query are as follows.
Parameters
The organization to fetch users for
The number of results to return at a time. Must be between 1 and 100, default 10.
Used to page over results
Whether to return an orgIdToOrgInfo object, default value is false
Successful response:
{
"totalUsers": 43,
"currentPage": 0,
"pageSize": 10,
"hasMoreResults": true,
"users": [{
// See (1) for example users
}, {
// There will be 10 users in this response, all in the specified organization
}]
}
User Management
Create User
function createUser(createUserRequest)
createUserRequest
Parameters
The user’s email address
Whether the email address should start off as already confirmed. If false, the user is required to confirm the email address before they sign in.
Whether we should send an email immediately to confirm the user’s email address. If false, the user will get a confirmation email when they first sign in.
Whether we should require the user to set or update their password on initial login. Default false
Optional password. If unset, the user can set it themselves via their account page
Optional username. Can only be used if username is enabled in your user schema
Optional first name. Can only be used if name is enabled in your user schema
Optional last name. Can only be used if name is enabled in your user schema
Successful response:
{
"userId": "b5f667fb-e51a-49c6-a396-711e62948689"
}
Update User Email
// Returns true if it was successful, false if the user was not found
function updateUserEmailWrapper(userId, updateUserEmailRequest)
Id for the user
Update User Metadata
// Returns true if it was successful, false if the user was not found
function updateUserMetadata(userId, updateUserMetadataRequest)
Id for the user
Update Password
// Returns true if it was successful, false if the user was not found
function updateUserPassword(userId, updateUserPasswordRequest)
Id for the user
Returns true if the user’s password was updated.
Delete user
function deleteUser(userId)
Id for the user
Returns true if the user was deleted.
Disable user
function disableUser(userId)
Id for the user
Returns true if the user was disabled. Afterwards, the user is logged out and unable to log back in.
Enable user
function enableUser(userId)
Id for the user
Returns true if the user was enabled, allowing them to log in again.
Migrate User from External Source
Similar to Create User, but for cases where you already have a user stored in an external system. You can, for example, pass in a password hash for an existing user, and they will be able to login with their same password. It is also possible to provide an existing identifier, and we will store and return it along with our future identifiers, allowing you to link them.
function migrateUserFromExternalSource(migrateUserFromExternalSourceRequest)
Successful response:
{
"userId": "b5f667fb-e51a-49c6-a396-711e62948689"
}
Create Magic Link
Creates a magic link that a user can use to log in. Use this API if you’d prefer to send the magic link to the customer yourself, otherwise, we have createUser which will email them directly.
function createMagicLink(createUserRequest)
Successful response:
{
"url": "https://auth.yourdomain.com/..."
}
Create Access Token
Our frontend libraries allow you to get access tokens that can be sent to the backend. The backend is then responsible for verifying these tokens.
For testing purposes, you may want to create access tokens separately from the frontend and set a custom expiration time. With this API, you can create access tokens for users programmatically and set a custom expiration.
function createAccessToken(createAccessTokenRequest)
Successful response:
{
"access_token": "..."
}
Org Management
Create Organization
function createOrg(createOrgRequest)
Successful response:
{
"orgId": "d488996d-8ccc-4101-b5f2-131f5f09ddb6"
}
Add user to organization
function addUserToOrg(addUserToOrgRequest)
Returns true if the user was successfully added to the organization.
Allow organization to set up SAML connection
function allowOrgToSetupSamlConnection(orgId)
The org’s ID
Returns true if successful, meaning the organization can now set up SAML connections.
Disallow organization to set up SAML connection
function disallowOrgToSetupSamlConnection(orgId: string): Promise<boolean>
The org’s ID
Returns true if successful, meaning the organization can no longer set up SAML connections.
Update Organization Metadata
// Returns true if it was successful, false if the user was not found
function updateOrg(updateOrgRequest)