A comprehensive REST API for user management, authentication, and metric tracking with admin dashboard.
- Prerequisites
- Quick Start Guide
- Installation
- Configuration
- Project Structure
- Database
- Running the Server
- API Documentation
- Admin Dashboard
- Authentication System
- API Endpoints
- Error Handling
- Hardware Monitoring
- Security Features
- Email Service
- Development
- Deployment Considerations
- Troubleshooting
- Contributing
- Node.js (v18 or later)
- npm (v8 or later)
- PostgreSQL (v12 or later)
- lm-sensors (for hardware monitoring on Linux)
- Clone the repository:
git clone https://github.com/apptrackit/trackit-backend
cd trackit-backend
- Install dependencies:
npm install
-
Clone and Install:
git clone https://github.com/apptrackit/trackit-backend cd trackit-backend npm install
-
Set up Environment:
touch .env
-
Set up Database:
# Create PostgreSQL database createdb trackitdb # Tables will be auto-created on first run
-
Start the Server:
npm run dev # For development # OR npm start # For production
-
Access Services:
- API Server:
http://localhost:3000
- Admin Dashboard:
http://localhost:3000/
- API Documentation:
http://localhost:3000/api-docs
(dev mode only)
- API Server:
Create a .env
file in the root directory:
# Database Configuration
DATABASE_URL=postgres://username:password@localhost:5432/database_name
# JWT Security
JWT_SECRET=your_secure_jwt_secret_here
# Server Configuration
PORT=3000
HOST=0.0.0.0
# Security Settings
SALT=10 # Number of salt rounds for password hashing
# Admin Account
ADMIN_USERNAME=admin
ADMIN_PASSWORD=admin
# Environment
NODE_ENV=development
# Email Configuration
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=[email protected]
EMAIL_PASS=your_app_password_here
EMAIL_FROM=TrackIt <[email protected]>
EMAIL_TLS_REJECT_UNAUTHORIZED=true
trackit-backend/
│
├── app.js # Main application entry point
├── auth.js # Authentication middleware
├── database.js # Database connection and setup
├── package.json # Project dependencies and scripts
├── package-lock.json # Dependency lock file
├── .env # Environment variables (create from template)
├── .gitignore # Git ignore rules
│
├── controllers/ # Business logic controllers
│ ├── adminController.js # Admin operations
│ ├── authController.js # Authentication logic
│ ├── metricController.js # Metric tracking logic
│ └── userController.js # User management logic
│
├── routes/ # API route definitions
│ ├── admin.js # Admin routes
│ ├── auth.js # Authentication routes
│ ├── metrics.js # Metric tracking routes
│ └── users.js # User management routes
│
├── services/ # Business logic services
│ ├── authService.js # Authentication service
│ ├── emailService.js # Email sending service
│ ├── hardwareService.js # Hardware monitoring service
│ ├── metricService.js # Metric data service
│ ├── sessionService.js # Session management service
│ └── userService.js # User data service
│
├── utils/ # Utility modules
│ ├── logger.js # Winston logging configuration
│ └── swagger.js # Swagger API documentation setup
│
├── public/ # Static files and admin dashboard
│ ├── index.html # Admin login page
│ ├── admin-dashboard.html # Admin dashboard
│ ├── css/
│ │ ├── index.css # Login page styles
│ │ └── admin-dashboard.css # Dashboard styles
│ └── scripts/
│ ├── admin-dashboard.js # Dashboard logic
│ ├── clipboard-helper.js # Clipboard utility functions
│ └── index.js # Login page logic
│
└── logs/ # Application logs (auto-created)
├── combined.log # All log levels
└── error.log # Error logs only
The application uses Winston for comprehensive logging:
- Console Output: Colorized, timestamped logs for development
- File Logging:
logs/error.log
- Error level logs onlylogs/combined.log
- All log levels
- Log Format: Structured JSON with timestamps and service tags
- Log Levels: error, warn, info, debug
Log files are automatically created in the logs/
directory.
The application uses PostgreSQL with the following tables:
id
: Serial primary keyusername
: Unique username (TEXT)email
: User's email (TEXT)password
: Hashed password (TEXT)created_at
: Account creation timestamp (TIMESTAMP)
id
: Serial primary keyuser_id
: Reference to users table (INTEGER)device_id
: Unique device identifier (TEXT)access_token
: JWT access token (TEXT)refresh_token
: Refresh token (TEXT)access_token_expires_at
: Access token expiration (TIMESTAMP)refresh_token_expires_at
: Refresh token expiration (TIMESTAMP)created_at
: Session creation timestamp (TIMESTAMP)last_refresh_at
: Last token refresh timestamp (TIMESTAMP)last_check_at
: Last session check timestamp (TIMESTAMP)refresh_count
: Number of token refreshes (INTEGER)
id
: Serial primary keytoken
: Bearer token for admin authentication (TEXT)username
: Admin username (TEXT)created_at
: Session creation timestamp (TIMESTAMP)expires_at
: Token expiration timestamp (TIMESTAMP)
id
: Serial primary keyname
: Name of the metric type (VARCHAR, UNIQUE)unit
: Unit for this type (VARCHAR)icon_name
: Icon name for this type (VARCHAR)is_default
: Indicates if it's a system-defined default type (BOOLEAN)user_id
: Reference to user who created custom type (INTEGER, nullable)category
: Category of the metric type (VARCHAR)
id
: Serial primary keyuser_id
: Reference to users table (INTEGER)metric_type_id
: Reference to metric_types table (INTEGER)value
: Metric value (BIGINT)date
: Date of the metric entry (DATE)is_apple_health
: Is from Apple Health (BOOLEAN)
Default Metric Types: The system automatically seeds 12 default body measurement metric types (Weight, Height, Body Fat, Waist, Bicep, Chest, Thigh, Shoulder, Glutes, Calf, Neck, Forearm).
- Install PostgreSQL on your system
- Create a database:
CREATE DATABASE trackitdb;
- Create a user (optional):
CREATE USER dev WITH PASSWORD 'dev';
GRANT ALL PRIVILEGES ON DATABASE trackitdb TO dev;
- Update your
.env
file with the correct DATABASE_URL
The database tables and default data are automatically created when the application starts.
Start the server:
npm start
For development with auto-restart:
npm run dev
The server will run on http://localhost:3000
by default.
Interactive API documentation is available via Swagger UI when running in development mode:
- Swagger UI:
http://localhost:3000/api-docs
The Swagger documentation provides:
- Complete API endpoint reference
- Request/response schemas
- Authentication examples
- Interactive testing interface
Note: Swagger UI is only available in development mode for security reasons.
Access the admin dashboard at http://localhost:3000/
with your admin credentials.
Features:
- User management (create, edit, delete users)
- Real-time hardware monitoring (CPU temperature, fan speed, uptime)
- User activity statistics with customizable timeframes
- Active session management
- Search and sort functionality
- Responsive design for mobile and desktop
The system uses multiple authentication mechanisms:
- JWT Tokens: Short-lived access tokens (7 days) for API access
- Refresh Tokens: Long-lived tokens (365 days) for token renewal
- Device-based Sessions: Each device gets a unique session
- Session Limits: Maximum 5 concurrent sessions per user
- Bearer Tokens: Secure admin session tokens (1 hour expiration)
- JWT Authentication: User authentication with access/refresh tokens
- Auto-cleanup: Expired tokens are automatically removed
- Session Validation: Token validation endpoint for dashboard
💡 Tip: For interactive API testing, visit the Swagger UI at
http://localhost:3000/api-docs
when running in development mode.
- POST
/auth/login
- Body:
{ "username": "user", "password": "pass" }
- Returns: Access token, refresh token, user info
- POST
/auth/refresh
- Body:
{ "refreshToken": "token", "deviceId": "id" }
- Returns: New access and refresh tokens
- GET
/auth/check
- Headers:
Authorization: Bearer token
- Returns: Session validity and user info
- POST
/auth/logout
- Headers:
Authorization: Bearer token
- Body:
{ "deviceId": "id" }
- POST
/auth/logout-all
- Headers:
Authorization: Bearer token
- Body:
{}
(empty - user identified from token)
- POST
/auth/sessions
- Headers:
Authorization: Bearer token
- Body:
{}
(empty - user identified from token) - Returns: Array of active sessions with device info
- POST
/user/register
- Body:
{ "username": "user", "email": "email", "password": "pass" }
- Returns: User info and authentication tokens
- POST
/user/change/password
- Headers:
Authorization: Bearer token
- Body:
{ "username": "user", "oldPassword": "old", "newPassword": "new" }
- POST
/user/change/username
- Headers:
Authorization: Bearer token
- Body:
{ "oldUsername": "old", "newUsername": "new", "password": "pass" }
- POST
/user/change/email
- Headers:
Authorization: Bearer token
- Body:
{ "username": "user", "newEmail": "email", "password": "pass" }
- POST
/user/delete
- Headers:
Authorization: Bearer token
- Body:
{ "username": "user", "password": "pass" }
All metric endpoints require: Authorization: Bearer token
header
- POST
/api/metrics
- Body:
{ "metric_type_id": 1, "value": 75, "date": "2024-03-25", "is_apple_health": false }
- Returns: Entry ID and success message
- PUT
/api/metrics/:entryId
- Body:
{ "value": 76, "date": "2024-03-26" }
(partial updates allowed)
- DELETE
/api/metrics/:entryId
- POST
/admin/login
- Body:
{ "username": "admin", "password": "admin" }
- Returns: Bearer token and expiration time
- POST
/admin/validate-token
- Headers:
Authorization: Bearer admin_token
- POST
/admin/logout
- Headers:
Authorization: Bearer admin_token
All other admin endpoints require: Authorization: Bearer admin_token
- GET
/admin/getAllUserData
- Get all users - POST
/admin/user
- Get specific user info - POST
/admin/updateUser
- Update user data - POST
/admin/deleteUser
- Delete user - POST
/admin/createUser
- Create new user - GET
/admin/emails
- Get all user emails
- GET
/admin/registrations?range=24h|week|month|year
- Registration stats - GET
/admin/active-users?range=24h|week|month|year
- Active user stats
- GET
/admin/hardwareinfo
- Get server hardware stats - Returns: CPU temperature, fan speed, uptime with color coding
- POST
/admin/check
- Legacy admin credentials check (use login instead)
The API returns consistent error responses:
{
"success": false,
"error": "Error message description"
}
Common HTTP Status Codes:
200
: Success201
: Created400
: Bad Request (missing/invalid data)401
: Unauthorized (invalid/missing token)403
: Forbidden (insufficient permissions)404
: Not Found409
: Conflict (duplicate data)500
: Internal Server Error
The admin dashboard includes real-time hardware monitoring requiring lm-sensors
:
# Install on Ubuntu/Debian
sudo apt-get install lm-sensors
# Configure sensors
sudo sensors-detect
Monitored Metrics:
- CPU Temperature: Color-coded (Red: >70°C, Green: 40-70°C, Blue: <40°C)
- Fan Speed: Color-coded (Red: >3000 RPM, Green: 1500-3000 RPM, Blue: <1500 RPM)
- System Uptime: Formatted display (days, hours, minutes)
- Password Hashing: bcrypt with configurable salt rounds
- JWT Security: Signed tokens with expiration
- Bearer Token Authentication: Required for protected endpoints
- Session Management: Device-based tracking with limits
- Admin Token Expiration: 1-hour admin sessions with auto-cleanup
- Input Validation: Email format, required fields
- SQL Injection Protection: Parameterized queries
- CORS Protection: Configurable origin restrictions
npm start
- Start production servernpm run dev
- Start development server with nodemon (auto-restart on changes)
Core Dependencies:
express
- Web frameworkpg
- PostgreSQL clientjsonwebtoken
- JWT token handlingbcrypt
- Password hashingwinston
- Logging frameworknodemailer
- Email service
Development Dependencies:
nodemon
- Auto-restart during developmentswagger-jsdoc
- API documentation generationswagger-ui-express
- Interactive API documentation UI
The application requires all environment variables to be set in .env
. Missing variables will prevent startup.
Database schema updates are handled automatically on application startup. New tables and default data are created as needed.
Customize logging in utils/logger.js
:
- Adjust log levels
- Modify output formats
- Change file destinations
- Configure rotation policies
- Environment Variables: Secure storage of secrets in production
- Database: PostgreSQL with proper connection pooling and backup strategy
- Logging: Persistent log storage and rotation (consider ELK stack for production)
- Hardware Monitoring: Ensure lm-sensors is installed and configured on Linux servers
- HTTPS: Use reverse proxy (nginx/Apache) for SSL termination
- Process Management: Use PM2, Docker, or Kubernetes for process management
- API Documentation: Swagger UI is disabled in production for security
- Load Balancing: Consider multiple instances behind a load balancer for high availability
- Store tokens securely (keychain/secure storage)
- Include bearer tokens in authorization headers
- Handle token refresh automatically on 401 errors
- Implement proper logout flow
- Track current device ID
- Implement session list UI
- Allow users to manage active sessions
- Handle session limits gracefully
- Parse error responses consistently
- Show user-friendly error messages
- Handle network connectivity issues
- Implement retry logic for failed requests
The application includes a comprehensive email service for sending HTML emails. The service supports:
- HTML Email Sending: Send rich HTML emails with styling
- Environment Configuration: All email settings configured via environment variables
- Built-in Templates: Welcome emails and password reset emails
- Multiple Recipients: Support for CC, BCC, and multiple recipients
- Attachments: Support for email attachments
- Connection Verification: Test email configuration before sending
Configure the following environment variables in your .env
file:
EMAIL_HOST=smtp.gmail.com # SMTP server host
EMAIL_PORT=587 # SMTP server port
EMAIL_SECURE=false # Use SSL/TLS (true for port 465)
EMAIL_USER=[email protected] # Email account username
EMAIL_PASS=your_app_password # Email account password (use app password for Gmail)
EMAIL_FROM=TrackIt <[email protected]> # Default sender address
EMAIL_TLS_REJECT_UNAUTHORIZED=true # TLS certificate validation
Gmail:
- Host:
smtp.gmail.com
- Port:
587
- Secure:
false
- Note: Use app passwords instead of your regular password
Outlook/Hotmail:
- Host:
smtp-mail.outlook.com
- Port:
587
- Secure:
false
Yahoo:
- Host:
smtp.mail.yahoo.com
- Port:
587
- Secure:
false
const emailService = require('./services/emailService');
// Send simple HTML email
await emailService.sendSimpleHtmlEmail(
'[email protected]',
'Subject',
'<h1>Hello!</h1><p>HTML content here</p>'
);
// Send detailed email with all options
await emailService.sendHtmlEmail({
to: '[email protected]',
subject: 'Subject',
html: '<h1>HTML content</h1>',
cc: ['[email protected]'],
bcc: ['[email protected]'],
attachments: [/* attachment objects */]
});
// Send welcome email (built-in template)
await emailService.sendWelcomeEmail('[email protected]', 'Username');
// Send password reset email (built-in template)
await emailService.sendPasswordResetEmail('[email protected]', 'Username', 'reset-link');
// Verify email configuration
const isValid = await emailService.verifyConnection();
See examples/emailExamples.js
for complete usage examples.
Database Connection Issues:
# Check PostgreSQL is running
sudo systemctl status postgresql
# Test connection
psql -h localhost -U username -d database_name
Environment Variables:
- Ensure all required variables are set in
.env
- Check for typos in variable names
- Verify database URL format:
postgres://username:password@host:port/database
Hardware Monitoring:
# Install and configure sensors
sudo apt-get install lm-sensors
sudo sensors-detect
# Test sensors
sensors
Email Service:
- Use app-specific passwords for Gmail
- Check firewall settings for SMTP ports
- Verify email credentials and server settings
Port Already in Use:
# Find process using port 3000
lsof -i :3000
# Kill process if needed
kill -9 <PID>
- Follow existing code style and structure
- Add logging for new features using the Winston logger
- Update API documentation for new endpoints (add Swagger annotations)
- Test database operations thoroughly
- Ensure proper error handling and validation
- Update this README for any new features or configuration changes
ISC License - see package.json for details.
- GitHub Repository: https://github.com/apptrackit/trackit-backend
- API Documentation: Available at
/api-docs
when running in development mode - Issue Tracking: Use GitHub Issues for bug reports and feature requests
For questions or support, please refer to the project's GitHub repository.