CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-loopback

LoopBack is a highly-extensible, open-source Node.js framework that enables developers to create dynamic end-to-end REST APIs with minimal coding.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

auth.mddocs/

Authentication & Authorization

LoopBack's comprehensive authentication and authorization system provides user management, access tokens, role-based access control, and fine-grained ACL permissions through built-in models and middleware.

Capabilities

User Management

Built-in User model with authentication, email verification, and password management.

/**
 * User model for authentication and user management
 */
const User = loopback.User;

// Static authentication methods
/**
 * Authenticate user with credentials
 * @param {Object} credentials - Login credentials
 * @param {string} credentials.email - User email
 * @param {string} credentials.password - User password
 * @param {string|Object} include - Relations to include in response
 * @param {Function} callback - Callback function
 */
User.login(credentials, include, callback);

/**
 * Logout user by token ID
 * @param {string} tokenId - Access token ID
 * @param {Function} callback - Callback function
 */
User.logout(tokenId, callback);

// Instance authentication methods
/**
 * Login this user instance
 * @param {Object} credentials - Login credentials
 * @param {string|Object} include - Relations to include
 * @param {Function} callback - Callback function
 */
user.login(credentials, include, callback);

/**
 * Logout this user instance
 * @param {string} tokenId - Access token ID
 * @param {Function} callback - Callback function
 */
user.logout(tokenId, callback);

/**
 * Send email verification
 * @param {Object} options - Verification options
 * @param {string} options.type - Verification type ('email')
 * @param {string} options.to - Email address to send to
 * @param {string} options.from - From email address
 * @param {string} options.subject - Email subject
 * @param {string} options.redirect - Redirect URL after verification
 * @param {Function} callback - Callback function
 */
user.verify(options, callback);

/**
 * Confirm email verification
 * @param {string} uid - User ID
 * @param {string} token - Verification token
 * @param {string} redirect - Redirect URL
 * @param {Function} callback - Callback function
 */
user.confirm(uid, token, redirect, callback);

/**
 * Reset password via email
 * @param {Object} options - Reset options
 * @param {string} options.email - User email address
 * @param {Function} callback - Callback function
 */
user.resetPassword(options, callback);

/**
 * Change user password
 * @param {string} oldPassword - Current password
 * @param {string} newPassword - New password
 * @param {Function} callback - Callback function
 */
user.changePassword(oldPassword, newPassword, callback);

/**
 * Set user password
 * @param {string} newPassword - New password
 * @param {Function} callback - Callback function
 */
user.setPassword(newPassword, callback);

/**
 * Create access token for this user
 * @param {Object} data - Token data
 * @param {Object} options - Creation options
 * @param {Function} callback - Callback function
 */
user.createAccessToken(data, options, callback);

/**
 * Verify if plain text password matches user's password
 * @param {string} plain - Plain text password
 * @param {Function} callback - Callback function
 */
user.hasPassword(plain, callback);

User Model Properties:

interface UserProperties {
  id: any;                    // User ID
  username: string;           // Username (optional)
  password: string;           // Hashed password
  email: string;              // Email address (required)
  emailVerified: boolean;     // Email verification status
  verificationToken: string;  // Email verification token
  realm: string;              // User realm (optional)
  created: Date;              // Creation timestamp
  lastUpdated: Date;          // Last update timestamp
}

Usage Example:

const User = app.models.User;

// Register new user
User.create({
  email: 'user@example.com',
  password: 'secret123'
}, (err, user) => {
  if (err) return console.error(err);
  
  // Send verification email
  user.verify({
    type: 'email',
    to: user.email,
    from: 'noreply@myapp.com',
    subject: 'Verify your email',
    redirect: '/verified'
  }, (err, result) => {
    console.log('Verification email sent');
  });
});

// Login user
User.login({
  email: 'user@example.com',
  password: 'secret123'
}, 'user', (err, token) => {
  if (err) return console.error(err);
  console.log('Access token:', token.id);
  console.log('User:', token.user);
});

Access Token Management

Built-in AccessToken model for managing authentication tokens.

/**
 * AccessToken model for authentication tokens
 */
const AccessToken = loopback.AccessToken;

/**
 * AccessToken properties
 */
interface AccessTokenProperties {
  id: string;           // Token ID (the actual token)
  ttl: number;          // Time to live in seconds
  scopes: string[];     // Allowed scopes
  created: Date;        // Creation timestamp
  userId: any;          // Associated user ID
}

/**
 * AccessToken relationships
 */
interface AccessTokenRelations {
  user: User;           // belongsTo User
}

Application Management

Built-in Application model for registering client applications.

/**
 * Application model for client application registration
 */
const Application = loopback.Application;

/**
 * Application properties
 */
interface ApplicationProperties {
  id: string;                 // Application ID
  name: string;               // Application name
  description: string;        // Application description
  icon: string;              // Application icon URL
  owner: string;             // Owner user ID
  collaborators: string[];    // Collaborator user IDs
  email: string;             // Contact email
  url: string;               // Application URL
  callbackUrls: string[];    // OAuth callback URLs
  permissions: string[];      // Granted permissions
}

Role-Based Access Control

Built-in Role and RoleMapping models for role-based permissions.

/**
 * Role model for defining user roles
 */
const Role = loopback.Role;

/**
 * Check if principal is in role
 * @param {string} role - Role name or ID
 * @param {Object} context - Access context
 * @param {Function} callback - Callback function
 */
Role.isInRole(role, context, callback);

/**
 * Get roles for context
 * @param {Object} context - Access context
 * @param {Function} callback - Callback function
 */
Role.getRoles(context, callback);

/**
 * Role properties
 */
interface RoleProperties {
  id: any;              // Role ID
  name: string;         // Role name (unique)
  description: string;  // Role description
  created: Date;        // Creation timestamp
  modified: Date;       // Last modification timestamp
}

/**
 * RoleMapping model for assigning roles to principals
 */
const RoleMapping = loopback.RoleMapping;

/**
 * RoleMapping properties
 */
interface RoleMappingProperties {
  id: any;                  // Mapping ID
  principalType: string;    // Principal type (USER, APP, ROLE)
  principalId: string;      // Principal ID
  roleId: any;             // Role ID
}

/**
 * Principal types
 */
const Principal = {
  USER: 'USER',
  APP: 'APP', 
  ROLE: 'ROLE'
};

Usage Example:

const Role = app.models.Role;
const RoleMapping = app.models.RoleMapping;

// Create admin role
Role.create({
  name: 'admin',
  description: 'Administrator role'
}, (err, role) => {
  if (err) return console.error(err);
  
  // Assign role to user
  RoleMapping.create({
    principalType: 'USER',
    principalId: userId,
    roleId: role.id
  }, (err, mapping) => {
    console.log('User assigned to admin role');
  });
});

Access Control Lists (ACL)

Built-in ACL model for fine-grained permission control.

/**
 * ACL model for access control rules
 */
const ACL = loopback.ACL;

/**
 * Check permission for context
 * @param {Object} context - Access context
 * @param {Function} callback - Callback function  
 */
ACL.checkPermission(context, callback);

/**
 * Check access for context
 * @param {Object} context - Access context
 * @param {Function} callback - Callback function
 */
ACL.checkAccessForContext(context, callback);

/**
 * ACL properties
 */
interface ACLProperties {
  id: any;                  // ACL ID
  model: string;            // Model name (* for all)
  property: string;         // Property name (* for all)
  accessType: string;       // Access type (READ, WRITE, EXECUTE, *)
  permission: string;       // Permission (ALLOW, DENY)
  principalType: string;    // Principal type (USER, APP, ROLE)
  principalId: string;      // Principal ID
}

/**
 * Access types
 */
const AccessType = {
  READ: 'READ',
  WRITE: 'WRITE', 
  EXECUTE: 'EXECUTE',
  ALL: '*'
};

/**
 * Permission types
 */
const Permission = {
  ALLOW: 'ALLOW',
  DENY: 'DENY'
};

Access Context System

Access context objects for permission checking.

/**
 * Access context for permission evaluation
 */
class AccessContext {
  /**
   * Create access context
   * @param {Object} context - Context properties
   */
  constructor(context);

  /**
   * Add principal to context
   * @param {string} type - Principal type (USER, APP, ROLE)
   * @param {*} id - Principal ID
   * @param {string} name - Principal name
   */
  addPrincipal(type, id, name);

  /**
   * Get user ID from context
   * @returns {*} User ID
   */
  getUserId();

  /**
   * Get user object from context
   * @returns {User} User instance
   */
  getUser();

  /**
   * Get application ID from context
   * @returns {*} Application ID
   */
  getAppId();

  /**
   * Check if context is authenticated
   * @returns {boolean} True if authenticated
   */
  isAuthenticated();

  /**
   * Get allowed scopes
   * @returns {string[]} Array of scope names
   */
  getScopes();

  /**
   * Check if scope is allowed
   * @param {string} scope - Scope name
   * @returns {boolean} True if scope is allowed
   */
  isScopeAllowed(scope);
}

/**
 * Principal representation in access context
 */
class Principal {
  /**
   * Create principal
   * @param {string} type - Principal type
   * @param {*} id - Principal ID
   * @param {string} name - Principal name
   */
  constructor(type, id, name);

  /**
   * Compare with another principal
   * @param {Principal} otherPrincipal - Principal to compare
   * @returns {boolean} True if principals are equal
   */
  equals(otherPrincipal);
}

/**
 * Access request for permission checking
 */
class AccessRequest {
  /**
   * Create access request
   * @param {string} model - Model name
   * @param {string} property - Property name
   * @param {string} accessType - Access type
   * @param {string} permission - Permission
   * @param {string[]} methodNames - Method names
   * @param {Registry} registry - Model registry
   */
  constructor(model, property, accessType, permission, methodNames, registry);

  /**
   * Check if request uses wildcard
   * @returns {boolean} True if wildcard access
   */
  isWildcard();

  /**
   * Check if request exactly matches ACL
   * @param {Object} acl - ACL object
   * @returns {boolean} True if exact match
   */
  exactlyMatches(acl);

  /**
   * Check if request is allowed
   * @returns {boolean} True if allowed
   */
  isAllowed();
}

Scope Management

Built-in Scope model for managing permission scopes.

/**
 * Scope model for permission scopes
 */
const Scope = loopback.Scope;

/**
 * Scope properties
 */
interface ScopeProperties {
  id: any;              // Scope ID
  name: string;         // Scope name
  description: string;  // Scope description
}

Usage Example:

// Define ACL rules in model definition
const Product = loopback.createModel('Product', {
  name: String,
  price: Number
}, {
  acls: [
    // Deny all access by default
    {
      accessType: '*',
      principalType: 'ROLE',
      principalId: '$everyone',
      permission: 'DENY'
    },
    // Allow authenticated users to read
    {
      accessType: 'READ',
      principalType: 'ROLE', 
      principalId: '$authenticated',
      permission: 'ALLOW'
    },
    // Allow admin role full access
    {
      accessType: '*',
      principalType: 'ROLE',
      principalId: 'admin',
      permission: 'ALLOW'
    }
  ]
});

Email Verification and Password Reset

/**
 * Email model for sending emails
 */
const Email = loopback.Email;

/**
 * Send email
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email
 * @param {string} options.from - Sender email
 * @param {string} options.subject - Email subject
 * @param {string} options.text - Plain text content
 * @param {string} options.html - HTML content
 * @param {Function} callback - Callback function
 */
Email.send(options, callback);

Additional Built-in Models

/**
 * Change model for tracking data changes
 */
const Change = loopback.Change;

/**
 * Checkpoint model for replication synchronization
 */
const Checkpoint = loopback.Checkpoint;

/**
 * Key-value model for simple key-value storage
 */
const KeyValueModel = loopback.KeyValueModel;

Usage Example:

const Email = app.models.Email;

Email.send({
  to: 'user@example.com',
  from: 'noreply@myapp.com',
  subject: 'Welcome!',
  html: '<h1>Welcome to our app!</h1>'
}, (err, result) => {
  if (err) return console.error(err);
  console.log('Email sent successfully');
});

docs

application.md

auth.md

datasources.md

index.md

middleware.md

models.md

tile.json