User Management

How to Become an Admin

This guide explains the different ways to promote a user to admin role in the Earthquake Catalogue Platform.

Overview

The system has 4 user roles: - Guest - Limited access to public catalogues - Viewer - Read-only access with export capabilities (default for new users) - Editor - Create, edit, delete catalogues, import/merge data - Admin - Full system access including user management

        flowchart TD
    Start([User Needs Admin Access]) --> Method{Method?}

    Method -- "Script (Rec)" --> Script["Run: npx tsx scripts/promote-to-admin.ts"]
    Method -- "Database" --> DB["Update 'role' to 'admin' in MongoDB"]
    Method -- "GUI" --> GUI["Existing Admin uses User Management UI"]

    Script --> Logout[Log Out & Log Back In]
    DB --> Logout
    GUI --> Logout

    Logout --> Verify[Verify 'User Management'<br/>menu appears]
    Verify --> End([Done])
    

New users are created as Viewers by default. To access admin features, you need to be promoted to admin.

Method 2: Using MongoDB Shell

If you prefer to use MongoDB directly:

Step 1: Connect to MongoDB

mongosh "mongodb+srv://<atlas-username>:<atlas-password>@<atlas-cluster-host>/<database-name>"

Or if using local MongoDB: .. code-block:: bash

mongosh earthquake_catalogue

Step 2: Update the User Role

db.users.updateOne(
  { email: "your@email.com" },
  { $set: { role: "admin", updated_at: new Date().toISOString() } }
)

Example: .. code-block:: javascript

db.users.updateOne(

{ email: “test@example.com” }, { $set: { role: “admin”, updated_at: new Date().toISOString() } }

)

Step 3: Verify the Change

db.users.findOne({ email: "test@example.com" }, { name: 1, email: 1, role: 1 })

Expected output: .. code-block:: javascript

{

_id: ObjectId(”…”), name: ‘Test User’, email: ‘test@example.com’, role: ‘admin’

}

Step 4: Log Out and Log Back In

Same as Method 1, Step 3.

Method 3: Using MongoDB Compass (GUI)

If you prefer a graphical interface:

Step 1: Connect to MongoDB

  1. Open MongoDB Compass

  2. Connect using your connection string: ` mongodb+srv://<atlas-username>:<atlas-password>@<atlas-cluster-host>/<database-name> `

Step 2: Navigate to Users Collection

  1. Select the earthquake_catalogue database, or the value of MONGODB_DATABASE if you changed it

  2. Click on the users collection

Step 3: Find and Edit Your User

  1. Find your user by email (use the filter: { email: "your@email.com" })

  2. Click the “Edit” button (pencil icon)

  3. Change the role field from "viewer" to "admin"

  4. Update the updated_at field to the current date/time

  5. Click “Update”

Step 4: Log Out and Log Back In

Same as Method 1, Step 3.

Method 4: Admin User Management (Once You Have an Admin)

Once you have at least one admin user, admins can promote other users through the web interface:

Step 1: Log in as Admin

Log in with an admin account.

Step 2: Go to User Management

  1. Click your avatar in the top right

  2. Click “User Management”

  3. Or navigate directly to /admin/users

Step 3: Promote a User

  1. Find the user you want to promote

  2. Click the “Edit” or role dropdown button

  3. Change their role to “Admin”

  4. Save the changes

The user will need to log out and log back in for the changes to take effect.

Verifying Admin Access

After promoting to admin and logging back in, you should see:

In the User Menu (Top Right Avatar)

  • Your role should show as “admin”

  • You should see a “User Management” menu item with a shield icon

Admin Features You Can Access

  • User Management (/admin/users) - View, edit, and manage all users

  • Change User Roles - Promote/demote users

  • Activate/Deactivate Users - Enable or disable user accounts

  • Delete Users - Remove users from the system

Admin Permissions

As an admin, you have all permissions: - ✅ View all catalogues - ✅ Create, edit, delete catalogues - ✅ Import and merge data - ✅ Export catalogues - ✅ Manage users - ✅ Access system settings

Troubleshooting

“User not found” Error

If the script says user not found, list all users: .. code-block:: bash

mongosh earthquake_catalogue –eval “db.users.find({}, {email:1, name:1, role:1}).pretty()”

Make sure you’re using the exact email address from the database.

Changes Not Taking Effect

You MUST log out and log back in for role changes to take effect. The role is stored in the JWT session token, which is only updated on login.

Steps: 1. Click avatar → Sign Out 2. Go to /login 3. Enter your credentials 4. Log in 5. Check avatar menu for “User Management”

Can’t Connect to MongoDB

Make sure your .env file has the correct MongoDB connection string: .. code-block:: bash

MONGODB_URI=mongodb+srv://<atlas-username>:<atlas-password>@<atlas-cluster-host>/<database-name> MONGODB_DATABASE=<database-name>

Script Errors

If the promotion script fails, try using MongoDB shell directly (Method 2).

Quick Reference

Promote User to Admin (Quick Command)

# Using the script
npx tsx scripts/promote-to-admin.ts your@email.com

# Using MongoDB shell
mongosh earthquake_catalogue --eval 'db.users.updateOne({email:"your@email.com"},{$set:{role:"admin",updated_at:new Date().toISOString()}})'

List All Users

mongosh earthquake_catalogue --eval "db.users.find({}, {email:1, name:1, role:1}).pretty()"

Check Your Current Role

mongosh earthquake_catalogue --eval 'db.users.findOne({email:"your@email.com"}, {name:1, email:1, role:1})'

Security Notes

  • Protect admin accounts - Admin users have full system access

  • Use strong passwords - Especially for admin accounts

  • Limit admin users - Only promote trusted users to admin

  • Audit admin actions - Monitor what admins do in the system

  • First admin must be bootstrapped intentionally - Use CREATE_ADMIN_USER=true with a strong temporary password, or promote an existing user with the script or MongoDB shell

Next Steps

After becoming an admin:

  1. Test User Management - Go to /admin/users and explore the interface

  2. Create More Users - Register additional test accounts

  3. Test Role Changes - Practice promoting/demoting users

  4. Explore Admin Features - Check out all the admin-only functionality

  5. Set Up Production - Change default passwords and secure your admin accounts

For more information, see: - docs/source/appendix/authentication.rst - Complete authentication documentation - docs/source/appendix/getting_started_auth.rst - Authentication quick start guide

Change Password Feature

This guide explains how users can change their password in the Earthquake Catalogue Platform.

Overview

All authenticated users can change their own password at any time. This is a security best practice to: - Keep accounts secure - Update passwords periodically - Change passwords if they’ve been compromised - Set a new password after initial registration

How to Change Your Password

Method 2: From Your Profile Page

  1. Go to your Profile page (/profile)

  2. Click the “Change Password” button at the bottom

  3. You’ll be redirected to the change password page

Method 3: Direct URL

Navigate directly to: ``/change-password``

Change Password Form

The change password page requires three fields:

1. Current Password

  • Your existing password

  • Required to verify your identity

  • Must match your current password exactly

2. New Password

  • Your new password

  • Must be at least 8 characters long

  • Should be different from your current password

  • Use a strong password with a mix of: - Uppercase and lowercase letters - Numbers - Special characters

3. Confirm New Password

  • Re-enter your new password

  • Must match the “New Password” field exactly

  • Helps prevent typos

Password Requirements

Minimum length: 8 characters ✅ Must be different from current password ✅ Must match confirmation field

Recommended: - Use a mix of uppercase and lowercase letters - Include numbers - Include special characters (!@#$%^&*) - Avoid common words or patterns - Don’t reuse passwords from other sites

Step-by-Step Instructions

Step 1: Access the Change Password Page

Choose one of the methods above to navigate to /change-password.

Step 2: Enter Your Current Password

  1. In the “Current Password” field, enter your existing password

  2. Click the eye icon to show/hide the password if needed

Step 3: Enter Your New Password

  1. In the “New Password” field, enter your new password

  2. Make sure it’s at least 8 characters long

  3. Use a strong, unique password

Step 4: Confirm Your New Password

  1. In the “Confirm New Password” field, re-enter your new password

  2. Make sure it matches exactly

Step 5: Submit the Form

  1. Click the “Change Password” button

  2. Wait for the confirmation message

Step 6: Success!

  • You’ll see a success message: “Password changed successfully!”

  • You’ll be automatically redirected to your profile page

  • Your new password is now active

  • You can use it immediately for future logins

Common Errors and Solutions

“Current password is incorrect”

Problem: The current password you entered doesn’t match your actual password.

Solution: - Double-check your current password - Make sure Caps Lock is off - Try clicking the eye icon to see what you’re typing - If you’ve forgotten your password, you’ll need to contact an admin

“New password must be at least 8 characters long”

Problem: Your new password is too short.

Solution: - Make your password at least 8 characters - Consider using a longer password for better security

“New passwords do not match”

Problem: The “New Password” and “Confirm New Password” fields don’t match.

Solution: - Re-enter both fields carefully - Use the eye icon to verify what you’re typing - Copy-paste is not recommended for passwords

“New password must be different from current password”

Problem: You’re trying to change to the same password you already have.

Solution: - Choose a different password - This is a security measure to ensure you’re actually updating your password

Security Best Practices

When to Change Your Password

Regularly - Every 3-6 months ✅ After a security incident - If you suspect your account was compromised ✅ After using a public computer - If you logged in on a shared device ✅ If you shared it - If you accidentally shared your password ✅ After initial registration - Change from any temporary password

Creating Strong Passwords

Good Examples: - MyC@t$Name2024! - Tr0pic@lSt0rm#99 - B1ueM00n&Stars!

Bad Examples: - password (too common) - 12345678 (too simple) - qwerty (keyboard pattern) - short admin-themed passwords (predictable)

Tips: - Use a password manager to generate and store strong passwords - Don’t reuse passwords across different sites - Don’t share your password with anyone - Don’t write it down in plain text

For Administrators

Resetting User Passwords

Admins cannot see user passwords (they’re hashed), but they can help users who forgot their password:

Option 1: Manual Database Update

# Generate a new password hash
npx tsx -e "import bcrypt from 'bcryptjs'; bcrypt.hash('newpassword123', 10).then(console.log)"

# Update in MongoDB
mongosh earthquake_catalogue --eval 'db.users.updateOne({email:"user@email.com"},{$set:{password_hash:"<hash>"}})'

Option 2: Create a Password Reset Script

Consider creating a password reset script for easier admin password resets.

API Endpoint

The password change functionality uses the following API endpoint:

Endpoint: POST /api/auth/change-password

Request Body: .. code-block:: json

{

“currentPassword”: “oldpassword123”, “newPassword”: “newpassword456”

}

Success Response (200): .. code-block:: json

{

“message”: “Password changed successfully”

}

Error Responses:

  • 401 Unauthorized - Not logged in

  • 401 Unauthorized - Current password is incorrect

  • 400 Bad Request - Missing required fields

  • 400 Bad Request - New password too short

  • 404 Not Found - User not found

  • 500 Internal Server Error - Server error

Troubleshooting

Can’t Access the Change Password Page

Problem: Getting redirected to login page.

Solution: - You must be logged in to change your password - Log in first, then try again

Form Not Submitting

Problem: Nothing happens when you click “Change Password”.

Solution: - Check for error messages on the page - Make sure all fields are filled in - Check that passwords meet requirements - Check browser console for errors (F12)

Password Changed But Can’t Login

Problem: Changed password successfully but can’t log in with new password.

Solution: - Make sure you’re using the NEW password, not the old one - Check for typos - Make sure Caps Lock is off - Clear browser cache and try again - If still having issues, contact an admin

Quick Reference

Access Change Password Page

Method 1: Avatar Menu → "Change Password"
Method 2: Profile Page → "Change Password" button
Method 3: Direct URL → /change-password

Password Requirements

✅ Minimum 8 characters
✅ Different from current password
✅ Must match confirmation

Common Commands

# Check user's current info (doesn't show password)
npx tsx scripts/check-user-role.ts user@email.com

# Generate password hash (for admin password resets)
npx tsx -e "import bcrypt from 'bcryptjs'; bcrypt.hash('newpassword', 10).then(console.log)"

✅ Password Change Feature - Implementation Complete!

Overview

I’ve successfully implemented a comprehensive password change feature for the Earthquake Catalogue Platform. Users can now securely change their passwords through the web interface.

🎯 What Was Implemented

        sequenceDiagram
    actor User
    participant UI as Frontend Page
    participant API as /api/auth/change-password
    participant Auth as Auth Handler
    participant DB as Database

    User->>UI: Enter Current & New Password
    UI->>UI: Validate Length & Match
    UI->>API: POST {current, new}

    API->>Auth: Verify Session
    Auth-->>API: Session Valid

    API->>DB: Fetch User Hash
    DB-->>API: User Record

    API->>API: bcrypt.compare(current, hash)
    alt Invalid Password
        API-->>UI: 401 Unauthorized
        UI-->>User: Error: "Current password incorrect"
    else Valid Password
        API->>API: bcrypt.hash(new, 10)
        API->>DB: Update Password Hash
        DB-->>API: Success
        API-->>UI: 200 OK
        UI-->>User: Success & Redirect to Profile
    end
    

1. Change Password Page (/change-password)

  • Clean, user-friendly interface

  • Three password fields: - Current Password (with show/hide toggle) - New Password (with show/hide toggle) - Confirm New Password (with show/hide toggle)

  • Real-time validation

  • Success and error messages

  • Auto-redirect to profile after success

2. API Endpoint (/api/auth/change-password)

  • Secure password verification

  • Password hashing with bcryptjs

  • Proper error handling

  • Session-based authentication

  • Validates password strength (min 8 characters)

3. User Interface Integration

  • User Menu - “Change Password” option with key icon 🔑

  • Profile Page - “Change Password” button

  • Mobile Support - Works on all screen sizes

📁 Files Created

  1. ``app/api/auth/change-password/route.ts`` - API endpoint for password changes - Verifies current password - Hashes and updates new password

  2. ``app/(auth)/change-password/page.tsx`` - Password change form page - Client-side validation - Show/hide password toggles - Success/error handling

  3. ``docs/source/appendix/change_password.rst`` - Complete user documentation - Step-by-step instructions - Troubleshooting guide - Security best practices

  4. ``PASSWORD_CHANGE_FEATURE.md`` (this file) - Implementation summary

📝 Files Modified

  1. ``components/layout/Header.tsx`` - Added “Change Password” menu item to user dropdown - Added Key icon import - Works on both desktop and mobile

  2. ``app/(auth)/profile/page.tsx`` - Added “Change Password” button - Positioned next to “Sign Out” button

🚀 How to Use

For Users

Option 1: From User Menu 1. Click your avatar (top right) 2. Click “Change Password” 3. Fill in the form 4. Submit

Option 2: From Profile 1. Go to /profile 2. Click “Change Password” button 3. Fill in the form 4. Submit

Option 3: Direct URL - Navigate to /change-password

Password Requirements

Minimum 8 charactersMust be different from current passwordMust match confirmation field

🔐 Security Features

  1. Current Password Verification - Must provide current password to change - Prevents unauthorized password changes

  2. Password Hashing - Uses bcryptjs with 10 salt rounds - Passwords never stored in plain text

  3. Session-Based Authentication - Must be logged in to change password - Uses NextAuth session verification

  4. Password Strength Validation - Minimum 8 characters enforced - Client and server-side validation

  5. Password Visibility Toggles - Eye icons to show/hide passwords - Helps prevent typos

🎨 User Experience

Visual Features

  • Clean, modern interface

  • Card-based layout

  • Responsive design (mobile-friendly)

  • Clear labels and placeholders

  • Success/error alerts

  • Loading states during submission

Validation

  • Real-time error messages

  • Clear validation rules

  • Helpful error descriptions

  • Prevents common mistakes

🧪 Testing the Feature

Test Steps

  1. Log in to your account - Email: test@example.com - Password: password123

  2. Access Change Password - Click avatar → “Change Password” - OR go to /change-password

  3. Fill in the form: - Current Password: password123 - New Password: newpassword123 - Confirm New Password: newpassword123

  4. Submit - Should see success message - Auto-redirect to profile

  5. Test new password - Sign out - Log in with new password: newpassword123 - Should work!

Test Cases

Valid password change - Should succeed ✅ Wrong current password - Should show error ✅ Passwords don’t match - Should show error ✅ Password too short - Should show error ✅ Same as current password - Should show error ✅ Not logged in - Should redirect to login

📊 API Details

Endpoint

POST /api/auth/change-password

Request

{
  "currentPassword": "oldpassword123",
  "newPassword": "newpassword456"
}

Success Response (200)

{
  "message": "Password changed successfully"
}

Error Responses

Status

Error

Reason

401

Unauthorized

Not logged in

401

Current password is incorrect

Wrong current password

400

Current password and new password are required

Missing fields

400

New password must be at least 8 characters long

Password too short

404

User not found

User doesn’t exist

500

Failed to update password

Server error

🎯 Next Steps

For You (User)

  1. Test the feature - Try changing your password - Verify it works

  2. Update your password - Change from the default password123 - Use a strong, unique password

  3. Explore the interface - Check the user menu - Visit the profile page - Try on mobile

For Future Enhancements (Optional)

  1. Password Reset via Email - For users who forgot their password - Requires email service integration

  2. Password Strength Meter - Visual indicator of password strength - Real-time feedback

  3. Password History - Prevent reusing recent passwords - Store hashed password history

  4. Two-Factor Authentication (2FA) - Additional security layer - SMS or authenticator app

  5. Password Expiry - Force password changes after X days - Configurable policy

📚 Documentation

Complete documentation available at: - ``docs/source/appendix/change_password.rst`` - User guide with step-by-step instructions - ``docs/source/appendix/authentication.rst`` - Complete authentication documentation - ``docs/source/appendix/how_to_become_admin.rst`` - Admin promotion guide

✅ Summary

Feature Status:COMPLETE AND READY TO USE

What You Can Do Now: - ✅ Change your password through the web interface - ✅ Access from user menu or profile page - ✅ Secure password verification and hashing - ✅ Clear error messages and validation - ✅ Mobile-friendly interface

Files Created: 3 new files Files Modified: 2 existing files API Endpoints: 1 new endpoint Pages: 1 new page

The password change feature is fully functional and integrated into your authentication system! 🎉