Skip to content

pgdn-oss/pgdn-api-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

DePIN Scanner API - User Registration Guide

πŸ” Secure User Registration System

This guide explains how to register users in the DePIN Scanner API with comprehensive security features.

πŸ“‹ Prerequisites

  1. Database Setup: Run the SQL commands to create necessary tables
  2. Environment Configuration: Set up environment variables
  3. API Running: Ensure the FastAPI application is running

πŸš€ Quick Setup

1. Database Setup

# Connect to your PostgreSQL database
psql -U your_username -d depin

# Run the setup SQL
\i setup_tables.sql

2. Environment Configuration

# Copy and configure environment variables
cp .env.example .env

# Edit .env with your actual values
nano .env

3. Start the Application

# Install dependencies
pip install -r requirements.txt

# Run the application
uvicorn main:app --reload --host 0.0.0.0 --port 8000

πŸ“ Registration Endpoint

Endpoint Details

  • URL: POST /api/v1/register
  • Rate Limit: 5 requests per hour per IP
  • Security: Password breach checking, input validation, rate limiting

Request Format

{
  "email": "[email protected]",
  "username": "johndoe",
  "password": "MySecureP@ssw0rd123!",
  "confirm_password": "MySecureP@ssw0rd123!",
  "first_name": "John",
  "last_name": "Doe",
  "organization_name": "My Organization"
}

Password Requirements

Your password MUST meet all of the following criteria:

  • βœ… Minimum 12 characters (maximum 128)
  • βœ… At least 1 uppercase letter (A-Z)
  • βœ… At least 1 lowercase letter (a-z)
  • βœ… At least 1 digit (0-9)
  • βœ… At least 1 special character (!@#$%^&*()_+-=[]{}|;:,.<>?)
  • ❌ No common patterns (password, 123456, qwerty, admin, letmein)
  • ❌ Not found in data breaches (checked against HaveIBeenPwned)

Username Requirements

  • βœ… 3-50 characters
  • βœ… Letters, numbers, hyphens, underscores only
  • βœ… Must be unique
  • βœ… Automatically converted to lowercase

πŸ“± Registration Examples

Using cURL

curl -X POST "http://localhost:8000/api/v1/register" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "username": "johndoe",
    "password": "MySecureP@ssw0rd123!",
    "confirm_password": "MySecureP@ssw0rd123!",
    "first_name": "John",
    "last_name": "Doe",
    "organization_name": "Acme Corporation"
  }'

Using Python requests

import requests

url = "http://localhost:8000/api/v1/register"
data = {
    "email": "[email protected]",
    "username": "johndoe",
    "password": "MySecureP@ssw0rd123!",
    "confirm_password": "MySecureP@ssw0rd123!",
    "first_name": "John",
    "last_name": "Doe",
    "organization_name": "Acme Corporation"
}

response = requests.post(url, json=data)
print(response.json())

Using JavaScript/Fetch

const registerUser = async () => {
  const response = await fetch('http://localhost:8000/api/v1/register', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: '[email protected]',
      username: 'johndoe',
      password: 'MySecureP@ssw0rd123!',
      confirm_password: 'MySecureP@ssw0rd123!',
      first_name: 'John',
      last_name: 'Doe',
      organization_name: 'Acme Corporation'
    })
  });
  
  const result = await response.json();
  console.log(result);
};

βœ… Successful Response

{
  "id": 1,
  "uuid": "123e4567-e89b-12d3-a456-426614174000",
  "email": "[email protected]",
  "username": "johndoe",
  "first_name": "John",
  "last_name": "Doe",
  "is_active": true,
  "email_verified": false,
  "created_at": "2025-06-24T10:30:00Z",
  "message": "User account created successfully. Please verify your email address to complete registration."
}

❌ Error Responses

Password Too Weak

{
  "detail": {
    "message": "Password does not meet security requirements",
    "issues": [
      "Password must be at least 12 characters long",
      "Password must contain at least one special character"
    ]
  }
}

Password Compromised

{
  "detail": {
    "message": "Password has been found in data breaches",
    "recommendation": "Please choose a different password that has not been compromised"
  }
}

Email Already Exists

{
  "detail": "Email address is already registered"
}

Username Taken

{
  "detail": "Username is already taken"
}

Rate Limit Exceeded

{
  "detail": "Rate limit exceeded. Please try again later.",
  "error_code": "RATE_LIMIT_EXCEEDED"
}

πŸ”’ Security Features

1. Password Security

  • βœ… BCrypt hashing with 14 rounds
  • βœ… Password breach checking via HaveIBeenPwned API
  • βœ… Complex password requirements
  • βœ… No password storage in plain text

2. Rate Limiting

  • βœ… 5 registration attempts per hour per IP
  • βœ… 10 login attempts per 15 minutes per IP
  • βœ… Automatic IP-based throttling

3. Input Validation

  • βœ… Email format validation
  • βœ… Username sanitization
  • βœ… SQL injection prevention
  • βœ… XSS protection

4. Account Security

  • βœ… Account lockout after failed attempts
  • βœ… Email verification required
  • βœ… Audit logging for all actions
  • βœ… Automatic organization creation

🏒 Organization Management

When a user registers with an organization_name:

  1. New Organization Created with the user as admin
  2. Default Roles Assigned (admin, user, viewer)
  3. User Added to organization with admin role
  4. Organization UUID generated for API access

πŸ”‘ After Registration

1. Login to Get Tokens

curl -X POST "http://localhost:8000/api/v1/login" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=johndoe&password=MySecureP@ssw0rd123!"

2. Access Protected Endpoints

curl -X GET "http://localhost:8000/api/v1/me" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

3. Start Scanning

curl -X POST "http://localhost:8000/api/v1/organizations/YOUR_ORG_UUID/scan" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"target": "example.com", "protocol_filter": "sui"}'

πŸ› οΈ Troubleshooting

Common Issues

  1. "Database connection failed"

    • Check DATABASE_URL in .env
    • Ensure PostgreSQL is running
    • Verify database credentials
  2. "Password does not meet requirements"

    • Review password criteria above
    • Use a password manager to generate secure passwords
  3. "Rate limit exceeded"

    • Wait before retrying
    • Check if multiple attempts from same IP
  4. "Email already registered"

    • User already exists
    • Use login endpoint instead
    • Try password reset if needed

Security Monitoring

Check the audit logs for security events:

-- View recent registration attempts
SELECT * FROM login_attempts 
WHERE attempted_at > NOW() - INTERVAL '24 hours'
ORDER BY attempted_at DESC;

-- View audit events
SELECT * FROM audit_logs 
WHERE action = 'user_registration'
ORDER BY created_at DESC
LIMIT 10;

πŸ“š Next Steps

  1. Implement Email Verification (optional)
  2. Set up Password Reset (optional)
  3. Configure HTTPS for production
  4. Set up Monitoring for security events
  5. Backup Database regularly

🚨 Production Considerations

Essential Security Checklist

  • Change all default passwords
  • Use strong JWT secrets (32+ characters)
  • Enable HTTPS only
  • Configure proper CORS origins
  • Set up database backups
  • Monitor rate limits and failed attempts
  • Implement proper logging
  • Regular security updates

Environment Variables for Production

# Generate secure secrets
SECRET_KEY=$(openssl rand -base64 32)
DATABASE_PASSWORD=$(openssl rand -base64 24)
REDIS_PASSWORD=$(openssl rand -base64 24)

# Update .env
echo "SECRET_KEY=$SECRET_KEY" >> .env
echo "ENVIRONMENT=production" >> .env
echo "DEBUG=False" >> .env

πŸ” Security is paramount! Always use HTTPS in production and keep your dependencies updated.

About

No description, website, or topics provided.

Resources

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

Packages

 
 
 

Contributors