Skip to content

Latest commit

 

History

History
916 lines (594 loc) · 26.7 KB

index.md

File metadata and controls

916 lines (594 loc) · 26.7 KB

faunauth

faunauth

Table of contents

Interfaces

Type aliases

Variables

Functions

Type aliases

AnomalyCollectionQueryResult

Ƭ AnomalyCollectionQueryResult: CollectionQueryResult<Anomaly[]>

Defined in

types/auth.ts:205


DeleteUserInput

Ƭ DeleteUserInput: Object

Type declaration

Name Type Description
clientConfig? Omit<ClientConfig, "secret"> Fauna client config object
email? string Email address of the user to delete. If email is not provided, userID must be provided.
secret string A Fauna secret. This can either be an accessSecret that was returned after authenticating the user or a Fauna secret that has "admin" permissions.
userID? string ID of the user to delete. If userID is not provided, email must be provided.

Defined in

auth/deleteUser.ts:9


LoginInput

Ƭ LoginInput: LoginInputWithEmail | LoginInputWithUsername

Defined in

auth/login.ts:41


Maybe

Ƭ Maybe<T>: T | null

graphql-code-generator generates types that use a Maybe generic type. To keep things consistent, we're also going to do that here.

Type parameters

Name
T

Defined in

types/general.ts:5


RefreshResult

Ƭ RefreshResult: false | FaunaLoginResult | AnomalyError

Defined in

types/auth.ts:209


RegisterInput

Ƭ RegisterInput<SendEmailResult>: BaseRegisterInput & AuthInputWithEmailTemplate<SendEmailResult> | AuthInputWithCustomEmail<SendEmailResult>

Type parameters

Name
SendEmailResult

Defined in

auth/register.ts:38


RequestPasswordResetInput

Ƭ RequestPasswordResetInput<SendEmailResult>: BaseRequestPasswordResetInput & AuthInputWithEmailTemplate<SendEmailResult> | AuthInputWithCustomEmail<SendEmailResult>

Type parameters

Name
SendEmailResult

Defined in

auth/sendConfirmationEmail.ts:30


SendCustomEmail

Ƭ SendCustomEmail<SendEmailResult>: (callbackUrl: string) => Promise<SendEmailResult>

Type parameters

Name
SendEmailResult

Type declaration

▸ (callbackUrl): Promise<SendEmailResult>

Async function for sending an email; accepts a callback URL and returns a Promise that resolves to the generic ``. Use this when you want to provide your own email template logic.

remarks Typically this will a wrapper around something like https://www.npmjs.com/package/@sendgrid/mail. If using @sendgrid/mail as sgMail, you will need to set an API key using sgMail.setApiKey('API_KEY') before passing in sgMail as a SendCustomEmail function.

Parameters
Name Type
callbackUrl string
Returns

Promise<SendEmailResult>

Defined in

types/email.ts:119


SendEmailFromTemplate

Ƭ SendEmailFromTemplate<SendEmailResult>: (input: EmailTemplateInput) => Promise<SendEmailResult>

Type parameters

Name
SendEmailResult

Type declaration

▸ (input): Promise<SendEmailResult>

Async function for sending an email; accepts a EmailTemplateInput and returns a Promise that resolves to the generic ``. Use this when you want to send emails with the built-in template system provided by faunauth.

remarks Typically this will be a wrapper around something like https://www.npmjs.com/package/@sendgrid/mail. If using @sendgrid/mail as sgMail, you will need to set an API key using sgMail.setApiKey('API_KEY') before passing in sgMail as a SendEmailFromTemplate function.

Parameters
Name Type
input EmailTemplateInput
Returns

Promise<SendEmailResult>

Defined in

types/email.ts:105


SetUp

Ƭ SetUp: (testName: string) => Promise<TestContext>

Type declaration

▸ (testName): Promise<TestContext>

Parameters
Name Type
testName string
Returns

Promise<TestContext>

Defined in

types/test.ts:15


TearDown

Ƭ TearDown: (testName: string, context: TestContext) => Promise<true>

Type declaration

▸ (testName, context): Promise<true>

Parameters
Name Type
testName string
context TestContext
Returns

Promise<true>

Defined in

types/test.ts:17


TestContext

Ƭ TestContext: Object

Type declaration

Name Type
databaseClients DatabaseClients
loginResult? FaunauthError | FaunaLoginResult
secret? string
testDocumentRef? Maybe<values.Ref>

Defined in

types/test.ts:8


URLParamTuple

Ƭ URLParamTuple: [name: string, value: string]

A [name, value] pair that will be used to create a URL search parameter.

Defined in

utils/addParamsToPath.ts:4


UserCollectionQueryResult

Ƭ UserCollectionQueryResult: CollectionQueryResult<User[]>

Defined in

types/auth.ts:207


UserDataInput

Ƭ UserDataInput: Omit<UserData, "id">

Data for creating a new user. The id is not included because it is auto-generated when the user is created in Fauna.

Defined in

types/auth.ts:158

Variables

errors

Const errors: Object

Type declaration

Name Type
failedToChangePassword string
failedToCreateToken string
failedToLogout string
failedToRefreshToken string
failedToRegisterUser string
failedToSendEmail string
failedToSendEmailAndDeleteUser string
failedToSetPassword string
failedToUpdateUser string
invalidEmailConfirmationToken string
invalidEmailOrPassword string
invalidEmailOrSecret string
invalidOldPassword string
invalidUsernameOrPassword string
missingAccessToken string
missingAdminKey string
missingEmailAndUserID string
missingPublicFaunaKey string
missingSecret string
missingUserRef string
passwordAlreadyInUse string
unknownServerError string
userAlreadyExists string
userDoesNotExist string

Defined in

fauna/src/errors.ts:1

Functions

addParamsToPath

addParamsToPath(input): string

Add URL search params to a path. If the path contains existing search parameters or a hash, they will be preserved.

Search params are encoded to their UTF-8 equivalent by the new URLSearchParams constructor, similar to how https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent works.

Parameters

Name Type Description
input AddParamsToPathInput see AddParamsToPathInput

Returns

string

the input.path with the input.params added as search params

Defined in

utils/addParamsToPath.ts:28


changePassword

changePassword(input): Promise<ServerLoginResult>

Change the password for a user who knows their old password.

The input.email is converted to lowercase, so it is case-insensitive.

Parameters

Name Type
input ChangePasswordInput

Returns

Promise<ServerLoginResult>

Defined in

auth/changePassword.ts:41


createOrUpdateUserRole

createOrUpdateUserRole(__namedParameters): Promise<void>

Create or update a Fauna role that is scoped appropriately for a user. You will need to call this function with a privileges array that is populated for your particular database structure. A good way to do this is by creating a script that calls createOrUpdateUserRole and passes in the privileges that your app requires. Then you can call your script when you need to set up the role, allowing you to save your permissions in a reproducible form.

Here is an example of a script that calls createOrUpdateUserRole:

// scripts/setUpUserRole.js

// Read more on how dotenv works here: https://github.com/motdotla/dotenv
require('dotenv').config();

const { exit } = require('process');
const { Collection, Index } = require('faunadb');
const { createOrUpdateUserRole } = require('faunauth');

const faunaAdminKey = process.env.FAUNA_ADMIN_KEY;

// Create a FaunaDB role that is scoped appropriately for a user.
const main = async () => {
if (!faunaAdminKey) {
console.error('process.env.FAUNA_ADMIN_KEY is missing, closing');

exit(1);
}

try {
await createOrUpdateUserRole({
faunaAdminKey,
roleName: 'user',
privileges: [
// This is an example of what a privilege object looks like; you would need to
// change it to fit your needs.
{
resource: Collection('dinos'),
actions: {
create: true,
read: true,
delete: true,
write: true,
},
},
// ... more privileges go here
],
});
} catch(err) {
console.error('createOrUpdateUserRole threw error:\n', err);

exit(1);
}

exit(0);
};

main();

You could then set up a package.json script that calls this function, ie:

 {
     scripts: {
         set-up-user-role: "node scripts/setUpUserRole.js";
     }
 }

Parameters

Name Type
__namedParameters CreateOrUpdateUserRoleInput

Returns

Promise<void>

Defined in

utils/createOrUpdateUserRole.ts:95


deleteUser

deleteUser(input): Promise<UserResult>

Delete a user.

Parameters

Name Type
input DeleteUserInput

Returns

Promise<UserResult>

a Promise that resolves to the UserResult containing data for the user that was just deleted.

Defined in

auth/deleteUser.ts:34


getEmailContent

getEmailContent(input): Object

Returns the HTML template for an authentication email, which will be used to confirm either a user registration or a password reset.

Parameters

Name Type Description
input EmailTemplateConfig see EmailTemplateConfig

Returns

Object

Name Type
html string
subject string
text string

Defined in

email/getEmailContent.ts:12


login

login(input): Promise<ServerLoginResult>

Log a user in. The input can include either an email or a username in order to identify the user. The returned data will include an accessSecret, refreshSecret and user object including the user's id as well as any other data on the User document.

If the email/username or password is incorrect, this function throws the same error. This is by design; the person trying to log in should not be allowed to know which of these values is incorrect because it would help them guess the other value if they are a malicious actor.

The input.email or input.username is converted to lowercase, so it is case-insensitive.

Parameters

Name Type Description
input LoginInput LoginInput

Returns

Promise<ServerLoginResult>

  • {@link LoginResult}

Defined in

auth/login.ts:56


loginWithMagicLink

loginWithMagicLink(input): Promise<ServerLoginResult>

Log in a user via a link sent in an email. The link contains an encoded secret which must be passed to this function as the secret argument. This function checks the secret to see if a token exists in the database which matches the secret, has not expired, and belongs to the user associated with the given email. If these conditions are met, the user is logged in. The returned data will include an accessSecret, refreshSecret and user object including the user's id as well as any other data on the User document.

The input.email is converted to lowercase, so it is case-insensitive.

Parameters

Name Type
input LoginWithMagicLinkInput

Returns

Promise<ServerLoginResult>

Defined in

auth/loginWithMagicLink.ts:42


logout

logout(input): Promise<boolean>

Log a user out.

Parameters

Name Type Description
input LogoutInput LogoutInput

Returns

Promise<boolean>

true if user was signed out

Defined in

auth/logout.ts:27


register

register<SendEmailResult>(input): Promise<SendEmailResult>

Register a user by creating a user in the User collection and sending the user an email with a confirmation link to the specified callbackUrl that includes the encoded token and email address. setPassword will need to be invoked with the decoded token to complete the process.

A unique input.userData.email is required. If desired, you can provide a unique username on input.userData.username. If you do this (or if you later modify the user by adding a username to its data property), you can call the login function with the username rather than the email.

Both input.userData.email and input.userData.username are converted to lowercase, so they are case-insensitive.

remarks The token and email are wrapped into an object, then Base64-encoded and appended as a single URL search parameter called data. Your client-side code can read these values by doing:

const { email, token } = JSON.parse(atob(data));

You can either use the built-in email template system by passing in an input that conforms to AuthInputWithEmailTemplate, or create your own email template by passing in an input that conforms to AuthInputWithCustomEmail.

Type parameters

Name
SendEmailResult

Parameters

Name Type
input RegisterInput<SendEmailResult>

Returns

Promise<SendEmailResult>

the generic `` that you specify

Defined in

auth/register.ts:69


registerAdmin

registerAdmin(input): Promise<ServerLoginResult>

Register a user by creating a user in the User collection without verifying an email confirmation token. This is intended for use only when creating an account as an administrator and only works with a Fauna client that is authenticated with an admin key. Use this with caution.

A unique input.userData.email is required. If desired, you can provide a unique username on input.userData.username. If you do this (or if you later modify the user by adding a username to its data property), you can call the login function with the username rather than the email.

Both input.userData.email and input.userData.username are converted to lowercase, so they are case-insensitive.

Parameters

Name Type
input RegisterAdminInput

Returns

Promise<ServerLoginResult>

a ServerLoginResult

Defined in

auth/registerAdmin.ts:45


rotateTokens

rotateTokens(input): Promise<TokenPair>

Using the user's current refresh token, get a new pair of access & refresh tokens.

Parameters

Name Type Description
input RotateTokensInput RotateTokensInput

Returns

Promise<TokenPair>

the new access and refresh tokens if successful

Defined in

auth/rotateTokens.ts:24


sendConfirmationEmail

sendConfirmationEmail<SendEmailResult>(input): Promise<SendEmailResult>

Create an email confirmation token in the database, then send an email with a confirmation link that includes the token and email address. Upon clicking the link, either setPassword or loginWithMagicLink will need to be invoked with the decoded token to complete the process.

The input.email is converted to lowercase, so it is case-insensitive.

remarks The token and email are wrapped into an object, then Base64-encoded and appended as a single URL search parameter called data. Your client-side code can read these values by doing:

 // If you're using react-router, you can get search params with useSearchParams()
 const search = window.location.search
 const urlQuery = new URLSearchParams(search);
 const data = urlQuery.get('data');

 try {
     const { email, token } = JSON.parse(atob(data));
 } catch {
     // could not read data from URL search parameter
 }

You can either use the built-in email template system by passing in an input that conforms to AuthInputWithEmailTemplate, or create your own email template by passing in an input that conforms to AuthInputWithCustomEmail.

Type parameters

Name
SendEmailResult

Parameters

Name Type
input RequestPasswordResetInput<SendEmailResult>

Returns

Promise<SendEmailResult>

the generic `` that you specify

Defined in

auth/sendConfirmationEmail.ts:65


setPassword

setPassword(input): Promise<ServerLoginResult>

Set a user's password in order to finish either the "register" or "forgot password" flow. By now, the user has already triggered either register or sendConfirmationEmail to request a token. The token has been created in the database, and an email has been sent to the user with a link which includes an encoded copy of the token. The user has clicked the link, opening a page in the frontend app that calls an API endpoint which calls this function. This function checks the token to see if an exact match for the token exists in the database which:

  • has not expired
  • belongs to the user associated with the given email

If these conditions are met, the given password is set as the user's current password. The input.email is converted to lowercase, so it is case-insensitive.

Parameters

Name Type
input SetPasswordInput

Returns

Promise<ServerLoginResult>

Defined in

auth/setPassword.ts:48


updateUser

updateUser(input): Promise<UserResult>

Update data for the current user.

Parameters

Name Type
input UpdateUserInput

Returns

Promise<UserResult>

a Promise that resolves to the UserResult

Defined in

auth/updateUser.ts:32