CodeAPI

wix-users-backend

The wix-users-backend module contains functionality for working with your site's users from backend code.

There are three types of users:

  • Visitor: A user who is not logged into your site.
  • Member: A user who is logged into your site.
  • Admin: The owner of the site.

To use the Users API, import wixUsers from the wix-users-backend module:

   import wixUsers from 'wix-users-backend';

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

Table of Contents

PROPERTIES

?
Store values associated with an object.
currentUserGets the current user viewing the site.

FUNCTIONS

?
Perform actions on an object.
approveByEmail( )Approve a member whose status is "Pending" using an email address.
approveByToken( )Approve a member whose status is "Pending" using an approval token.
blockByEmail( )Blocks a member from logging into the site.
register( )Registers a new site member.

OBJECTS

?
Objects used when setting, getting, or calling the properties and methods listed above.
RegistrationResultAn object that contains information about the results of a site registration.

currentUser

Gets the current user viewing the site.

Description

Gets a User object containing information about the user currently viewing the site.

Syntax

get currentUser(): User
TYPE
?
The kind of data the property stores.

Examples

Get the current user's information

import wixUsers from 'wix-users-backend';

// ...

let user = wixUsers.currentUser;

let userId = user.id;           // "r5cme-6fem-485j-djre-4844c49"
let isLoggedIn = user.loggedIn; // true

user.getEmail()
  .then( (email) => {
    let userEmail = email;      // "user@something.com"
  } );

user.getRoles()
  .then( (roles) => {
    let firstRole = roles[0];
    let roleName = firstRole.name;                // "Role Name"
    let roleDescription = firstRole.description;  // "Role Description"
  } );

approveByEmail( )

Approve a member whose status is "Pending" using an email address.

Description

The approveByEmail() function returns a Promise that resolves to a session token when the specified user is approved.

A member's status is "Pending" after you've called the register() function when the site's membership policy is set to manual approval. To learn more about setting you site's membership approval policy, see Editing Your Member Signup Settings.

Pass the member's email address in the email parameter.

Syntax

function approveByEmail(email: string): Promise<string>
PARAMETERS
?
The kind of data the property stores.
email
string
Email address of the user to approve.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<string>

Fulfilled - A session token for logging in the approved user in client-side code. Rejected - Error message.

Examples

Approve a pending member using an email address

This example contains a backend function which approves a pending user using an email address and returns a session token to be used in client-side code to log in the user who was just approved.

import wixUsers from 'wix-users-backend';

export function myBackendFunction(email) {
  wixUsers.approveByEmail(email)
    .then( (sessionToken) => {
      return {sessionToken, "approved": true};
    } );
    .catch( (error) => {
      return {"approved": false, "reason": error};
    } );
  }
}

approveByToken( )

Approve a member whose status is "Pending" using an approval token.

Description

The approveByToken() function returns a Promise that resolves to a session token when the specified user is approved.

A member's status is "Pending" after you've called the register() function when the site's membership policy is set to manual approval. To learn more about setting you site's membership approval policy, see Editing Your Member Signup Settings.

Use the approvalToken parameter of the RegistrationResult object returned from the register() function when calling approveByToken.

Syntax

function approveByToken(token: string): Promise<string>
PARAMETERS
?
The kind of data the property stores.
token
string
Approval token returned by the register() function.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<string>

Fulfilled - A session token for logging in the approved user in client-side code. Rejected - Error message.

Examples

Approve a pending member using an approval token

This example contains a backend function which approves a pending user using an approval token and returns a session token to be used in client-side code to log in the user who was just approved.

import wixUsers from 'wix-users-backend';

export function myBackendFunction(token) {
  wixUsers.approveByToken(token)
    .then( (sessionToken) => {
      return {sessionToken, "approved": true};
    } );
    .catch( (error) => {
      return {"approved": false, "reason": error};
    } );
  }
}

Register a user using a 3rd party for approval

This example demonstrates a common 3rd party approval flow. The backend code calls a 3rd party function that determines whether the user will be approved or not. If approved, the register() function is called, the registration is approved programmatically using the approveByToken() function, and a session token is returned to the calling client-side code. If rejected, the blockByEmail() function is called.

/*******************************
 * backend code - register.jsw *
 *******************************/
import wixUsers from 'wix-users-backend';
import {approveBy3rdParty} from 'some-backend-module';

export function doRegistration(email, password, firstName, lastName) {
  // call a 3rd party API to check if the user is approved
  return approveBy3rdParty(email, password)
    .then( (isApproved) => {
      // if approved by 3rd party
      if (isApproved) {
        // register the user
        return wixUsers.register(email, password, {
          "contactInfo": {
            "firstName": firstName,
            "lastName": lastName
          }
        } )
        // user is now registered and pending approval
        // approve the user
          .then( (result) => wixUsers.approveByToken(result.approvalToken) )
          // user is now active, but not logged in
          // return the session token to log in the user client-side
          .then( (sessionToken) => {
            return {sessionToken, "approved": true};
          } );
      }
      // if not approved by 3rd party
      else {
        return {"approved": false};
      }
    } )
}

/********************
 * client-side code *
 ********************/
import wixUsers from 'wix-users';
import {doRegistration} from 'backend/register';

// ...

let email = // the user's email addresses
let password = // the user's password
let firstName = // the user's first name
let lastName = // the user's last name

doRegistration(email, password, firstName, lastName)
  .then( (result) => {
    if (result.approved)
    // log the user in
      wixUsers.applySessionToken(result.sessionToken);
    else {
      console.log("Not approved!");
    }
  } );

Register a user sending an email for confirmation

This example demonstrates a common email verification flow. A user is initially registered but not yet approved. At registration, a verification email is sent with a link to a verification page. When a user goes to the verification page, the approval is granted using the approveByToken() function and the user is logged into the site.

/*******************************
 * backend code - register.jsw *
 *******************************/
import wixUsers from 'wix-users-backend';
import {sendEmailUsing3rdParty} from 'some-backend-module';

export function doRegistration(email, password, firstName, lastName) {
  // register the user
  return wixUsers.register(email, password, {
    "contactInfo": {
      "firstName": firstName,
      "lastName": lastName
    }
  } )
    .then( (results) => {
      // user is now registered and pending approval
      // send a registration verification email
      return sendEmailUsing3rdParty('verify-registration', email,{
        "name": firstName,
        "verifyLink": `http://domain.com/post-register?token=${approvalToken}`
      } );
    } );
}

export function doApproval(token) {
  // approve the user
  return wixUsers.approveByToken(token)
  // user is now active, but not logged in
  // return the session token to log in the user client-side
    .then( (sessionToken) => {
      return {sessionToken, "approved": true};
    } )
    .catch( (error) => {
      return {"approved": false, "reason": error};
    } );
}

/*********************************
 * client-side registration code *
 *********************************/
import wixUsers from 'wix-users';
import {doRegistration} from 'backend/register';

// ...

let email = // the user's email address
let password = // the user's password
let firstName = // the user's first name
let lastName = // the user's last name

doRegistration(email, password, firstName, lastName)
  .then( () => {
    console.log("Confirmation email sent.");
  } );

/**************************************
 * client-side post-registration code *
 **************************************/
import wixLocation from 'wix-location';
import {doApproval} from 'backend/register';

$w.onReady( () => {
  // get the token from the URL
  let token = wixLocation.query.token;

  doAppoval(token)
    .then( (result) => {
      if (result.approved)
        // log the user in
        wixUsers.applySessionToken(result.sessionToken);
      else
        console.log("Not approved!");
    } );
}

blockByEmail( )

Blocks a member from logging into the site.

Description

The blockByEmail() function returns a Promise that resolves when the specified user has been blocked.

Pass the member's email address in the email parameter.

Syntax

function blockByEmail(email: string): Promise<void>
PARAMETERS
?
The kind of data the property stores.
email
string
Email address of the user to approve.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>

Fulfilled - When specified member is blocked. Rejected - Error message.

Examples

Bloc a member using an email address

import wixUsers from 'wix-users-backend';

export function myBackendFunction(email) {
  wixUsers.blockByEmail(email)
    .then( () => {
      // user has been blocked
    } );
  }
}

register( )

Registers a new site member.

Description

The register() function returns a Promise that resolves to a RegistrationResult object when the user is either registered or is pending registration.

If Site Members is configured for automatic approval, the register() function returns a status of "Active" and the user will be an active member of the site.

If Site Members is configured for manual approval, the register() function returns a status of "Pending" and the user will be a pending member of the site. In order to activate a pending user, the site owner can approve the user manually using the Contacts application or you can call the approveByToken() or approveByEmail() functions.

The sessionToken returned when the new member is "Active" must be applied using the applySessionToken() function in client-side code to complete the user registration by logging in the registered user.

Note

When member registration is set to auto approve, calling the client-side register() function is equally as secure as calling it from backend code. However, when member approval is set to manual, calling the backend version of the register() function allows you to construct more secure approval flows.

Syntax

function register(email: string, password: string, [options: RegistrationOptions]): Promise<RegistrationResult>
PARAMETERS
?
The kind of data the property stores.
email
string
The email address to use when registering the user as a site member.
password
string
The password the newly added site member will use to log in.
options(Optional)
Registration options.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.

Fulfilled - When the user has been registered. Rejected - Error message.

Examples

Register a user using a 3rd party for approval

This example demonstrates a common 3rd party approval flow. The backend code calls a 3rd party function that determines whether the user will be approved or not. If approved, the register() function is called, the registration is approved programmatically, and a session token is returned to the calling client-side code. If rejected, the blockByEmail() function is called.

/*******************************
 * backend code - register.jsw *
 *******************************/
import wixUsers from 'wix-users-backend';
import {approveBy3rdParty} from 'some-backend-module';

export function doRegistration(email, password, firstName, lastName) {
  // call a 3rd party API to check if the user is approved
  return approveBy3rdParty(email, password)
    .then( (isApproved) => {
      // if approved by 3rd party
      if (isApproved) {
        // register the user
        return wixUsers.register(email, password, {
          "contactInfo": {
            "firstName": firstName,
            "lastName": lastName
          }
        } )
        // user is now registered and pending approval
        // approve the user
          .then( (result) => wixUsers.approveByToken(result.approvalToken) )
          // user is now active, but not logged in
          // return the session token to log in the user client-side
          .then( (sessionToken) => {
            return {sessionToken, "approved": true};
          } );
      }
      // if not approved by 3rd party
      else {
        return {"approved": false};
      }
    } )
}

/********************
 * client-side code *
 ********************/
import wixUsers from 'wix-users';
import {doRegistration} from 'backend/register';

// ...

let email = // the user's email addresses
let password = // the user's password
let firstName = // the user's first name
let lastName = // the user's last name

doRegistration(email, password, firstName, lastName)
  .then( (result) => {
    if (result.approved)
    // log the user in
      wixUsers.applySessionToken(result.sessionToken);
    else {
      console.log("Not approved!");
    }
  } );

Register a user sending an email for confirmation

This example demonstrates a common email verification flow. A user is initially registered but not yet approved. At registration, a verification email is sent with a link to a verification page. When a user goes to the verification page, the approval is granted and the user is logged into the site.

/*******************************
 * backend code - register.jsw *
 *******************************/
import wixUsers from 'wix-users-backend';
import {sendEmailUsing3rdParty} from 'some-backend-module';

export function doRegistration(email, password, firstName, lastName) {
  // register the user
  return wixUsers.register(email, password, {
    "contactInfo": {
      "firstName": firstName,
      "lastName": lastName
    }
  } )
    .then( (results) => {
      // user is now registered and pending approval
      // send a registration verification email
      return sendEmailUsing3rdParty('verify-registration', email,{
        "name": firstName,
        "verifyLink": `http://domain.com/post-register?token=${approvalToken}`
      } );
    } );
}

export function doApproval(token) {
  // approve the user
  return wixUsers.approveByToken(token)
  // user is now active, but not logged in
  // return the session token to log in the user client-side
    .then( (sessionToken) => {
      return {sessionToken, "approved": true};
    } )
    .catch( (error) => {
      return {"approved": false, "reason": error};
    } );
}

/*********************************
 * client-side registration code *
 *********************************/
import wixUsers from 'wix-users';
import {doRegistration} from 'backend/register';

// ...

let email = // the user's email address
let password = // the user's password
let firstName = // the user's first name
let lastName = // the user's last name

doRegistration(email, password, firstName, lastName)
  .then( () => {
    console.log("Confirmation email sent.");
  } );

/**************************************
 * client-side post-registration code *
 **************************************/
import wixLocation from 'wix-location';
import {doApproval} from 'backend/register';

$w.onReady( () => {
  // get the token from the URL
  let token = wixLocation.query.token;

  doAppoval(token)
    .then( (result) => {
      if (result.approved)
        // log the user in
        wixUsers.applySessionToken(result.sessionToken);
      else
        console.log("Not approved!");
    } );
}

RegistrationResult

An object that contains information about the results of a site registration.

Syntax

type RegistrationResult = {
  status: string
  sessionToken: string
  approvalToken: string
  user: User
}
MEMBERS
?
The kind of data the property stores.
status
string
Registration status. Either "Pending" or "Active".
sessionToken(Optional)
string

A token used to log in the current user as a site member. Pass the token from your backend code to client-side code and use it when calling the applySessionToken() function. The token is only available when status is "Active".

approvalToken(Optional)
string

A token for approving the user as a site member using the approveByToken() function. The token is safe to pass via email or from client-side code to backend code. The token is only available when status is "Pending".

user
The user that has been registered.