@rs-tech-hub/nestjs-user

User management for NestJS applications with GraphQL support. Create, activate, deactivate, and manage user accounts with status tracking and activity logging.


📚 Table of Contents


🔑 License

This package requires a valid commercial license. A valid license key must be configured to use this package.

Visit https://rstechhub.gumroad.com to purchase a license.

✨ Features

  • 👤 User CRUD - Create and manage user accounts
  • User Activation - Activate users with status tracking
  • 📧 Email Updates - Update user email addresses
  • 🔒 Password Management - Update user passwords with hash/salt
  • 🚫 Deactivation - Deactivate inactive users
  • Disable Users - Permanently disable user accounts
  • 📊 Activity Logging - Track user activities (register, activate, login, etc.)
  • 🔍 User Queries - Retrieve users by ID or email
  • 🔐 Authentication Required - Protected GraphQL operations

📋 Prerequisites

  • Node.js ≥ 18
  • TypeScript ≥ 5.1.0
  • NestJS ≥ 11.1.6
  • Prisma ORM v7.0+
  • GraphQL support configured in your NestJS application

📦 Installation

npm install @rs-tech-hub/nestjs-user \
            @rs-tech-hub/nestjs-auth-core \
            @rs-tech-hub/nestjs-clock \
            @rs-tech-hub/nestjs-license-validator \
            @rs-tech-hub/nestjs-prisma \
            @rs-tech-hub/nestjs-service-operation
yarn add @rs-tech-hub/nestjs-user \
         @rs-tech-hub/nestjs-auth-core \
         @rs-tech-hub/nestjs-clock \
         @rs-tech-hub/nestjs-license-validator \
         @rs-tech-hub/nestjs-prisma \
         @rs-tech-hub/nestjs-service-operation
pnpm add @rs-tech-hub/nestjs-user \
         @rs-tech-hub/nestjs-auth-core \
         @rs-tech-hub/nestjs-clock \
         @rs-tech-hub/nestjs-license-validator \
         @rs-tech-hub/nestjs-prisma \
         @rs-tech-hub/nestjs-service-operation

🚀 Module Registration

Import the module in your NestJS application:

import { Module } from "@nestjs/common";
import { UserModule } from "@rs-tech-hub/nestjs-user";

@Module({
  imports: [UserModule],
})
export class AppModule {}

📖 GraphQL API

Queries

Get Current User

query {
  user_getCurrent {
    id
    email
    Status
    Role
    accountId
    createdAt
    updatedAt
  }
}

Get User by ID

query {
  user_getById(userId: "user-id-here") {
    id
    email
    Status
    Role
    accountId
    createdAt
    updatedAt
  }
}

Get User by Email

query {
  user_getByEmail(email: "user@example.com") {
    id
    email
    Status
    Role
    accountId
    createdAt
    updatedAt
  }
}

💻 Service Usage

Creating Users

import { Injectable } from "@nestjs/common";
import { UserService } from "@rs-tech-hub/nestjs-user";

@Injectable()
export class AuthService {
  constructor(private userService: UserService) {}

  async registerUser(email: string, password: string, accountId: string) {
    const { hash, salt } = this.hashPassword(password);

    const result = await this.userService.create({
      email,
      hash,
      salt,
      accountId,
    });

    if (result.status === "COMPLETED") {
      return result.output;
    }

    throw new Error("User creation failed");
  }
}

Activating Users

async activateUser(userId: string) {
  const result = await this.userService.activate({ id: userId });

  if (result.status === 'COMPLETED') {
    console.log('User activated successfully');
    return result.output;
  }

  throw new Error(result.error?.message || 'Activation failed');
}

Updating Email

async changeUserEmail(userId: string, newEmail: string) {
  const result = await this.userService.updateEmail({
    id: userId,
    email: newEmail,
  });

  return result.output;
}

Updating Password

async changePassword(userId: string, newPassword: string) {
  const { hash, salt } = this.hashPassword(newPassword);

  const result = await this.userService.updatePassword({
    id: userId,
    hash,
    salt,
  });

  return result.output;
}

User Status Management

// Deactivate user (inactive for 3+ months)
async deactivateUser(userId: string) {
  const result = await this.userService.deactivate(userId);
  return result.output;
}

// Permanently disable user
async disableUser(userId: string) {
  const result = await this.userService.disable(userId);
  return result.output;
}

Activity Logging

async logUserActivity(userId: string, activityType: UserActivityType) {
  await this.userService.logActivity({
    userId,
    Type: activityType,
  });
}

Retrieving Users

// Get user by ID
const userResult = await this.userService.getById("user-id");
const user = userResult.output;

// Get user by email
const userResult = await this.userService.getByEmail("user@example.com");
const user = userResult.output;

🔧 Repository Usage

Direct database access via UserRepository:

import { Injectable } from "@nestjs/common";
import { UserRepository } from "@rs-tech-hub/nestjs-user";

@Injectable()
export class UserManagementService {
  constructor(private userRepo: UserRepository) {}

  async findActiveUsers() {
    return this.userRepo.findMany({ Status: "ACTIVE" });
  }

  async countUsers() {
    return this.userRepo.count();
  }

  async deleteUser(userId: string) {
    return this.userRepo.delete({ id: userId });
  }
}

📖 API Reference

UserService Methods

create(input: UserCreateServiceInput): Promise<ServiceResult>

Create a new user with email, hash, salt, and account association.

activate(input: UserActivateServiceInput): Promise<ServiceResult>

Activate a user account and log activation activity.

updateEmail(input: UserUpdateEmailServiceInput): Promise<ServiceResult>

Update user email address (email is normalized to lowercase and trimmed).

updatePassword(data: { id, hash, salt }): Promise<ServiceResult>

Update user password with new hash and salt.

deactivate(userId: string): Promise<ServiceResult>

Deactivate a user (for users inactive for 3+ months).

disable(userId: string): Promise<ServiceResult>

Permanently disable a user account.

logActivity(input: UserLogActivityServiceInput): Promise<ServiceResult>

Log user activity (register, activate, login, update, etc.).

getById(userId: string): Promise<ServiceResult>

Retrieve user by ID.

getByEmail(email: string): Promise<ServiceResult>

Retrieve user by email address.

📊 Data Types

UserStatus Enum

  • PENDING - User created but not activated
  • ACTIVE - User is active and can use the system
  • INACTIVE - User inactive for extended period (3+ months)
  • DISABLED - User permanently disabled

UserRole Enum

  • USER - Regular user
  • ADMIN - Administrator
  • SUPER_ADMIN - Super administrator

UserActivityType Enum

  • REGISTER - User registration
  • ACTIVATE - Account activation
  • LOGIN - User login
  • LOGOUT - User logout
  • UPDATE_EMAIL - Email address update
  • UPDATE_PASSWORD - Password update
  • DEACTIVATE - Account deactivation
  • DISABLE - Account disable

UserCreateServiceInput

{
  email: string; // User email (normalized to lowercase)
  hash: string; // Password hash
  salt: string; // Password salt
  accountId: string; // Associated account ID
}

UserActivateServiceInput

{
  id: string; // User ID to activate
}

UserUpdateEmailServiceInput

{
  id: string; // User ID
  email: string; // New email address
}

🔒 Authentication

All GraphQL queries require authentication. The package uses @rs-tech-hub/nestjs-auth-core for JWT authentication:

  • user_getCurrent - Returns authenticated user's information
  • user_getById - Protected with GqlAuthGuard
  • user_getByEmail - Protected with GqlAuthGuard

⚠️ Error Codes

Error CodeDescription
user-error:activation-key-invalidInvalid activation key
user-error:user-already-activatedUser is already activated
user-error:user-already-inactiveUser is already inactive
user-error:user-already-disabledUser is already disabled
user-error:user-already-existsUser already exists
user-error:user-does-not-existUser not found
user-error:is-current-emailEmail is the same as current
user-error:id-requiredUser ID is required
user-error:no-password-foundNo password found for user
user-error:user-not-activatedUser not activated
user-error:unauthorizedUnauthorized access
user-error:password-reset-key-invalidInvalid password reset key
user-error:password-update-failedPassword update failed
user-error:update-failedUser update failed

💡 Best Practices

  1. Email Normalization: Emails are automatically lowercased and trimmed
  2. Status Transitions: Follow proper status flow (PENDING → ACTIVE → INACTIVE/DISABLED)
  3. Activity Logging: Always log significant user activities
  4. Password Security: Store only hash and salt, never plain passwords
  5. Account Association: Users must be linked to an account
  6. Deactivation Policy: Use deactivate for temporary, disable for permanent
  7. Timestamp Tracking: activatedAt is set when user is activated

📄 License

This package requires a valid commercial license. See LICENSE.txt for details. By using this software, you agree to the terms outlined in the Software License Agreement (SLA.md). The license grants you specific rights to use, modify, and deploy the software within the scope defined in the agreement. For full terms, conditions, and restrictions, please refer to the Software License Agreement.

📋 Release Notes

1.0.0

  • Initial release

1.0.1

  • Fixes user_getCurrent graphql endpoint
  • Updates internal license handling

🆘 Support

For technical support and inquiries: