Intermediate
30 mins

User Management

Learn how to implement secure and scalable user management features in your applications. This guide covers user authentication, authorization, and data management.

Prerequisites

  • Understanding of database operations
  • Knowledge of authentication concepts
  • Experience with API development
  • Familiarity with security practices

User Management Overview

User Management Workflow

Visual representation of the user management lifecycle and key components.

1

User Model Setup

Define the user model and database schema:

// User schema
CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  email TEXT UNIQUE NOT NULL,
  password_hash TEXT NOT NULL,
  first_name TEXT,
  last_name TEXT,
  role TEXT NOT NULL DEFAULT 'user',
  status TEXT NOT NULL DEFAULT 'active',
  last_login TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

// User profile schema
CREATE TABLE user_profiles (
  user_id UUID PRIMARY KEY REFERENCES users(id),
  avatar_url TEXT,
  bio TEXT,
  location TEXT,
  preferences JSONB DEFAULT '{}',
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

// Enable RLS
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
ALTER TABLE user_profiles ENABLE ROW LEVEL SECURITY;
2

User Service Implementation

Create user management service with core functionality:

class UserService {
  async createUser(userData) {
    const { email, password, firstName, lastName } = userData;
    
    // Hash password
    const passwordHash = await bcrypt.hash(password, 12);
    
    // Create user
    const user = await db.transaction(async (trx) => {
      const [user] = await trx('users').insert({
        email,
        password_hash: passwordHash,
        first_name: firstName,
        last_name: lastName
      }).returning('*');
      
      // Create profile
      await trx('user_profiles').insert({
        user_id: user.id
      });
      
      return user;
    });
    
    return user;
  }
  
  async updateUser(userId, updates) {
    const user = await db('users')
      .where({ id: userId })
      .update({
        ...updates,
        updated_at: new Date()
      })
      .returning('*');
      
    return user;
  }
  
  async deleteUser(userId) {
    await db.transaction(async (trx) => {
      await trx('user_profiles')
        .where({ user_id: userId })
        .delete();
        
      await trx('users')
        .where({ id: userId })
        .delete();
    });
  }
}
3

Authentication Integration

Implement user authentication and session management:

// Authentication middleware
const authenticate = async (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({ error: 'Authentication required' });
  }
  
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const user = await db('users')
      .where({ id: decoded.userId })
      .first();
      
    if (!user) {
      throw new Error('User not found');
    }
    
    req.user = user;
    next();
  } catch (error) {
    res.status(401).json({ error: 'Invalid token' });
  }
};

// Login handler
async function login(email, password) {
  const user = await db('users')
    .where({ email })
    .first();
    
  if (!user) {
    throw new Error('Invalid credentials');
  }
  
  const valid = await bcrypt.compare(password, user.password_hash);
  
  if (!valid) {
    throw new Error('Invalid credentials');
  }
  
  const token = jwt.sign(
    { userId: user.id },
    process.env.JWT_SECRET,
    { expiresIn: '24h' }
  );
  
  return { user, token };
}
4

User Management API

Create RESTful API endpoints for user management:

// User routes
router.post('/users', async (req, res) => {
  try {
    const user = await userService.createUser(req.body);
    res.status(201).json(user);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

router.get('/users/:id', authenticate, async (req, res) => {
  try {
    const user = await userService.getUser(req.params.id);
    res.json(user);
  } catch (error) {
    res.status(404).json({ error: 'User not found' });
  }
});

router.put('/users/:id', authenticate, async (req, res) => {
  try {
    const user = await userService.updateUser(req.params.id, req.body);
    res.json(user);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

router.delete('/users/:id', authenticate, async (req, res) => {
  try {
    await userService.deleteUser(req.params.id);
    res.status(204).end();
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

Best Practices

Security

Best practices for user security:

  • Hash passwords properly
  • Implement rate limiting
  • Use secure sessions
  • Regular security audits

Data Management

Handle user data responsibly:

  • Data validation
  • Privacy compliance
  • Secure storage
  • Data backups

User Experience

Enhance user management UX:

  • Clear error messages
  • Password recovery
  • Email verification
  • Account settings

Common Issues

Authentication Issues

Common authentication problems:

  • Invalid credentials
  • Session management
  • Token expiration
  • Password reset

Data Management

Data-related challenges:

  • Data validation
  • Profile updates
  • Account deletion
  • Data migration

Next Steps

Now that you understand user management, explore these related topics: