feathers-authentication-management

website·Indexed 30 days ago

https://feathers-a-m.netlify.app/

A service for Feathers applications providing sign-up verification, forgotten password reset, and authentication management. Includes documentation on service calls, configuration, process flows, and service hooks such as addVerification, isVerified, and removeVerification.

Tokens
6.5K
Snippets
30
Records
41
Agent score
75%

What's inside feathers-authentication-management

  1. Overview of feathers-authentication-management

    feathers-authentication-management is an extension for FeathersJS that adds essential local authentication capabilities not found in the Feathers core LocalStrategy. It provides mechanisms for verifying user identities (e.g., email or phone) and managing secure account changes via communication transports like email or SMS.

    Key features include:

    • User verification via token-based URLs.
    • Password reset notifications for forgotten passwords.
    • Secure password change workflows.
    • Identity change processing (e.g., updating an email address or cellphone number).

    The library supports both long tokens (30 characters by default) for URLs and short tokens (6 digits/characters by default) for manual entry, such as in SMS messages.

  2. Implement authentication actions using different service patterns

    Depending on your architecture, you can trigger actions like sendResetPwd using three different patterns. Note that Separate Services and Custom Methods use a flattened data object.
    // 1. Old Fashioned: Single service with 'action' and 'value' keys
    app.use('auth-management', new AuthenticationManagementService(app, options));
    app.service("auth-management").create({
      action: "sendResetPwd",
      value: { email: "me@example.com" },
    });
    
    // 2. Separate Service: Dedicated service per action
    const { SendResetPwdService } = require('feathers-authentication-management');
    app.use("auth-management/send-reset-password", new SendResetPwdService(app, options));
    app.service("auth-management/send-reset-password").create({
      user: { email: "me@example.com" },
    });
    
    // 3. Custom Method: Feathers v5 style method on the main service
    app.use('auth-management', new AuthenticationManagementService(app, options));
    app.service("auth-management").sendResetPassword({
      user: { email: "me@example.com" },
    });
  3. Implement the notifier function for user notifications

    The feathers-authentication-management service relies on a custom notifier function to send notifications (e.g., via feathers-mailer). The service calls this function with three parameters: type (the action type), the user object, and notifierOptions. For actions like resendVerifySignup, the verification token is available within the user object data.
  4. Verify user signup from the client side

    To verify a user's signup, the client application must send the verification token (received via email) to the auth-management service. This is done by making a POST request to the /auth-management endpoint with a specific action payload. Upon successful validation, the service triggers a confirmation email.
    // Endpoint: POST /auth-management
    // Request body:
    {
      "action": "verifySignupLong",
      "value": "THE_VERIFICATION_TOKEN"
    }
  5. Secure authentication-management properties in Feathers

    To protect sensitive authentication data, implement hooks that prevent PATCH or PUT calls on internal authentication-management properties. This ensures that users cannot manually modify verification status or reset tokens via API updates.
    // users.hooks.js
    before: {
      update: [
        disallow("external")
      ],
      patch: [
        iff(isProvider('external'), preventChanges(
          true,
          'isVerified',
          'resetExpires',
          'resetShortToken',
          'resetToken',
          'verifyChanges',
          'verifyExpires',
          'verifyShortToken',
          'verifyToken',
        )),
      ],
    },
  6. Migrate to feathers-authentication-management v4

    Migrating to feathers-authentication-management (f-a-m) v4 is generally straightforward with no breaking changes for basic installations. The library has been rewritten in TypeScript to provide better IDE autocompletion.
    npm i feathers-authentication-management
  7. Implement Password Reset flow

    Password resets are managed by the feathers-authentication-management service to ensure security via user verification.

    1. Initiation: The client triggers the process by making a sendResetPwd service call to the feathers-authentication-management service.
    2. Token Handling: The service generates a short and/or long password reset token, saves it to the user item, and triggers the notifier function to send the token to the user.
    3. Reset Execution: The user follows the token URL to the client application, provides a new password, and the client sends both the new password and the reset token to the Feathers API to finalize the change.
  8. Install and register feathers-authentication-management

    To add authentication management to your Feathers application, install the service along with feathers-mailer (used for sending notifications). The service requires a Feathers application already configured with local authentication.
    npm i feathers-authentication-management feathers-mailer
    // services/index.js
    const authManagement = require("./auth-management/auth-management.service.js");
    
    module.exports = function (app) {
      app.configure(authManagement);
    };
    
    // services/auth-management/auth-management.service.js
    const { AuthenticationManagementService } = require("feathers-authentication-management");
    const notifier = require("./notifier");
    
    module.exports = function (app) {
      app.use(
        "/auth-management",
        new AuthenticationManagementService(app, {
          notifier: notifier(app),
        })
      );
    };
  9. Prerequisites for installing feathers-authentication-management

    To install and configure feathers-authentication-management, you must have a Feathers application that meets the following requirements:

    1. Configured with local authentication.
    2. Configured with a communication transport (e.g., an email or SMS service) to notify users.
  10. Call feathers-authentication-management service methods

    The feathers-authentication-management service can be invoked via the Feathers client, plain HTTP requests, or internal server calls. The primary way to trigger specific management actions is by calling the .create() method on the service with an action and a value object.
    // Example: Sending a password reset request
    app.service("auth-management").create({
      action: "sendResetPwd",
      value: {
        email: "me@example.com",
      },
    });
  11. Implement Sign Up Verification flow

    Sign up verification in feathers-authentication-management is handled via an addVerification hook during the create method of the users service.

    1. Token Generation: The hook automatically creates long and/or short verification tokens and stores them in the user record fields verifyToken and verifyShortToken.
    2. Expiration: The expiration date is calculated and stored in the verifyExpires field.
    3. Notification: The service does NOT automatically send notifications. You must implement a call to your notifier function within the after hook of the users create method.
    4. Verification Process: The user receives a token (via email URL or SMS). The client application should capture this token and send it to the Feathers API to complete the verification.
  12. Configure Authentication Management Service options

    The AuthenticationManagementService accepts an options object to customize token lengths, timeouts, and user identification. Key configuration parameters include:

    • service: The path to the user items service (default: /users).
    • skipIsVerifiedCheck: If false (default), password resets are blocked if the email is not verified.
    • sanitizeUserForClient: A function to modify the user object returned in responses. To return an empty object, use () => ({}).
    • notifier: A function (type, user, notifierOptions) that returns a Promise to handle communications (email, SMS, etc.).
    • longTokenLen: Half the length of the long token. Default is 15 (resulting in 30 characters).
    • shortTokenLen: Length of the short token (default: 6).
    • shortTokenDigits: If true (default), short tokens contain only digits.
    • delay: Lifetime for email verification tokens in milliseconds (default: 432000000 or 5 days).
    • resetDelay: Lifetime for password reset tokens in milliseconds (default: 7200000 or 2 hours).
    • resetAttempts: Number of invalid token submissions allowed before the token is removed (default: 0).
    • reuseResetToken: If true, the same reset token is used for multiple resets in a short period; the token is not hashed in the DB (default: false).
    • identifyUserProps: Array of property names that uniquely identify a user (default: ['email']). These are the only properties changeable via verification.
    • passwordField: The name of the password field in the user model (default: password).
    • passParams: A function (params) => Params used to pass parameters from the auth-management service to the users service.