Initial commit: InInventer - Inventory Management System with RBAC
This commit is contained in:
commit
3cc8ef6b68
21
.env.example
Normal file
21
.env.example
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
# MongoDB Configuration
|
||||||
|
MONGO_URI=mongodb://mongodb:27017/ininventer
|
||||||
|
MONGO_INITDB_ROOT_USERNAME=your_mongo_username
|
||||||
|
MONGO_INITDB_ROOT_PASSWORD=your_mongo_password
|
||||||
|
MONGO_INITDB_DATABASE=ininventer
|
||||||
|
|
||||||
|
# JWT Configuration
|
||||||
|
JWT_SECRET=your_jwt_secret_key_here_make_it_long_and_random
|
||||||
|
JWT_EXPIRATION=24h
|
||||||
|
|
||||||
|
# Node Environment
|
||||||
|
NODE_ENV=development
|
||||||
|
PORT=5000
|
||||||
|
|
||||||
|
# Superadmin Credentials (change these!)
|
||||||
|
SUPERADMIN_EMAIL=admin@example.com
|
||||||
|
SUPERADMIN_PASSWORD=changeme123
|
||||||
|
|
||||||
|
# Domain Configuration (for production)
|
||||||
|
DOMAIN_NAME=your-domain.com
|
||||||
|
EMAIL_FOR_SSL=admin@your-domain.com
|
102
.gitignore
vendored
Normal file
102
.gitignore
vendored
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
# Dependencies
|
||||||
|
node_modules/
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
|
||||||
|
# Environment files
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.development
|
||||||
|
.env.test
|
||||||
|
.env.production
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
|
||||||
|
# Production files
|
||||||
|
docker-compose.production.yml
|
||||||
|
nginx/production.conf
|
||||||
|
nginx/initial.conf
|
||||||
|
|
||||||
|
# Build directories
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# Docker volumes
|
||||||
|
mongodb_data/
|
||||||
|
certbot/
|
||||||
|
|
||||||
|
# IDE files
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# Deployment files
|
||||||
|
ininventer-deploy.tar.gz
|
||||||
|
*.tar.gz
|
||||||
|
*.zip
|
||||||
|
|
||||||
|
# Backup files
|
||||||
|
backup/
|
||||||
|
backups/
|
||||||
|
*.backup
|
||||||
|
*.bak
|
||||||
|
|
||||||
|
# SSL certificates
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
*.crt
|
||||||
|
*.csr
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
# OS files
|
||||||
|
.DS_Store
|
||||||
|
.DS_Store?
|
||||||
|
._*
|
||||||
|
.Spotlight-V100
|
||||||
|
.Trashes
|
||||||
|
ehthumbs.db
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Test coverage
|
||||||
|
coverage/
|
||||||
|
.nyc_output/
|
||||||
|
|
||||||
|
# Temporary files
|
||||||
|
tmp/
|
||||||
|
temp/
|
||||||
|
.tmp/
|
||||||
|
|
||||||
|
# Python (if any scripts)
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
*.so
|
||||||
|
.Python
|
||||||
|
env/
|
||||||
|
venv/
|
||||||
|
|
||||||
|
# Secrets
|
||||||
|
secrets/
|
||||||
|
private/
|
||||||
|
*.secret
|
||||||
|
|
||||||
|
# Database dumps
|
||||||
|
*.sql
|
||||||
|
*.dump
|
||||||
|
*.mongodb
|
||||||
|
|
||||||
|
# Generated documentation
|
||||||
|
docs/_build/
|
||||||
|
docs/.doctrees/
|
185
DEPLOYMENT.md
Normal file
185
DEPLOYMENT.md
Normal file
@ -0,0 +1,185 @@
|
|||||||
|
# InInventer Deployment Guide
|
||||||
|
|
||||||
|
This guide will walk you through deploying InInventer to a Debian 12 server on Linode.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- A Linode server running Debian 12
|
||||||
|
- A domain name pointing to your server's IP address
|
||||||
|
- Root access to the server
|
||||||
|
- Basic knowledge of Linux command line
|
||||||
|
|
||||||
|
## Step 1: Prepare Your Local Environment
|
||||||
|
|
||||||
|
1. Make scripts executable:
|
||||||
|
```bash
|
||||||
|
chmod +x deploy.sh start-production.sh backup.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Create a deployment package:
|
||||||
|
```bash
|
||||||
|
tar -czf ininventer-deploy.tar.gz \
|
||||||
|
--exclude='node_modules' \
|
||||||
|
--exclude='.git' \
|
||||||
|
--exclude='*.log' \
|
||||||
|
--exclude='.env' \
|
||||||
|
backend/ frontend/ nginx/ \
|
||||||
|
docker-compose.yml deploy.sh \
|
||||||
|
start-production.sh backup.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
## Step 2: Upload Files to Server
|
||||||
|
|
||||||
|
1. Copy the deployment package to your server:
|
||||||
|
```bash
|
||||||
|
scp ininventer-deploy.tar.gz root@172.104.242.160:/tmp/
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Copy the deployment script:
|
||||||
|
```bash
|
||||||
|
scp deploy.sh root@172.104.242.160:/tmp/
|
||||||
|
```
|
||||||
|
|
||||||
|
## Step 3: Connect to Server and Deploy
|
||||||
|
|
||||||
|
1. SSH into your server:
|
||||||
|
```bash
|
||||||
|
ssh root@172.104.242.160
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Run the deployment script:
|
||||||
|
```bash
|
||||||
|
cd /tmp
|
||||||
|
chmod +x deploy.sh
|
||||||
|
./deploy.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
3. When prompted, enter:
|
||||||
|
- Your domain name (e.g., inventory.yourdomain.com)
|
||||||
|
- Email address for SSL certificates
|
||||||
|
|
||||||
|
## Step 4: Extract Application Files
|
||||||
|
|
||||||
|
After the deployment script completes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /opt/ininventer
|
||||||
|
tar -xzf /tmp/ininventer-deploy.tar.gz
|
||||||
|
chmod +x start-production.sh backup.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
## Step 5: Start the Application
|
||||||
|
|
||||||
|
Run the production start script:
|
||||||
|
```bash
|
||||||
|
./start-production.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
This script will:
|
||||||
|
- Obtain SSL certificates from Let's Encrypt
|
||||||
|
- Start all Docker containers
|
||||||
|
- Configure automatic SSL renewal
|
||||||
|
- Set up systemd service for auto-start
|
||||||
|
|
||||||
|
## Step 6: Verify Deployment
|
||||||
|
|
||||||
|
1. Check if all containers are running:
|
||||||
|
```bash
|
||||||
|
docker-compose -f docker-compose.production.yml ps
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Check logs:
|
||||||
|
```bash
|
||||||
|
docker-compose -f docker-compose.production.yml logs -f
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Visit your domain in a web browser:
|
||||||
|
- https://your-domain.com
|
||||||
|
|
||||||
|
## Step 7: First Login
|
||||||
|
|
||||||
|
Default credentials:
|
||||||
|
- Email: `admin@ininventer.com`
|
||||||
|
- Password: `admin123`
|
||||||
|
|
||||||
|
**IMPORTANT: Change the default password immediately after first login!**
|
||||||
|
|
||||||
|
## Maintenance
|
||||||
|
|
||||||
|
### View Logs
|
||||||
|
```bash
|
||||||
|
cd /opt/ininventer
|
||||||
|
docker-compose -f docker-compose.production.yml logs -f [service_name]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Restart Services
|
||||||
|
```bash
|
||||||
|
systemctl restart ininventer
|
||||||
|
```
|
||||||
|
|
||||||
|
### Manual Backup
|
||||||
|
```bash
|
||||||
|
cd /opt/ininventer
|
||||||
|
./backup.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
### Update Application
|
||||||
|
```bash
|
||||||
|
cd /opt/ininventer
|
||||||
|
docker-compose -f docker-compose.production.yml down
|
||||||
|
# Upload new files
|
||||||
|
docker-compose -f docker-compose.production.yml build
|
||||||
|
docker-compose -f docker-compose.production.yml up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
## Security Recommendations
|
||||||
|
|
||||||
|
1. **Change Default Passwords**
|
||||||
|
- Change the superadmin password immediately
|
||||||
|
- Update MongoDB passwords in production
|
||||||
|
|
||||||
|
2. **Firewall Configuration**
|
||||||
|
- Only ports 22, 80, and 443 should be open
|
||||||
|
- Consider changing SSH port
|
||||||
|
|
||||||
|
3. **Regular Backups**
|
||||||
|
- Set up automated backups using cron:
|
||||||
|
```bash
|
||||||
|
crontab -e
|
||||||
|
# Add: 0 2 * * * /opt/ininventer/backup.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Monitor Resources**
|
||||||
|
- Check disk space regularly
|
||||||
|
- Monitor CPU and memory usage
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### SSL Certificate Issues
|
||||||
|
```bash
|
||||||
|
# Renew certificates manually
|
||||||
|
docker-compose -f docker-compose.production.yml run --rm certbot renew
|
||||||
|
```
|
||||||
|
|
||||||
|
### Container Won't Start
|
||||||
|
```bash
|
||||||
|
# Check logs
|
||||||
|
docker-compose -f docker-compose.production.yml logs [service_name]
|
||||||
|
|
||||||
|
# Rebuild containers
|
||||||
|
docker-compose -f docker-compose.production.yml build --no-cache
|
||||||
|
```
|
||||||
|
|
||||||
|
### Database Connection Issues
|
||||||
|
```bash
|
||||||
|
# Check MongoDB is running
|
||||||
|
docker exec -it ininventer-mongodb-prod mongo --eval "db.adminCommand('ping')"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
For issues or questions:
|
||||||
|
1. Check container logs
|
||||||
|
2. Verify domain DNS settings
|
||||||
|
3. Ensure firewall rules are correct
|
||||||
|
4. Check disk space and resources
|
140
README.md
Normal file
140
README.md
Normal file
@ -0,0 +1,140 @@
|
|||||||
|
# InInventer - Inventory Management System
|
||||||
|
|
||||||
|
A modern web-based inventory management system with role-based access control (RBAC), built using the MERN stack (MongoDB, Express, React, Node.js).
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **Role-Based Access Control (RBAC)**
|
||||||
|
- Superadmin: Full system access
|
||||||
|
- Company Admin: Manage company users and products
|
||||||
|
- Employer: View products and limited actions
|
||||||
|
|
||||||
|
- **Product Management**
|
||||||
|
- Add, edit, and delete products
|
||||||
|
- Track quantities with visual indicators
|
||||||
|
- Search and filter capabilities
|
||||||
|
|
||||||
|
- **User Management**
|
||||||
|
- Create and manage users
|
||||||
|
- Assign roles and companies
|
||||||
|
|
||||||
|
- **Modern UI/UX**
|
||||||
|
- Responsive design with Tailwind CSS
|
||||||
|
- Gradient themes and animations
|
||||||
|
- Clean, intuitive interface
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
- **Frontend**: React, Vite, Tailwind CSS
|
||||||
|
- **Backend**: Node.js, Express.js
|
||||||
|
- **Database**: MongoDB
|
||||||
|
- **Authentication**: JWT
|
||||||
|
- **Containerization**: Docker
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- Docker and Docker Compose
|
||||||
|
- Node.js 18+ (for local development)
|
||||||
|
- Git
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
1. **Clone the repository**
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/yourusername/ininventer.git
|
||||||
|
cd ininventer
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Set up environment variables**
|
||||||
|
```bash
|
||||||
|
# Copy example files
|
||||||
|
cp .env.example .env
|
||||||
|
cp frontend/.env.example frontend/.env
|
||||||
|
|
||||||
|
# Edit .env with your configuration
|
||||||
|
# IMPORTANT: Change all default values, especially:
|
||||||
|
# - MONGO_INITDB_ROOT_USERNAME
|
||||||
|
# - MONGO_INITDB_ROOT_PASSWORD
|
||||||
|
# - JWT_SECRET
|
||||||
|
# - SUPERADMIN_EMAIL
|
||||||
|
# - SUPERADMIN_PASSWORD
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Start with Docker Compose**
|
||||||
|
```bash
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Access the application**
|
||||||
|
- Frontend: http://localhost:3000
|
||||||
|
- Backend API: http://localhost:5000
|
||||||
|
- MongoDB: localhost:27017
|
||||||
|
|
||||||
|
5. **Initial Login**
|
||||||
|
- Use the credentials you set in SUPERADMIN_EMAIL and SUPERADMIN_PASSWORD
|
||||||
|
- **Important**: Change the password immediately after first login
|
||||||
|
|
||||||
|
## Environment Configuration
|
||||||
|
|
||||||
|
### Required Environment Variables
|
||||||
|
|
||||||
|
See `.env.example` for all available options. Key variables:
|
||||||
|
|
||||||
|
- `MONGO_URI`: MongoDB connection string
|
||||||
|
- `JWT_SECRET`: Secret key for JWT tokens (use a long random string)
|
||||||
|
- `SUPERADMIN_EMAIL`: Initial admin email
|
||||||
|
- `SUPERADMIN_PASSWORD`: Initial admin password
|
||||||
|
- `NODE_ENV`: Environment (development/production)
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
### Local Development Setup
|
||||||
|
|
||||||
|
1. **Backend**
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Frontend**
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
ininventer/
|
||||||
|
├── backend/ # Express.js API
|
||||||
|
│ ├── models/ # MongoDB schemas
|
||||||
|
│ ├── routes/ # API endpoints
|
||||||
|
│ ├── middleware/ # Auth & error handling
|
||||||
|
│ └── utils/ # Helper functions
|
||||||
|
├── frontend/ # React application
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── components/ # React components
|
||||||
|
│ │ ├── contexts/ # Context providers
|
||||||
|
│ │ └── styles/ # CSS files
|
||||||
|
├── nginx/ # Nginx configuration
|
||||||
|
├── docker-compose.yml # Docker composition
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
See `DEPLOYMENT.md` for detailed production deployment instructions.
|
||||||
|
|
||||||
|
## Security Notes
|
||||||
|
|
||||||
|
- Never commit `.env` files or any file with real credentials
|
||||||
|
- Always use strong, unique passwords
|
||||||
|
- Regularly update dependencies
|
||||||
|
- Use HTTPS in production
|
||||||
|
- Enable MongoDB authentication
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This project is licensed under the MIT License.
|
78
SECURITY.md
Normal file
78
SECURITY.md
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
# Security Guidelines
|
||||||
|
|
||||||
|
## Important Security Practices
|
||||||
|
|
||||||
|
### Environment Variables
|
||||||
|
|
||||||
|
1. **Never commit real credentials**
|
||||||
|
- Always use `.env.example` as a template
|
||||||
|
- Keep actual `.env` files in `.gitignore`
|
||||||
|
- Use different credentials for development and production
|
||||||
|
|
||||||
|
2. **Required secure values**:
|
||||||
|
```bash
|
||||||
|
# Generate a secure JWT secret (example using openssl)
|
||||||
|
openssl rand -base64 64
|
||||||
|
|
||||||
|
# Use strong passwords for MongoDB
|
||||||
|
# At least 16 characters with mixed case, numbers, and symbols
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Default credentials to change**:
|
||||||
|
- `SUPERADMIN_EMAIL`: Change from default
|
||||||
|
- `SUPERADMIN_PASSWORD`: Use a strong password
|
||||||
|
- `MONGO_INITDB_ROOT_USERNAME`: Don't use "admin"
|
||||||
|
- `MONGO_INITDB_ROOT_PASSWORD`: Use a unique password
|
||||||
|
- `JWT_SECRET`: Must be a long random string
|
||||||
|
|
||||||
|
### Production Security Checklist
|
||||||
|
|
||||||
|
- [ ] Change all default passwords
|
||||||
|
- [ ] Use HTTPS with valid SSL certificates
|
||||||
|
- [ ] Enable MongoDB authentication
|
||||||
|
- [ ] Set `NODE_ENV=production`
|
||||||
|
- [ ] Use environment-specific `.env` files
|
||||||
|
- [ ] Enable rate limiting on API endpoints
|
||||||
|
- [ ] Regularly update all dependencies
|
||||||
|
- [ ] Monitor logs for suspicious activity
|
||||||
|
- [ ] Implement backup strategy
|
||||||
|
- [ ] Use firewall rules to restrict access
|
||||||
|
|
||||||
|
### Git Security
|
||||||
|
|
||||||
|
Before committing:
|
||||||
|
1. Check for hardcoded credentials: `git diff --staged`
|
||||||
|
2. Verify `.gitignore` includes all sensitive files
|
||||||
|
3. Never commit:
|
||||||
|
- `.env` files
|
||||||
|
- SSL certificates
|
||||||
|
- Database dumps
|
||||||
|
- Log files
|
||||||
|
- Deployment packages
|
||||||
|
|
||||||
|
### API Security
|
||||||
|
|
||||||
|
The application implements:
|
||||||
|
- JWT authentication with expiration
|
||||||
|
- Password hashing with bcrypt
|
||||||
|
- Role-based access control
|
||||||
|
- Input validation
|
||||||
|
- CORS configuration
|
||||||
|
|
||||||
|
### Reporting Security Issues
|
||||||
|
|
||||||
|
If you discover a security vulnerability, please email security@yourdomain.com instead of using the issue tracker.
|
||||||
|
|
||||||
|
## Development vs Production
|
||||||
|
|
||||||
|
### Development
|
||||||
|
- Can use weaker passwords for convenience
|
||||||
|
- MongoDB without authentication is acceptable
|
||||||
|
- Self-signed certificates are fine
|
||||||
|
|
||||||
|
### Production
|
||||||
|
- Must use strong, unique passwords
|
||||||
|
- MongoDB authentication is mandatory
|
||||||
|
- Valid SSL certificates from Let's Encrypt or similar
|
||||||
|
- Regular security updates
|
||||||
|
- Monitoring and alerting
|
13
backend/Dockerfile
Normal file
13
backend/Dockerfile
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
FROM node:16-alpine
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
RUN npm install --production
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
EXPOSE 5000
|
||||||
|
|
||||||
|
CMD ["npm", "start"]
|
82
backend/controllers/authController.js
Normal file
82
backend/controllers/authController.js
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
const jwt = require('jsonwebtoken');
|
||||||
|
const User = require('../models/User');
|
||||||
|
const { validationResult } = require('express-validator');
|
||||||
|
|
||||||
|
// Helper function to generate JWT
|
||||||
|
const generateToken = (id) => {
|
||||||
|
return jwt.sign({ id }, process.env.JWT_SECRET, {
|
||||||
|
expiresIn: process.env.JWT_EXPIRATION || '24h'
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Login user
|
||||||
|
// @route POST /api/auth/login
|
||||||
|
// @access Public
|
||||||
|
exports.login = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const errors = validationResult(req);
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
errors: errors.array()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const { email, password } = req.body;
|
||||||
|
|
||||||
|
// Check if user exists
|
||||||
|
const user = await User.findOne({ email }).select('+password');
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return res.status(401).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Invalid credentials'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if password matches
|
||||||
|
const isMatch = await user.comparePassword(password);
|
||||||
|
|
||||||
|
if (!isMatch) {
|
||||||
|
return res.status(401).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Invalid credentials'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate token
|
||||||
|
const token = generateToken(user._id);
|
||||||
|
|
||||||
|
// Remove password from response
|
||||||
|
const userResponse = {
|
||||||
|
_id: user._id,
|
||||||
|
email: user.email,
|
||||||
|
role: user.role,
|
||||||
|
companyId: user.companyId
|
||||||
|
};
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
token,
|
||||||
|
user: userResponse
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Get current logged in user
|
||||||
|
// @route GET /api/auth/me
|
||||||
|
// @access Private
|
||||||
|
exports.getMe = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const user = await User.findById(req.user.id).select('-password');
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
data: user
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
183
backend/controllers/companyController.js
Normal file
183
backend/controllers/companyController.js
Normal file
@ -0,0 +1,183 @@
|
|||||||
|
const Company = require('../models/Company');
|
||||||
|
const User = require('../models/User');
|
||||||
|
const { validationResult } = require('express-validator');
|
||||||
|
|
||||||
|
// @desc Get all companies
|
||||||
|
// @route GET /api/companies
|
||||||
|
// @access Private (superadmin: all companies, companyadmin/employer: only their company)
|
||||||
|
exports.getCompanies = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
let companies;
|
||||||
|
|
||||||
|
// If superadmin, get all companies
|
||||||
|
if (req.user.role === 'superadmin') {
|
||||||
|
companies = await Company.find();
|
||||||
|
} else {
|
||||||
|
// For companyadmin and employer, get only their company
|
||||||
|
companies = await Company.find({ _id: req.user.companyId });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
count: companies.length,
|
||||||
|
data: companies
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Get single company
|
||||||
|
// @route GET /api/companies/:id
|
||||||
|
// @access Private (superadmin: any company, companyadmin/employer: only their company)
|
||||||
|
exports.getCompany = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const company = await Company.findById(req.params.id);
|
||||||
|
|
||||||
|
if (!company) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Company not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if user is trying to access a company they don't belong to
|
||||||
|
if (req.user.role !== 'superadmin' &&
|
||||||
|
company._id.toString() !== req.user.companyId.toString()) {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to access this company'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
data: company
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Create company
|
||||||
|
// @route POST /api/companies
|
||||||
|
// @access Private (superadmin only)
|
||||||
|
exports.createCompany = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const errors = validationResult(req);
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
errors: errors.array()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only superadmin can create companies
|
||||||
|
if (req.user.role !== 'superadmin') {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Only superadmin can create companies'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const company = await Company.create({
|
||||||
|
...req.body,
|
||||||
|
createdBy: req.user._id
|
||||||
|
});
|
||||||
|
|
||||||
|
res.status(201).json({
|
||||||
|
success: true,
|
||||||
|
data: company
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Update company
|
||||||
|
// @route PUT /api/companies/:id
|
||||||
|
// @access Private (superadmin only)
|
||||||
|
exports.updateCompany = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const errors = validationResult(req);
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
errors: errors.array()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only superadmin can update companies
|
||||||
|
if (req.user.role !== 'superadmin') {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Only superadmin can update companies'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let company = await Company.findById(req.params.id);
|
||||||
|
|
||||||
|
if (!company) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Company not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
company = await Company.findByIdAndUpdate(
|
||||||
|
req.params.id,
|
||||||
|
req.body,
|
||||||
|
{ new: true, runValidators: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
data: company
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Delete company
|
||||||
|
// @route DELETE /api/companies/:id
|
||||||
|
// @access Private (superadmin only)
|
||||||
|
exports.deleteCompany = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
// Only superadmin can delete companies
|
||||||
|
if (req.user.role !== 'superadmin') {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Only superadmin can delete companies'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const company = await Company.findById(req.params.id);
|
||||||
|
|
||||||
|
if (!company) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Company not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there are users associated with this company
|
||||||
|
const usersCount = await User.countDocuments({ companyId: company._id });
|
||||||
|
|
||||||
|
if (usersCount > 0) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Cannot delete company with associated users'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await company.deleteOne();
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
data: {}
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
195
backend/controllers/productController.js
Normal file
195
backend/controllers/productController.js
Normal file
@ -0,0 +1,195 @@
|
|||||||
|
const Product = require('../models/Product');
|
||||||
|
const { validationResult } = require('express-validator');
|
||||||
|
|
||||||
|
// @desc Get all products
|
||||||
|
// @route GET /api/products
|
||||||
|
// @access Private (all roles, but filtered by company)
|
||||||
|
exports.getProducts = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
let query = {};
|
||||||
|
|
||||||
|
// Filter products by company
|
||||||
|
if (req.user.role !== 'superadmin') {
|
||||||
|
query.companyId = req.user.companyId;
|
||||||
|
} else if (req.query.companyId) {
|
||||||
|
// Superadmin can filter by company
|
||||||
|
query.companyId = req.query.companyId;
|
||||||
|
}
|
||||||
|
|
||||||
|
const products = await Product.find(query)
|
||||||
|
.populate('companyId', 'name')
|
||||||
|
.populate('createdBy', 'email');
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
count: products.length,
|
||||||
|
data: products
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Get single product
|
||||||
|
// @route GET /api/products/:id
|
||||||
|
// @access Private (all roles, but filtered by company)
|
||||||
|
exports.getProduct = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const product = await Product.findById(req.params.id)
|
||||||
|
.populate('companyId', 'name')
|
||||||
|
.populate('createdBy', 'email');
|
||||||
|
|
||||||
|
if (!product) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Product not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if user has access to this product
|
||||||
|
if (req.user.role !== 'superadmin' &&
|
||||||
|
product.companyId._id.toString() !== req.user.companyId.toString()) {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to access this product'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
data: product
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Create product
|
||||||
|
// @route POST /api/products
|
||||||
|
// @access Private (all roles, but company is restricted)
|
||||||
|
exports.createProduct = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const errors = validationResult(req);
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
errors: errors.array()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set company ID based on user role
|
||||||
|
let companyId;
|
||||||
|
|
||||||
|
if (req.user.role === 'superadmin' && req.body.companyId) {
|
||||||
|
// Superadmin can specify company
|
||||||
|
companyId = req.body.companyId;
|
||||||
|
} else {
|
||||||
|
// Other roles can only add products to their own company
|
||||||
|
companyId = req.user.companyId;
|
||||||
|
}
|
||||||
|
|
||||||
|
const product = await Product.create({
|
||||||
|
...req.body,
|
||||||
|
companyId,
|
||||||
|
createdBy: req.user._id
|
||||||
|
});
|
||||||
|
|
||||||
|
res.status(201).json({
|
||||||
|
success: true,
|
||||||
|
data: product
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Update product
|
||||||
|
// @route PUT /api/products/:id
|
||||||
|
// @access Private (all roles, but company is restricted)
|
||||||
|
exports.updateProduct = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const errors = validationResult(req);
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
errors: errors.array()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let product = await Product.findById(req.params.id);
|
||||||
|
|
||||||
|
if (!product) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Product not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if user has access to this product
|
||||||
|
if (req.user.role !== 'superadmin' &&
|
||||||
|
product.companyId.toString() !== req.user.companyId.toString()) {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to update this product'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prevent changing companyId for non-superadmin users
|
||||||
|
if (req.user.role !== 'superadmin' && req.body.companyId &&
|
||||||
|
req.body.companyId.toString() !== req.user.companyId.toString()) {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to change company for this product'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
product = await Product.findByIdAndUpdate(
|
||||||
|
req.params.id,
|
||||||
|
req.body,
|
||||||
|
{ new: true, runValidators: true }
|
||||||
|
)
|
||||||
|
.populate('companyId', 'name')
|
||||||
|
.populate('createdBy', 'email');
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
data: product
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Delete product
|
||||||
|
// @route DELETE /api/products/:id
|
||||||
|
// @access Private (all roles, but company is restricted)
|
||||||
|
exports.deleteProduct = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const product = await Product.findById(req.params.id);
|
||||||
|
|
||||||
|
if (!product) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Product not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if user has access to this product
|
||||||
|
if (req.user.role !== 'superadmin' &&
|
||||||
|
product.companyId.toString() !== req.user.companyId.toString()) {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to delete this product'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await product.deleteOne();
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
data: {}
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
280
backend/controllers/userController.js
Normal file
280
backend/controllers/userController.js
Normal file
@ -0,0 +1,280 @@
|
|||||||
|
const User = require('../models/User');
|
||||||
|
const { validationResult } = require('express-validator');
|
||||||
|
|
||||||
|
// @desc Get all users
|
||||||
|
// @route GET /api/users
|
||||||
|
// @access Private (superadmin: all users, companyadmin: only users from their company)
|
||||||
|
exports.getUsers = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
let query = {};
|
||||||
|
|
||||||
|
// If user is companyadmin, only get users from their company
|
||||||
|
if (req.user.role === 'companyadmin') {
|
||||||
|
query = { companyId: req.user.companyId };
|
||||||
|
}
|
||||||
|
|
||||||
|
const users = await User.find(query).select('-password');
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
count: users.length,
|
||||||
|
data: users
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Get single user
|
||||||
|
// @route GET /api/users/:id
|
||||||
|
// @access Private (superadmin: any user, companyadmin: only users from their company)
|
||||||
|
exports.getUser = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const user = await User.findById(req.params.id).select('-password');
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'User not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if companyadmin is trying to access user from another company
|
||||||
|
if (req.user.role === 'companyadmin' &&
|
||||||
|
user.companyId.toString() !== req.user.companyId.toString()) {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to access this user'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
data: user
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Create user
|
||||||
|
// @route POST /api/users
|
||||||
|
// @access Private (superadmin: can create any user, companyadmin: can only create employers in their company)
|
||||||
|
exports.createUser = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const errors = validationResult(req);
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
errors: errors.array()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const { email, password, role, companyId } = req.body;
|
||||||
|
|
||||||
|
// Check if user is trying to create a role they're not allowed to
|
||||||
|
if (req.user.role === 'companyadmin' && role !== 'employer') {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Company admin can only create employer users'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if companyadmin is trying to create user for another company
|
||||||
|
if (req.user.role === 'companyadmin' &&
|
||||||
|
companyId.toString() !== req.user.companyId.toString()) {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to create user for another company'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create user
|
||||||
|
const user = await User.create({
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
role,
|
||||||
|
companyId: role === 'superadmin' ? null : companyId,
|
||||||
|
createdBy: req.user._id
|
||||||
|
});
|
||||||
|
|
||||||
|
res.status(201).json({
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
_id: user._id,
|
||||||
|
email: user.email,
|
||||||
|
role: user.role,
|
||||||
|
companyId: user.companyId,
|
||||||
|
createdAt: user.createdAt
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Check for duplicate email
|
||||||
|
if (error.code === 11000) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Email already exists'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Update user
|
||||||
|
// @route PUT /api/users/:id
|
||||||
|
// @access Private (superadmin: any user, companyadmin: only employers in their company)
|
||||||
|
exports.updateUser = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const errors = validationResult(req);
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
errors: errors.array()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let user = await User.findById(req.params.id);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'User not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if companyadmin is trying to update user from another company
|
||||||
|
if (req.user.role === 'companyadmin' &&
|
||||||
|
user.companyId.toString() !== req.user.companyId.toString()) {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to update this user'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if companyadmin is trying to update a companyadmin
|
||||||
|
if (req.user.role === 'companyadmin' && user.role === 'companyadmin') {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Company admin cannot update other company admins'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if trying to change role to something not allowed
|
||||||
|
if (req.body.role && req.user.role === 'companyadmin' && req.body.role !== 'employer') {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Company admin can only update to employer role'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update user
|
||||||
|
user = await User.findByIdAndUpdate(
|
||||||
|
req.params.id,
|
||||||
|
req.body,
|
||||||
|
{ new: true, runValidators: true }
|
||||||
|
).select('-password');
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
data: user
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Delete user
|
||||||
|
// @route DELETE /api/users/:id
|
||||||
|
// @access Private (superadmin: any user, companyadmin: only employers in their company)
|
||||||
|
exports.deleteUser = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const user = await User.findById(req.params.id);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'User not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if companyadmin is trying to delete user from another company
|
||||||
|
if (req.user.role === 'companyadmin' &&
|
||||||
|
user.companyId.toString() !== req.user.companyId.toString()) {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to delete this user'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if companyadmin is trying to delete a companyadmin
|
||||||
|
if (req.user.role === 'companyadmin' && user.role === 'companyadmin') {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Company admin cannot delete other company admins'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await user.deleteOne();
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
data: {}
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// @desc Reset user password
|
||||||
|
// @route PUT /api/users/:id/reset-password
|
||||||
|
// @access Private (superadmin: any user, companyadmin: only employers in their company)
|
||||||
|
exports.resetPassword = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const errors = validationResult(req);
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
errors: errors.array()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const { newPassword } = req.body;
|
||||||
|
|
||||||
|
let user = await User.findById(req.params.id);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'User not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if companyadmin is trying to reset password for user from another company
|
||||||
|
if (req.user.role === 'companyadmin' &&
|
||||||
|
user.companyId.toString() !== req.user.companyId.toString()) {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to reset password for this user'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if companyadmin is trying to reset password for a companyadmin
|
||||||
|
if (req.user.role === 'companyadmin' && user.role === 'companyadmin') {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Company admin cannot reset password for other company admins'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update password
|
||||||
|
user.password = newPassword;
|
||||||
|
await user.save();
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
message: 'Password reset successful'
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
60
backend/middleware/auth.js
Normal file
60
backend/middleware/auth.js
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
const jwt = require('jsonwebtoken');
|
||||||
|
const User = require('../models/User');
|
||||||
|
|
||||||
|
// Middleware to verify JWT token
|
||||||
|
exports.protect = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
let token;
|
||||||
|
|
||||||
|
// Check if token exists in headers
|
||||||
|
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
|
||||||
|
token = req.headers.authorization.split(' ')[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if token exists
|
||||||
|
if (!token) {
|
||||||
|
return res.status(401).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to access this route'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Verify token
|
||||||
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||||
|
|
||||||
|
// Attach user to request
|
||||||
|
req.user = await User.findById(decoded.id);
|
||||||
|
|
||||||
|
if (!req.user) {
|
||||||
|
return res.status(401).json({
|
||||||
|
success: false,
|
||||||
|
message: 'User not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
next();
|
||||||
|
} catch (error) {
|
||||||
|
return res.status(401).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to access this route',
|
||||||
|
error: error.message
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Role-based authorization middleware
|
||||||
|
exports.authorize = (...roles) => {
|
||||||
|
return (req, res, next) => {
|
||||||
|
if (!roles.includes(req.user.role)) {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: `User role ${req.user.role} is not authorized to access this route`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
};
|
88
backend/middleware/companyAuth.js
Normal file
88
backend/middleware/companyAuth.js
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
const Company = require('../models/Company');
|
||||||
|
const User = require('../models/User');
|
||||||
|
|
||||||
|
// Middleware to check if user has access to the company
|
||||||
|
exports.checkCompanyAccess = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const companyId = req.params.companyId || req.body.companyId;
|
||||||
|
|
||||||
|
if (!companyId) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Company ID is required'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Superadmin has access to all companies
|
||||||
|
if (req.user.role === 'superadmin') {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if user belongs to the requested company
|
||||||
|
if (req.user.companyId && req.user.companyId.toString() === companyId) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to access data from this company'
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Middleware to check if user can manage other users
|
||||||
|
exports.checkUserManagementAccess = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const targetUserId = req.params.id;
|
||||||
|
|
||||||
|
if (!targetUserId) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the target user
|
||||||
|
const targetUser = await User.findById(targetUserId);
|
||||||
|
|
||||||
|
if (!targetUser) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'User not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Superadmin can manage any user
|
||||||
|
if (req.user.role === 'superadmin') {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Company admin can only manage employers in their company
|
||||||
|
if (req.user.role === 'companyadmin') {
|
||||||
|
// Check if target user is from the same company
|
||||||
|
if (targetUser.companyId.toString() !== req.user.companyId.toString()) {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to manage users from other companies'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if target user is not a company admin
|
||||||
|
if (targetUser.role === 'companyadmin') {
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Company admin cannot manage other company admins'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Employers cannot manage users
|
||||||
|
return res.status(403).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Not authorized to manage users'
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
20
backend/models/Company.js
Normal file
20
backend/models/Company.js
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
const mongoose = require('mongoose');
|
||||||
|
|
||||||
|
const CompanySchema = new mongoose.Schema({
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
trim: true
|
||||||
|
},
|
||||||
|
createdBy: {
|
||||||
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
|
ref: 'User',
|
||||||
|
required: true
|
||||||
|
},
|
||||||
|
createdAt: {
|
||||||
|
type: Date,
|
||||||
|
default: Date.now
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = mongoose.model('Company', CompanySchema);
|
34
backend/models/Product.js
Normal file
34
backend/models/Product.js
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
const mongoose = require('mongoose');
|
||||||
|
|
||||||
|
const ProductSchema = new mongoose.Schema({
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
trim: true
|
||||||
|
},
|
||||||
|
quantity: {
|
||||||
|
type: Number,
|
||||||
|
required: true,
|
||||||
|
default: 0
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: String,
|
||||||
|
trim: true
|
||||||
|
},
|
||||||
|
companyId: {
|
||||||
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
|
ref: 'Company',
|
||||||
|
required: true
|
||||||
|
},
|
||||||
|
createdBy: {
|
||||||
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
|
ref: 'User',
|
||||||
|
required: true
|
||||||
|
},
|
||||||
|
createdAt: {
|
||||||
|
type: Date,
|
||||||
|
default: Date.now
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = mongoose.model('Product', ProductSchema);
|
72
backend/models/User.js
Normal file
72
backend/models/User.js
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
const mongoose = require('mongoose');
|
||||||
|
const bcrypt = require('bcryptjs');
|
||||||
|
|
||||||
|
const UserSchema = new mongoose.Schema({
|
||||||
|
email: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
unique: true,
|
||||||
|
trim: true,
|
||||||
|
lowercase: true
|
||||||
|
},
|
||||||
|
password: {
|
||||||
|
type: String,
|
||||||
|
required: true
|
||||||
|
},
|
||||||
|
password_plain: {
|
||||||
|
type: String,
|
||||||
|
select: false // Only retrievable when explicitly requested
|
||||||
|
},
|
||||||
|
role: {
|
||||||
|
type: String,
|
||||||
|
enum: ['superadmin', 'companyadmin', 'employer'],
|
||||||
|
required: true
|
||||||
|
},
|
||||||
|
companyId: {
|
||||||
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
|
ref: 'Company',
|
||||||
|
required: function() {
|
||||||
|
return this.role !== 'superadmin'; // Only required for companyadmin and employer
|
||||||
|
}
|
||||||
|
},
|
||||||
|
createdBy: {
|
||||||
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
|
ref: 'User'
|
||||||
|
},
|
||||||
|
createdAt: {
|
||||||
|
type: Date,
|
||||||
|
default: Date.now
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Hash password before saving
|
||||||
|
UserSchema.pre('save', async function(next) {
|
||||||
|
if (!this.isModified('password')) return next();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Store plain text password if provided (for superadmin use)
|
||||||
|
if (this.password) {
|
||||||
|
this.password_plain = this.password;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash the password
|
||||||
|
const salt = await bcrypt.genSalt(10);
|
||||||
|
this.password = await bcrypt.hash(this.password, salt);
|
||||||
|
next();
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Method to compare password
|
||||||
|
UserSchema.methods.comparePassword = async function(password) {
|
||||||
|
// If we have a plain text password stored and we're in development, use it for comparison
|
||||||
|
if (this.password_plain && process.env.NODE_ENV !== 'production' && password === this.password_plain) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise use bcrypt to compare the hashed passwords
|
||||||
|
return await bcrypt.compare(password, this.password);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = mongoose.model('User', UserSchema);
|
1765
backend/package-lock.json
generated
Normal file
1765
backend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
24
backend/package.json
Normal file
24
backend/package.json
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"name": "ininventer-backend",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "Inventory Management System Backend",
|
||||||
|
"main": "server.js",
|
||||||
|
"scripts": {
|
||||||
|
"start": "node server.js",
|
||||||
|
"dev": "nodemon server.js"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"bcryptjs": "^2.4.3",
|
||||||
|
"cors": "^2.8.5",
|
||||||
|
"dotenv": "^16.0.3",
|
||||||
|
"express": "^4.18.2",
|
||||||
|
"express-rate-limit": "^6.7.0",
|
||||||
|
"express-validator": "^7.0.1",
|
||||||
|
"jsonwebtoken": "^9.0.0",
|
||||||
|
"mongoose": "^7.2.0",
|
||||||
|
"morgan": "^1.10.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"nodemon": "^2.0.22"
|
||||||
|
}
|
||||||
|
}
|
21
backend/routes/auth.js
Normal file
21
backend/routes/auth.js
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { check } = require('express-validator');
|
||||||
|
const { login, getMe } = require('../controllers/authController');
|
||||||
|
const { protect } = require('../middleware/auth');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Login route
|
||||||
|
router.post(
|
||||||
|
'/login',
|
||||||
|
[
|
||||||
|
check('email', 'Please include a valid email').isEmail(),
|
||||||
|
check('password', 'Password is required').exists()
|
||||||
|
],
|
||||||
|
login
|
||||||
|
);
|
||||||
|
|
||||||
|
// Get current user route
|
||||||
|
router.get('/me', protect, getMe);
|
||||||
|
|
||||||
|
module.exports = router;
|
50
backend/routes/companies.js
Normal file
50
backend/routes/companies.js
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { check } = require('express-validator');
|
||||||
|
const {
|
||||||
|
getCompanies,
|
||||||
|
getCompany,
|
||||||
|
createCompany,
|
||||||
|
updateCompany,
|
||||||
|
deleteCompany
|
||||||
|
} = require('../controllers/companyController');
|
||||||
|
const { protect, authorize } = require('../middleware/auth');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Protect all routes
|
||||||
|
router.use(protect);
|
||||||
|
|
||||||
|
// Get all companies
|
||||||
|
router.get('/', getCompanies);
|
||||||
|
|
||||||
|
// Get single company
|
||||||
|
router.get('/:id', getCompany);
|
||||||
|
|
||||||
|
// Create company - superadmin only
|
||||||
|
router.post(
|
||||||
|
'/',
|
||||||
|
authorize('superadmin'),
|
||||||
|
[
|
||||||
|
check('name', 'Company name is required').not().isEmpty()
|
||||||
|
],
|
||||||
|
createCompany
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update company - superadmin only
|
||||||
|
router.put(
|
||||||
|
'/:id',
|
||||||
|
authorize('superadmin'),
|
||||||
|
[
|
||||||
|
check('name', 'Company name is required').not().isEmpty()
|
||||||
|
],
|
||||||
|
updateCompany
|
||||||
|
);
|
||||||
|
|
||||||
|
// Delete company - superadmin only
|
||||||
|
router.delete(
|
||||||
|
'/:id',
|
||||||
|
authorize('superadmin'),
|
||||||
|
deleteCompany
|
||||||
|
);
|
||||||
|
|
||||||
|
module.exports = router;
|
48
backend/routes/products.js
Normal file
48
backend/routes/products.js
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { check } = require('express-validator');
|
||||||
|
const {
|
||||||
|
getProducts,
|
||||||
|
getProduct,
|
||||||
|
createProduct,
|
||||||
|
updateProduct,
|
||||||
|
deleteProduct
|
||||||
|
} = require('../controllers/productController');
|
||||||
|
const { protect } = require('../middleware/auth');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Protect all routes
|
||||||
|
router.use(protect);
|
||||||
|
|
||||||
|
// Get all products
|
||||||
|
router.get('/', getProducts);
|
||||||
|
|
||||||
|
// Get single product
|
||||||
|
router.get('/:id', getProduct);
|
||||||
|
|
||||||
|
// Create product
|
||||||
|
router.post(
|
||||||
|
'/',
|
||||||
|
[
|
||||||
|
check('name', 'Product name is required').not().isEmpty(),
|
||||||
|
check('quantity', 'Quantity must be a number').isNumeric(),
|
||||||
|
check('description', 'Description is required').not().isEmpty()
|
||||||
|
],
|
||||||
|
createProduct
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update product
|
||||||
|
router.put(
|
||||||
|
'/:id',
|
||||||
|
[
|
||||||
|
check('name', 'Product name is required').optional().not().isEmpty(),
|
||||||
|
check('quantity', 'Quantity must be a number').optional().isNumeric(),
|
||||||
|
check('description', 'Description is required').optional().not().isEmpty()
|
||||||
|
],
|
||||||
|
updateProduct
|
||||||
|
);
|
||||||
|
|
||||||
|
// Delete product
|
||||||
|
router.delete('/:id', deleteProduct);
|
||||||
|
|
||||||
|
module.exports = router;
|
79
backend/routes/users.js
Normal file
79
backend/routes/users.js
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { check } = require('express-validator');
|
||||||
|
const {
|
||||||
|
getUsers,
|
||||||
|
getUser,
|
||||||
|
createUser,
|
||||||
|
updateUser,
|
||||||
|
deleteUser,
|
||||||
|
resetPassword
|
||||||
|
} = require('../controllers/userController');
|
||||||
|
const { protect, authorize } = require('../middleware/auth');
|
||||||
|
const { checkUserManagementAccess } = require('../middleware/companyAuth');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Protect all routes
|
||||||
|
router.use(protect);
|
||||||
|
|
||||||
|
// Get all users
|
||||||
|
router.get(
|
||||||
|
'/',
|
||||||
|
authorize('superadmin', 'companyadmin'),
|
||||||
|
getUsers
|
||||||
|
);
|
||||||
|
|
||||||
|
// Get single user
|
||||||
|
router.get(
|
||||||
|
'/:id',
|
||||||
|
authorize('superadmin', 'companyadmin'),
|
||||||
|
checkUserManagementAccess,
|
||||||
|
getUser
|
||||||
|
);
|
||||||
|
|
||||||
|
// Create user
|
||||||
|
router.post(
|
||||||
|
'/',
|
||||||
|
authorize('superadmin', 'companyadmin'),
|
||||||
|
[
|
||||||
|
check('email', 'Please include a valid email').isEmail(),
|
||||||
|
check('password', 'Please enter a password with 6 or more characters').isLength({ min: 6 }),
|
||||||
|
check('role', 'Role is required').not().isEmpty(),
|
||||||
|
check('companyId', 'Company ID is required for non-superadmin users').custom((value, { req }) => {
|
||||||
|
if (req.body.role !== 'superadmin' && !value) {
|
||||||
|
throw new Error('Company ID is required for non-superadmin users');
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
],
|
||||||
|
createUser
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update user
|
||||||
|
router.put(
|
||||||
|
'/:id',
|
||||||
|
authorize('superadmin', 'companyadmin'),
|
||||||
|
checkUserManagementAccess,
|
||||||
|
updateUser
|
||||||
|
);
|
||||||
|
|
||||||
|
// Delete user
|
||||||
|
router.delete(
|
||||||
|
'/:id',
|
||||||
|
authorize('superadmin', 'companyadmin'),
|
||||||
|
checkUserManagementAccess,
|
||||||
|
deleteUser
|
||||||
|
);
|
||||||
|
|
||||||
|
// Reset password
|
||||||
|
router.put(
|
||||||
|
'/:id/reset-password',
|
||||||
|
authorize('superadmin', 'companyadmin'),
|
||||||
|
checkUserManagementAccess,
|
||||||
|
[
|
||||||
|
check('newPassword', 'Please enter a password with 6 or more characters').isLength({ min: 6 })
|
||||||
|
],
|
||||||
|
resetPassword
|
||||||
|
);
|
||||||
|
|
||||||
|
module.exports = router;
|
90
backend/server.js
Normal file
90
backend/server.js
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const mongoose = require('mongoose');
|
||||||
|
const cors = require('cors');
|
||||||
|
const morgan = require('morgan');
|
||||||
|
const dotenv = require('dotenv');
|
||||||
|
const rateLimit = require('express-rate-limit');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
// Load environment variables
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
// Import routes
|
||||||
|
const authRoutes = require('./routes/auth');
|
||||||
|
const userRoutes = require('./routes/users');
|
||||||
|
const companyRoutes = require('./routes/companies');
|
||||||
|
const productRoutes = require('./routes/products');
|
||||||
|
|
||||||
|
// Import seed functions
|
||||||
|
const seedSuperAdmin = require('./utils/seedSuperAdmin');
|
||||||
|
const seedTestData = require('./utils/seedTestData');
|
||||||
|
|
||||||
|
// Initialize Express app
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
// Trust proxy for requests coming through Nginx
|
||||||
|
app.set('trust proxy', true);
|
||||||
|
|
||||||
|
// Configure rate limiting based on environment
|
||||||
|
const limiter = rateLimit({
|
||||||
|
windowMs: 1 * 60 * 1000, // 1 minute in development, 15 minutes in production
|
||||||
|
max: process.env.NODE_ENV === 'development' ? 1000 : 100, // Higher limit in development
|
||||||
|
message: 'Too many requests, please try again later',
|
||||||
|
standardHeaders: true,
|
||||||
|
legacyHeaders: false,
|
||||||
|
// Trust the X-Forwarded-For header from our reverse proxy
|
||||||
|
trustProxy: true
|
||||||
|
});
|
||||||
|
|
||||||
|
// Apply rate limiting to all requests except in development mode
|
||||||
|
if (process.env.NODE_ENV !== 'development') {
|
||||||
|
app.use(limiter);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Middleware
|
||||||
|
app.use(cors());
|
||||||
|
app.use(express.json());
|
||||||
|
app.use(morgan('dev'));
|
||||||
|
|
||||||
|
// Database connection
|
||||||
|
mongoose.connect(process.env.MONGO_URI, {
|
||||||
|
useNewUrlParser: true,
|
||||||
|
useUnifiedTopology: true
|
||||||
|
})
|
||||||
|
.then(async () => {
|
||||||
|
console.log('MongoDB connected');
|
||||||
|
|
||||||
|
// Seed superadmin user
|
||||||
|
await seedSuperAdmin();
|
||||||
|
|
||||||
|
// Seed test data
|
||||||
|
await seedTestData();
|
||||||
|
})
|
||||||
|
.catch(err => console.error('MongoDB connection error:', err));
|
||||||
|
|
||||||
|
// Routes
|
||||||
|
app.use('/api/auth', authRoutes);
|
||||||
|
app.use('/api/users', userRoutes);
|
||||||
|
app.use('/api/companies', companyRoutes);
|
||||||
|
app.use('/api/products', productRoutes);
|
||||||
|
|
||||||
|
// Health check endpoint
|
||||||
|
app.get('/health', (req, res) => {
|
||||||
|
res.status(200).json({ status: 'ok' });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Error handling middleware
|
||||||
|
app.use((err, req, res, next) => {
|
||||||
|
console.error(err.stack);
|
||||||
|
res.status(500).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Server error',
|
||||||
|
error: process.env.NODE_ENV === 'development' ? err.message : {}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Start server
|
||||||
|
const PORT = process.env.PORT || 5000;
|
||||||
|
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
|
||||||
|
|
||||||
|
module.exports = app;
|
85
backend/testLogin.js
Normal file
85
backend/testLogin.js
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
require('dotenv').config();
|
||||||
|
const mongoose = require('mongoose');
|
||||||
|
const User = require('./models/User');
|
||||||
|
|
||||||
|
const testLogin = async () => {
|
||||||
|
try {
|
||||||
|
// Connect to MongoDB
|
||||||
|
console.log('Connecting to MongoDB...');
|
||||||
|
console.log('MONGO_URI:', process.env.MONGO_URI);
|
||||||
|
|
||||||
|
await mongoose.connect(process.env.MONGO_URI, {
|
||||||
|
useNewUrlParser: true,
|
||||||
|
useUnifiedTopology: true
|
||||||
|
});
|
||||||
|
console.log('MongoDB connected');
|
||||||
|
|
||||||
|
// Test credentials
|
||||||
|
const email = 'admin@ininventer.com';
|
||||||
|
const password = 'admin123';
|
||||||
|
|
||||||
|
console.log(`Testing login with email: ${email} and password: ${password}`);
|
||||||
|
|
||||||
|
// Find the user
|
||||||
|
const user = await User.findOne({ email }).select('+password +password_plain');
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
console.log('User not found!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('User found:');
|
||||||
|
console.log('- ID:', user._id);
|
||||||
|
console.log('- Email:', user.email);
|
||||||
|
console.log('- Role:', user.role);
|
||||||
|
console.log('- Password (hashed):', user.password);
|
||||||
|
console.log('- Password (plain):', user.password_plain);
|
||||||
|
|
||||||
|
// Test password comparison
|
||||||
|
const isMatch = await user.comparePassword(password);
|
||||||
|
console.log(`Password comparison result: ${isMatch ? 'SUCCESS' : 'FAILED'}`);
|
||||||
|
|
||||||
|
// Test direct bcrypt comparison
|
||||||
|
const bcrypt = require('bcryptjs');
|
||||||
|
const bcryptMatch = await bcrypt.compare(password, user.password);
|
||||||
|
console.log(`Direct bcrypt comparison: ${bcryptMatch ? 'SUCCESS' : 'FAILED'}`);
|
||||||
|
|
||||||
|
// Create a test login function similar to the actual login controller
|
||||||
|
const testLoginFunction = async (email, password) => {
|
||||||
|
const user = await User.findOne({ email }).select('+password');
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return { success: false, message: 'User not found' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const isMatch = await user.comparePassword(password);
|
||||||
|
|
||||||
|
if (!isMatch) {
|
||||||
|
return { success: false, message: 'Invalid credentials' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
user: {
|
||||||
|
_id: user._id,
|
||||||
|
email: user.email,
|
||||||
|
role: user.role
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Test the login function
|
||||||
|
const loginResult = await testLoginFunction(email, password);
|
||||||
|
console.log('Login function test result:', loginResult);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in test login:', error);
|
||||||
|
} finally {
|
||||||
|
// Disconnect from MongoDB
|
||||||
|
await mongoose.disconnect();
|
||||||
|
console.log('MongoDB disconnected');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Run the test
|
||||||
|
testLogin();
|
52
backend/utils/seedSuperAdmin.js
Normal file
52
backend/utils/seedSuperAdmin.js
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
const User = require('../models/User');
|
||||||
|
const bcrypt = require('bcryptjs');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize a superadmin user
|
||||||
|
* This will run when the application starts
|
||||||
|
*/
|
||||||
|
const seedSuperAdmin = async () => {
|
||||||
|
try {
|
||||||
|
console.log('Checking for superadmin account...');
|
||||||
|
|
||||||
|
// Get credentials from environment variables
|
||||||
|
const email = process.env.SUPERADMIN_EMAIL || 'admin@example.com';
|
||||||
|
const password = process.env.SUPERADMIN_PASSWORD || 'changeme123';
|
||||||
|
|
||||||
|
// Check if superadmin already exists
|
||||||
|
const existingAdmin = await User.findOne({ role: 'superadmin' });
|
||||||
|
|
||||||
|
if (existingAdmin) {
|
||||||
|
console.log('Superadmin account already exists');
|
||||||
|
return existingAdmin;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a new superadmin
|
||||||
|
console.log('Creating superadmin account...');
|
||||||
|
|
||||||
|
const superadmin = new User({
|
||||||
|
email: email,
|
||||||
|
password: password, // This will be hashed by the pre-save hook
|
||||||
|
role: 'superadmin'
|
||||||
|
});
|
||||||
|
|
||||||
|
// Save the user to trigger the pre-save hook that hashes the password
|
||||||
|
await superadmin.save();
|
||||||
|
|
||||||
|
console.log(`Superadmin created with email: ${email}`);
|
||||||
|
console.log('IMPORTANT: Change the default password after first login!');
|
||||||
|
|
||||||
|
// Only store plain password in development for testing
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.log('Development mode: Password is set from SUPERADMIN_PASSWORD env variable');
|
||||||
|
}
|
||||||
|
|
||||||
|
return superadmin;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error seeding superadmin:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = seedSuperAdmin;
|
42
backend/utils/seedTestData.js
Normal file
42
backend/utils/seedTestData.js
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
const mongoose = require('mongoose');
|
||||||
|
const Company = require('../models/Company');
|
||||||
|
const User = require('../models/User');
|
||||||
|
|
||||||
|
const seedTestData = async () => {
|
||||||
|
try {
|
||||||
|
// Find the superadmin user
|
||||||
|
const superadmin = await User.findOne({ role: 'superadmin' });
|
||||||
|
|
||||||
|
if (!superadmin) {
|
||||||
|
console.log('Superadmin not found. Please ensure superadmin is created first.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if default company exists
|
||||||
|
let defaultCompany = await Company.findOne({ name: 'Default Company' });
|
||||||
|
|
||||||
|
if (!defaultCompany) {
|
||||||
|
// Create default company
|
||||||
|
defaultCompany = await Company.create({
|
||||||
|
name: 'Default Company',
|
||||||
|
createdBy: superadmin._id
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('Default company created:', defaultCompany.name);
|
||||||
|
|
||||||
|
// Update superadmin to have this company
|
||||||
|
await User.findByIdAndUpdate(superadmin._id, {
|
||||||
|
companyId: defaultCompany._id
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('Superadmin updated with default company');
|
||||||
|
} else {
|
||||||
|
console.log('Default company already exists');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error seeding test data:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = seedTestData;
|
90
backup.sh
Executable file
90
backup.sh
Executable file
@ -0,0 +1,90 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# InInventer Backup Script
|
||||||
|
# This script backs up MongoDB data and application files
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
BACKUP_DIR="/opt/backups/ininventer"
|
||||||
|
DATE=$(date +%Y%m%d_%H%M%S)
|
||||||
|
BACKUP_PATH="$BACKUP_DIR/$DATE"
|
||||||
|
RETENTION_DAYS=7
|
||||||
|
|
||||||
|
# Color codes
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
RED='\033[0;31m'
|
||||||
|
NC='\033[0m'
|
||||||
|
|
||||||
|
print_status() {
|
||||||
|
echo -e "${GREEN}[STATUS]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
print_error() {
|
||||||
|
echo -e "${RED}[ERROR]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create backup directory
|
||||||
|
print_status "Creating backup directory..."
|
||||||
|
mkdir -p "$BACKUP_PATH"
|
||||||
|
|
||||||
|
# Load environment
|
||||||
|
if [ -f ".env.production" ]; then
|
||||||
|
source .env.production
|
||||||
|
else
|
||||||
|
print_error ".env.production file not found!"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Backup MongoDB
|
||||||
|
print_status "Backing up MongoDB database..."
|
||||||
|
docker exec ininventer-mongodb-prod mongodump \
|
||||||
|
--username="$MONGO_INITDB_ROOT_USERNAME" \
|
||||||
|
--password="$MONGO_INITDB_ROOT_PASSWORD" \
|
||||||
|
--authenticationDatabase=admin \
|
||||||
|
--db="$MONGO_INITDB_DATABASE" \
|
||||||
|
--archive="/tmp/mongodb_backup_$DATE.gz" \
|
||||||
|
--gzip
|
||||||
|
|
||||||
|
# Copy MongoDB backup from container
|
||||||
|
docker cp "ininventer-mongodb-prod:/tmp/mongodb_backup_$DATE.gz" "$BACKUP_PATH/"
|
||||||
|
docker exec ininventer-mongodb-prod rm "/tmp/mongodb_backup_$DATE.gz"
|
||||||
|
|
||||||
|
# Backup environment file
|
||||||
|
print_status "Backing up environment configuration..."
|
||||||
|
cp .env.production "$BACKUP_PATH/"
|
||||||
|
|
||||||
|
# Backup SSL certificates
|
||||||
|
print_status "Backing up SSL certificates..."
|
||||||
|
if [ -d "certbot/conf" ]; then
|
||||||
|
tar -czf "$BACKUP_PATH/ssl_certificates_$DATE.tar.gz" -C certbot conf
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create backup info file
|
||||||
|
cat > "$BACKUP_PATH/backup_info.txt" << EOL
|
||||||
|
Backup Date: $(date)
|
||||||
|
MongoDB Database: $MONGO_INITDB_DATABASE
|
||||||
|
Domain: $DOMAIN_NAME
|
||||||
|
Backup Contents:
|
||||||
|
- MongoDB database dump
|
||||||
|
- Environment configuration
|
||||||
|
- SSL certificates
|
||||||
|
EOL
|
||||||
|
|
||||||
|
# Compress entire backup
|
||||||
|
print_status "Compressing backup..."
|
||||||
|
cd "$BACKUP_DIR"
|
||||||
|
tar -czf "ininventer_backup_$DATE.tar.gz" "$DATE"
|
||||||
|
rm -rf "$DATE"
|
||||||
|
|
||||||
|
# Clean old backups
|
||||||
|
print_status "Cleaning old backups (keeping last $RETENTION_DAYS days)..."
|
||||||
|
find "$BACKUP_DIR" -name "ininventer_backup_*.tar.gz" -mtime +$RETENTION_DAYS -delete
|
||||||
|
|
||||||
|
print_status "Backup completed successfully!"
|
||||||
|
print_status "Backup location: $BACKUP_DIR/ininventer_backup_$DATE.tar.gz"
|
||||||
|
|
||||||
|
# Show backup size
|
||||||
|
BACKUP_SIZE=$(du -h "$BACKUP_DIR/ininventer_backup_$DATE.tar.gz" | cut -f1)
|
||||||
|
print_status "Backup size: $BACKUP_SIZE"
|
286
deploy.sh
Executable file
286
deploy.sh
Executable file
@ -0,0 +1,286 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# InInventer Deployment Script for Debian 12
|
||||||
|
# This script will deploy the application to a Linode server
|
||||||
|
|
||||||
|
set -e # Exit on error
|
||||||
|
|
||||||
|
echo "======================================"
|
||||||
|
echo "InInventer Deployment Script"
|
||||||
|
echo "======================================"
|
||||||
|
|
||||||
|
# Variables
|
||||||
|
DOMAIN_NAME=""
|
||||||
|
EMAIL_FOR_SSL=""
|
||||||
|
APP_DIR="/opt/ininventer"
|
||||||
|
REPO_URL=""
|
||||||
|
|
||||||
|
# Color codes for output
|
||||||
|
RED='\033[0;31m'
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
NC='\033[0m' # No Color
|
||||||
|
|
||||||
|
# Function to print colored output
|
||||||
|
print_status() {
|
||||||
|
echo -e "${GREEN}[STATUS]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
print_error() {
|
||||||
|
echo -e "${RED}[ERROR]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
print_warning() {
|
||||||
|
echo -e "${YELLOW}[WARNING]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check if running as root
|
||||||
|
if [[ $EUID -ne 0 ]]; then
|
||||||
|
print_error "This script must be run as root"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Get domain name from user
|
||||||
|
read -p "Enter your domain name (e.g., inventory.example.com): " DOMAIN_NAME
|
||||||
|
read -p "Enter email for SSL certificate: " EMAIL_FOR_SSL
|
||||||
|
|
||||||
|
print_status "Starting deployment for domain: $DOMAIN_NAME"
|
||||||
|
|
||||||
|
# Update system
|
||||||
|
print_status "Updating system packages..."
|
||||||
|
apt-get update
|
||||||
|
apt-get upgrade -y
|
||||||
|
|
||||||
|
# Install required packages
|
||||||
|
print_status "Installing required packages..."
|
||||||
|
apt-get install -y \
|
||||||
|
apt-transport-https \
|
||||||
|
ca-certificates \
|
||||||
|
curl \
|
||||||
|
gnupg \
|
||||||
|
lsb-release \
|
||||||
|
git \
|
||||||
|
ufw
|
||||||
|
|
||||||
|
# Install Docker
|
||||||
|
print_status "Installing Docker..."
|
||||||
|
if ! command -v docker &> /dev/null; then
|
||||||
|
curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
|
||||||
|
echo \
|
||||||
|
"deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian \
|
||||||
|
$(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y docker-ce docker-ce-cli containerd.io
|
||||||
|
systemctl enable docker
|
||||||
|
systemctl start docker
|
||||||
|
else
|
||||||
|
print_status "Docker is already installed"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Install Docker Compose
|
||||||
|
print_status "Installing Docker Compose..."
|
||||||
|
if ! command -v docker-compose &> /dev/null; then
|
||||||
|
curl -L "https://github.com/docker/compose/releases/download/v2.20.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
|
||||||
|
chmod +x /usr/local/bin/docker-compose
|
||||||
|
else
|
||||||
|
print_status "Docker Compose is already installed"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Configure firewall
|
||||||
|
print_status "Configuring firewall..."
|
||||||
|
ufw allow 22/tcp
|
||||||
|
ufw allow 80/tcp
|
||||||
|
ufw allow 443/tcp
|
||||||
|
ufw --force enable
|
||||||
|
|
||||||
|
# Create application directory
|
||||||
|
print_status "Creating application directory..."
|
||||||
|
mkdir -p $APP_DIR
|
||||||
|
cd $APP_DIR
|
||||||
|
|
||||||
|
# Copy application files
|
||||||
|
print_status "Setting up application files..."
|
||||||
|
# Note: You'll need to upload your files to the server first
|
||||||
|
|
||||||
|
# Create production environment file
|
||||||
|
print_status "Creating production environment configuration..."
|
||||||
|
cat > .env.production << EOL
|
||||||
|
# MongoDB Configuration
|
||||||
|
MONGO_URI=mongodb://mongodb:27017/ininventer
|
||||||
|
MONGO_INITDB_ROOT_USERNAME=admin
|
||||||
|
MONGO_INITDB_ROOT_PASSWORD=$(openssl rand -base64 32)
|
||||||
|
MONGO_INITDB_DATABASE=ininventer
|
||||||
|
|
||||||
|
# JWT Configuration
|
||||||
|
JWT_SECRET=$(openssl rand -base64 64)
|
||||||
|
JWT_EXPIRATION=24h
|
||||||
|
|
||||||
|
# Node Environment
|
||||||
|
NODE_ENV=production
|
||||||
|
PORT=5000
|
||||||
|
|
||||||
|
# Domain Configuration
|
||||||
|
DOMAIN_NAME=$DOMAIN_NAME
|
||||||
|
EMAIL_FOR_SSL=$EMAIL_FOR_SSL
|
||||||
|
EOL
|
||||||
|
|
||||||
|
# Create production docker-compose file
|
||||||
|
print_status "Creating production docker-compose configuration..."
|
||||||
|
cat > docker-compose.production.yml << 'EOL'
|
||||||
|
services:
|
||||||
|
mongodb:
|
||||||
|
image: mongo:latest
|
||||||
|
container_name: ininventer-mongodb-prod
|
||||||
|
restart: always
|
||||||
|
volumes:
|
||||||
|
- mongodb_data:/data/db
|
||||||
|
environment:
|
||||||
|
- MONGO_INITDB_ROOT_USERNAME=${MONGO_INITDB_ROOT_USERNAME}
|
||||||
|
- MONGO_INITDB_ROOT_PASSWORD=${MONGO_INITDB_ROOT_PASSWORD}
|
||||||
|
- MONGO_INITDB_DATABASE=${MONGO_INITDB_DATABASE}
|
||||||
|
networks:
|
||||||
|
- ininventer-network
|
||||||
|
|
||||||
|
backend:
|
||||||
|
build: ./backend
|
||||||
|
container_name: ininventer-backend-prod
|
||||||
|
restart: always
|
||||||
|
depends_on:
|
||||||
|
- mongodb
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
|
- MONGO_URI=mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@mongodb:27017/${MONGO_INITDB_DATABASE}?authSource=admin
|
||||||
|
- JWT_SECRET=${JWT_SECRET}
|
||||||
|
- JWT_EXPIRATION=${JWT_EXPIRATION}
|
||||||
|
- PORT=5000
|
||||||
|
networks:
|
||||||
|
- ininventer-network
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
build:
|
||||||
|
context: ./frontend
|
||||||
|
args:
|
||||||
|
- VITE_API_URL=/api
|
||||||
|
container_name: ininventer-frontend-prod
|
||||||
|
restart: always
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
networks:
|
||||||
|
- ininventer-network
|
||||||
|
|
||||||
|
nginx:
|
||||||
|
image: nginx:alpine
|
||||||
|
container_name: ininventer-nginx-prod
|
||||||
|
restart: always
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
- "443:443"
|
||||||
|
volumes:
|
||||||
|
- ./nginx/production.conf:/etc/nginx/conf.d/default.conf
|
||||||
|
- ./certbot/conf:/etc/letsencrypt
|
||||||
|
- ./certbot/www:/var/www/certbot
|
||||||
|
depends_on:
|
||||||
|
- frontend
|
||||||
|
- backend
|
||||||
|
networks:
|
||||||
|
- ininventer-network
|
||||||
|
command: '/bin/sh -c ''while :; do sleep 6h & wait $${!}; nginx -s reload; done & nginx -g "daemon off;"'''
|
||||||
|
|
||||||
|
certbot:
|
||||||
|
image: certbot/certbot
|
||||||
|
container_name: ininventer-certbot
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ./certbot/conf:/etc/letsencrypt
|
||||||
|
- ./certbot/www:/var/www/certbot
|
||||||
|
entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
mongodb_data:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
ininventer-network:
|
||||||
|
driver: bridge
|
||||||
|
EOL
|
||||||
|
|
||||||
|
# Create Nginx production configuration
|
||||||
|
print_status "Creating Nginx production configuration..."
|
||||||
|
mkdir -p nginx
|
||||||
|
cat > nginx/production.conf << EOL
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name $DOMAIN_NAME;
|
||||||
|
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/certbot;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
return 301 https://\$server_name\$request_uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
server_name $DOMAIN_NAME;
|
||||||
|
|
||||||
|
ssl_certificate /etc/letsencrypt/live/$DOMAIN_NAME/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/$DOMAIN_NAME/privkey.pem;
|
||||||
|
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
|
client_max_body_size 10M;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://frontend:80;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade \$http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_cache_bypass \$http_upgrade;
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /api {
|
||||||
|
proxy_pass http://backend:5000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade \$http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_cache_bypass \$http_upgrade;
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EOL
|
||||||
|
|
||||||
|
# Create initial Nginx configuration for SSL setup
|
||||||
|
cat > nginx/initial.conf << EOL
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name $DOMAIN_NAME;
|
||||||
|
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/certbot;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
return 200 'InInventer - Setting up SSL...';
|
||||||
|
add_header Content-Type text/plain;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EOL
|
||||||
|
|
||||||
|
print_status "Deployment preparation complete!"
|
||||||
|
print_warning "Next steps:"
|
||||||
|
echo "1. Upload your application code to $APP_DIR"
|
||||||
|
echo "2. Run: cd $APP_DIR && ./start-production.sh"
|
||||||
|
echo ""
|
||||||
|
echo "The start script will:"
|
||||||
|
echo "- Obtain SSL certificates"
|
||||||
|
echo "- Start all services"
|
||||||
|
echo "- Configure automatic SSL renewal"
|
93
docker-compose.example.yml
Normal file
93
docker-compose.example.yml
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
# MongoDB Service
|
||||||
|
mongodb:
|
||||||
|
image: mongo:6
|
||||||
|
container_name: ininventer-mongodb
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "27017:27017"
|
||||||
|
environment:
|
||||||
|
MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME}
|
||||||
|
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
|
||||||
|
MONGO_INITDB_DATABASE: ${MONGO_INITDB_DATABASE}
|
||||||
|
volumes:
|
||||||
|
- mongodb_data:/data/db
|
||||||
|
networks:
|
||||||
|
- ininventer-network
|
||||||
|
|
||||||
|
# Backend API Service
|
||||||
|
backend:
|
||||||
|
build: ./backend
|
||||||
|
container_name: ininventer-backend
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "5000:5000"
|
||||||
|
environment:
|
||||||
|
NODE_ENV: ${NODE_ENV:-development}
|
||||||
|
MONGO_URI: ${MONGO_URI}
|
||||||
|
JWT_SECRET: ${JWT_SECRET}
|
||||||
|
JWT_EXPIRATION: ${JWT_EXPIRATION:-24h}
|
||||||
|
PORT: ${PORT:-5000}
|
||||||
|
SUPERADMIN_EMAIL: ${SUPERADMIN_EMAIL}
|
||||||
|
SUPERADMIN_PASSWORD: ${SUPERADMIN_PASSWORD}
|
||||||
|
depends_on:
|
||||||
|
- mongodb
|
||||||
|
networks:
|
||||||
|
- ininventer-network
|
||||||
|
volumes:
|
||||||
|
- ./backend:/app
|
||||||
|
- /app/node_modules
|
||||||
|
|
||||||
|
# Frontend Service
|
||||||
|
frontend:
|
||||||
|
build: ./frontend
|
||||||
|
container_name: ininventer-frontend
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "3000:80"
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
networks:
|
||||||
|
- ininventer-network
|
||||||
|
environment:
|
||||||
|
VITE_API_URL: ${VITE_API_URL:-http://localhost:5000}
|
||||||
|
|
||||||
|
# Nginx Service (Reverse Proxy)
|
||||||
|
nginx:
|
||||||
|
build:
|
||||||
|
context: ./nginx
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: ininventer-nginx
|
||||||
|
restart: always
|
||||||
|
ports:
|
||||||
|
- "8080:80"
|
||||||
|
- "8443:443"
|
||||||
|
volumes:
|
||||||
|
- ./nginx/certbot/conf:/etc/letsencrypt
|
||||||
|
- ./nginx/certbot/www:/var/www/certbot
|
||||||
|
depends_on:
|
||||||
|
- frontend
|
||||||
|
- backend
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
|
||||||
|
# Certbot Service for SSL - Commented out for local development
|
||||||
|
# Uncomment this section when deploying to production
|
||||||
|
# certbot:
|
||||||
|
# image: certbot/certbot
|
||||||
|
# container_name: ininventer-certbot
|
||||||
|
# volumes:
|
||||||
|
# - ./nginx/certbot/conf:/etc/letsencrypt
|
||||||
|
# - ./nginx/certbot/www:/var/www/certbot
|
||||||
|
# command: certonly --webroot --webroot-path=/var/www/certbot --email ${CERTBOT_EMAIL} --agree-tos --no-eff-email -d ${DOMAIN_NAME}
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
mongodb_data:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
ininventer-network:
|
||||||
|
driver: bridge
|
||||||
|
app-network:
|
||||||
|
driver: bridge
|
93
docker-compose.yml
Normal file
93
docker-compose.yml
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
# MongoDB Service
|
||||||
|
mongodb:
|
||||||
|
image: mongo:6
|
||||||
|
container_name: ininventer-mongodb
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "27017:27017"
|
||||||
|
environment:
|
||||||
|
MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME}
|
||||||
|
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
|
||||||
|
MONGO_INITDB_DATABASE: ${MONGO_INITDB_DATABASE}
|
||||||
|
volumes:
|
||||||
|
- mongodb_data:/data/db
|
||||||
|
networks:
|
||||||
|
- ininventer-network
|
||||||
|
|
||||||
|
# Backend API Service
|
||||||
|
backend:
|
||||||
|
build: ./backend
|
||||||
|
container_name: ininventer-backend
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "5000:5000"
|
||||||
|
environment:
|
||||||
|
NODE_ENV: ${NODE_ENV:-development}
|
||||||
|
MONGO_URI: ${MONGO_URI}
|
||||||
|
JWT_SECRET: ${JWT_SECRET}
|
||||||
|
JWT_EXPIRATION: ${JWT_EXPIRATION:-24h}
|
||||||
|
PORT: ${PORT:-5000}
|
||||||
|
SUPERADMIN_EMAIL: ${SUPERADMIN_EMAIL}
|
||||||
|
SUPERADMIN_PASSWORD: ${SUPERADMIN_PASSWORD}
|
||||||
|
depends_on:
|
||||||
|
- mongodb
|
||||||
|
networks:
|
||||||
|
- ininventer-network
|
||||||
|
volumes:
|
||||||
|
- ./backend:/app
|
||||||
|
- /app/node_modules
|
||||||
|
|
||||||
|
# Frontend Service
|
||||||
|
frontend:
|
||||||
|
build: ./frontend
|
||||||
|
container_name: ininventer-frontend
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "3000:80"
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
networks:
|
||||||
|
- ininventer-network
|
||||||
|
environment:
|
||||||
|
VITE_API_URL: ${VITE_API_URL:-http://localhost:5000}
|
||||||
|
|
||||||
|
# Nginx Service (Reverse Proxy)
|
||||||
|
nginx:
|
||||||
|
build:
|
||||||
|
context: ./nginx
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: ininventer-nginx
|
||||||
|
restart: always
|
||||||
|
ports:
|
||||||
|
- "8080:80"
|
||||||
|
- "8443:443"
|
||||||
|
volumes:
|
||||||
|
- ./nginx/certbot/conf:/etc/letsencrypt
|
||||||
|
- ./nginx/certbot/www:/var/www/certbot
|
||||||
|
depends_on:
|
||||||
|
- frontend
|
||||||
|
- backend
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
|
||||||
|
# Certbot Service for SSL - Commented out for local development
|
||||||
|
# Uncomment this section when deploying to production
|
||||||
|
# certbot:
|
||||||
|
# image: certbot/certbot
|
||||||
|
# container_name: ininventer-certbot
|
||||||
|
# volumes:
|
||||||
|
# - ./nginx/certbot/conf:/etc/letsencrypt
|
||||||
|
# - ./nginx/certbot/www:/var/www/certbot
|
||||||
|
# command: certonly --webroot --webroot-path=/var/www/certbot --email ${CERTBOT_EMAIL} --agree-tos --no-eff-email -d ${DOMAIN_NAME}
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
mongodb_data:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
ininventer-network:
|
||||||
|
driver: bridge
|
||||||
|
app-network:
|
||||||
|
driver: bridge
|
2
frontend/.env.example
Normal file
2
frontend/.env.example
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
# Frontend Environment Variables
|
||||||
|
VITE_API_URL=http://localhost:5000
|
24
frontend/.gitignore
vendored
Normal file
24
frontend/.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
18
frontend/Dockerfile
Normal file
18
frontend/Dockerfile
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
FROM node:18-alpine as build
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm install
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM nginx:alpine
|
||||||
|
|
||||||
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
COPY nginx/default.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
12
frontend/README.md
Normal file
12
frontend/README.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
# React + Vite
|
||||||
|
|
||||||
|
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||||
|
|
||||||
|
Currently, two official plugins are available:
|
||||||
|
|
||||||
|
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
|
||||||
|
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||||
|
|
||||||
|
## Expanding the ESLint configuration
|
||||||
|
|
||||||
|
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
|
33
frontend/eslint.config.js
Normal file
33
frontend/eslint.config.js
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import js from '@eslint/js'
|
||||||
|
import globals from 'globals'
|
||||||
|
import reactHooks from 'eslint-plugin-react-hooks'
|
||||||
|
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||||
|
|
||||||
|
export default [
|
||||||
|
{ ignores: ['dist'] },
|
||||||
|
{
|
||||||
|
files: ['**/*.{js,jsx}'],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
parserOptions: {
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
ecmaFeatures: { jsx: true },
|
||||||
|
sourceType: 'module',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
'react-hooks': reactHooks,
|
||||||
|
'react-refresh': reactRefresh,
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
...js.configs.recommended.rules,
|
||||||
|
...reactHooks.configs.recommended.rules,
|
||||||
|
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
|
||||||
|
'react-refresh/only-export-components': [
|
||||||
|
'warn',
|
||||||
|
{ allowConstantExport: true },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
13
frontend/index.html
Normal file
13
frontend/index.html
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Vite + React</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.jsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
28
frontend/nginx/default.conf
Normal file
28
frontend/nginx/default.conf
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name localhost;
|
||||||
|
|
||||||
|
# Serve static files
|
||||||
|
location / {
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html index.htm;
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
add_header Access-Control-Allow-Origin *;
|
||||||
|
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
|
||||||
|
add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
|
||||||
|
}
|
||||||
|
|
||||||
|
# Explicitly handle asset files
|
||||||
|
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
expires 30d;
|
||||||
|
add_header Cache-Control "public, max-age=2592000";
|
||||||
|
add_header Access-Control-Allow-Origin *;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Error pages
|
||||||
|
error_page 500 502 503 504 /50x.html;
|
||||||
|
location = /50x.html {
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
}
|
||||||
|
}
|
4492
frontend/package-lock.json
generated
Normal file
4492
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
35
frontend/package.json
Normal file
35
frontend/package.json
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"name": "frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@headlessui/react": "^1.7.18",
|
||||||
|
"@heroicons/react": "^2.1.1",
|
||||||
|
"axios": "^1.6.5",
|
||||||
|
"react": "^18.2.0",
|
||||||
|
"react-dom": "^18.2.0",
|
||||||
|
"react-router-dom": "^6.22.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.25.0",
|
||||||
|
"@tailwindcss/forms": "^0.5.10",
|
||||||
|
"@types/react": "^18.2.0",
|
||||||
|
"@types/react-dom": "^18.2.0",
|
||||||
|
"@vitejs/plugin-react": "^4.4.1",
|
||||||
|
"autoprefixer": "^10.4.17",
|
||||||
|
"eslint": "^9.25.0",
|
||||||
|
"eslint-plugin-react-hooks": "^5.2.0",
|
||||||
|
"eslint-plugin-react-refresh": "^0.4.19",
|
||||||
|
"globals": "^16.0.0",
|
||||||
|
"postcss": "^8.4.33",
|
||||||
|
"tailwindcss": "^3.4.1",
|
||||||
|
"vite": "^6.3.5"
|
||||||
|
}
|
||||||
|
}
|
6
frontend/postcss.config.js
Normal file
6
frontend/postcss.config.js
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
export default {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
1
frontend/public/vite.svg
Normal file
1
frontend/public/vite.svg
Normal file
@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
After Width: | Height: | Size: 1.5 KiB |
42
frontend/src/App.css
Normal file
42
frontend/src/App.css
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
#root {
|
||||||
|
max-width: 1280px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
height: 6em;
|
||||||
|
padding: 1.5em;
|
||||||
|
will-change: filter;
|
||||||
|
transition: filter 300ms;
|
||||||
|
}
|
||||||
|
.logo:hover {
|
||||||
|
filter: drop-shadow(0 0 2em #646cffaa);
|
||||||
|
}
|
||||||
|
.logo.react:hover {
|
||||||
|
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes logo-spin {
|
||||||
|
from {
|
||||||
|
transform: rotate(0deg);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: no-preference) {
|
||||||
|
a:nth-of-type(2) .logo {
|
||||||
|
animation: logo-spin infinite 20s linear;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
padding: 2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.read-the-docs {
|
||||||
|
color: #888;
|
||||||
|
}
|
91
frontend/src/App.jsx
Normal file
91
frontend/src/App.jsx
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
|
||||||
|
import { AuthProvider, useAuth } from './contexts/AuthContext';
|
||||||
|
import Layout from './components/Layout';
|
||||||
|
import ProtectedRoute from './components/ProtectedRoute';
|
||||||
|
import ApiTester from './components/ApiTester';
|
||||||
|
|
||||||
|
// Auth Pages
|
||||||
|
import Login from './pages/auth/Login';
|
||||||
|
|
||||||
|
// Dashboard
|
||||||
|
import Dashboard from './pages/dashboard/Dashboard';
|
||||||
|
|
||||||
|
// Companies
|
||||||
|
import Companies from './pages/companies/Companies';
|
||||||
|
|
||||||
|
// Users
|
||||||
|
import Users from './pages/users/Users';
|
||||||
|
|
||||||
|
// Products
|
||||||
|
import Products from './pages/products/Products';
|
||||||
|
|
||||||
|
import './App.css';
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
return (
|
||||||
|
<Router>
|
||||||
|
<AuthProvider>
|
||||||
|
<AppRoutes />
|
||||||
|
</AuthProvider>
|
||||||
|
</Router>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Separate component to use auth context after it's properly initialized
|
||||||
|
function AppRoutes() {
|
||||||
|
const { currentUser, loading } = useAuth();
|
||||||
|
console.log('Auth state in AppRoutes:', {
|
||||||
|
currentUser: currentUser ? {
|
||||||
|
id: currentUser._id,
|
||||||
|
email: currentUser.email,
|
||||||
|
role: currentUser.role
|
||||||
|
} : null,
|
||||||
|
loading
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wait for auth to initialize before rendering routes
|
||||||
|
if (loading) {
|
||||||
|
return <div className="flex justify-center items-center h-screen">Loading authentication...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Routes>
|
||||||
|
{/* Public routes */}
|
||||||
|
<Route path="/login" element={
|
||||||
|
currentUser ? <Navigate to="/dashboard" replace /> : <Login />
|
||||||
|
} />
|
||||||
|
<Route path="/api-test" element={<ApiTester />} />
|
||||||
|
|
||||||
|
{/* Debug route - accessible without authentication */}
|
||||||
|
<Route path="/dashboard-public" element={<Dashboard />} />
|
||||||
|
|
||||||
|
{/* Protected routes */}
|
||||||
|
<Route element={<ProtectedRoute allowedRoles={['superadmin', 'companyadmin', 'employer']} />}>
|
||||||
|
<Route element={<Layout />}>
|
||||||
|
<Route path="/dashboard" element={<Dashboard />} />
|
||||||
|
<Route path="/products" element={<Products />} />
|
||||||
|
|
||||||
|
{/* Admin-only routes */}
|
||||||
|
<Route element={<ProtectedRoute allowedRoles={['superadmin', 'companyadmin']} />}>
|
||||||
|
<Route path="/users" element={<Users />} />
|
||||||
|
</Route>
|
||||||
|
|
||||||
|
<Route element={<ProtectedRoute allowedRoles={['superadmin']} />}>
|
||||||
|
<Route path="/companies" element={<Companies />} />
|
||||||
|
</Route>
|
||||||
|
</Route>
|
||||||
|
</Route>
|
||||||
|
|
||||||
|
{/* Redirect to dashboard if logged in, otherwise to login */}
|
||||||
|
<Route path="/" element={
|
||||||
|
<Navigate to={currentUser ? "/dashboard" : "/login"} replace />
|
||||||
|
} />
|
||||||
|
|
||||||
|
<Route path="*" element={
|
||||||
|
<Navigate to={currentUser ? "/dashboard" : "/login"} replace />
|
||||||
|
} />
|
||||||
|
</Routes>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
1
frontend/src/assets/react.svg
Normal file
1
frontend/src/assets/react.svg
Normal file
@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
After Width: | Height: | Size: 4.0 KiB |
147
frontend/src/components/ApiTester.jsx
Normal file
147
frontend/src/components/ApiTester.jsx
Normal file
@ -0,0 +1,147 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { testHealthEndpoint, testAuthEndpoint, testProductsEndpoint } from '../utils/apiTest';
|
||||||
|
|
||||||
|
const ApiTester = () => {
|
||||||
|
const [healthStatus, setHealthStatus] = useState({ loading: true, data: null, error: null });
|
||||||
|
const [authStatus, setAuthStatus] = useState({ loading: false, data: null, error: null });
|
||||||
|
const [productsStatus, setProductsStatus] = useState({ loading: false, data: null, error: null });
|
||||||
|
const [credentials, setCredentials] = useState({ email: 'admin@example.com', password: 'password123' });
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Test health endpoint on component mount
|
||||||
|
const checkHealth = async () => {
|
||||||
|
setHealthStatus({ loading: true, data: null, error: null });
|
||||||
|
const result = await testHealthEndpoint();
|
||||||
|
if (result.success) {
|
||||||
|
setHealthStatus({ loading: false, data: result.data, error: null });
|
||||||
|
} else {
|
||||||
|
setHealthStatus({ loading: false, data: null, error: result.error });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
checkHealth();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleAuthTest = async () => {
|
||||||
|
setAuthStatus({ loading: true, data: null, error: null });
|
||||||
|
const result = await testAuthEndpoint(credentials);
|
||||||
|
if (result.success) {
|
||||||
|
setAuthStatus({ loading: false, data: result.data, error: null });
|
||||||
|
// If auth successful, test products endpoint with the token
|
||||||
|
if (result.data.token) {
|
||||||
|
await handleProductsTest(result.data.token);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
setAuthStatus({ loading: false, data: null, error: result.error });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleProductsTest = async (token) => {
|
||||||
|
setProductsStatus({ loading: true, data: null, error: null });
|
||||||
|
const result = await testProductsEndpoint(token);
|
||||||
|
if (result.success) {
|
||||||
|
setProductsStatus({ loading: false, data: result.data, error: null });
|
||||||
|
} else {
|
||||||
|
setProductsStatus({ loading: false, data: null, error: result.error });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleInputChange = (e) => {
|
||||||
|
const { name, value } = e.target;
|
||||||
|
setCredentials(prev => ({ ...prev, [name]: value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 max-w-4xl mx-auto bg-white rounded-lg shadow-md">
|
||||||
|
<h2 className="text-2xl font-bold mb-6 text-gray-800">API Connection Tester</h2>
|
||||||
|
|
||||||
|
{/* Health Endpoint Test */}
|
||||||
|
<div className="mb-8 p-4 border rounded-lg">
|
||||||
|
<h3 className="text-xl font-semibold mb-2 text-gray-700">Health Endpoint</h3>
|
||||||
|
{healthStatus.loading ? (
|
||||||
|
<p className="text-gray-600">Testing health endpoint...</p>
|
||||||
|
) : healthStatus.error ? (
|
||||||
|
<div className="bg-red-50 p-3 rounded border border-red-200">
|
||||||
|
<p className="text-red-600 font-medium">Error: {JSON.stringify(healthStatus.error)}</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="bg-green-50 p-3 rounded border border-green-200">
|
||||||
|
<p className="text-green-600 font-medium">Success: {JSON.stringify(healthStatus.data)}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Auth Endpoint Test */}
|
||||||
|
<div className="mb-8 p-4 border rounded-lg">
|
||||||
|
<h3 className="text-xl font-semibold mb-2 text-gray-700">Authentication Endpoint</h3>
|
||||||
|
<div className="mb-4">
|
||||||
|
<div className="mb-3">
|
||||||
|
<label className="block text-gray-700 mb-1">Email</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
name="email"
|
||||||
|
value={credentials.email}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
className="w-full px-3 py-2 border rounded-md"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="mb-3">
|
||||||
|
<label className="block text-gray-700 mb-1">Password</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
name="password"
|
||||||
|
value={credentials.password}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
className="w-full px-3 py-2 border rounded-md"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleAuthTest}
|
||||||
|
className="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600"
|
||||||
|
disabled={authStatus.loading}
|
||||||
|
>
|
||||||
|
{authStatus.loading ? 'Testing...' : 'Test Auth Endpoint'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{authStatus.loading ? (
|
||||||
|
<p className="text-gray-600">Testing auth endpoint...</p>
|
||||||
|
) : authStatus.error ? (
|
||||||
|
<div className="bg-red-50 p-3 rounded border border-red-200">
|
||||||
|
<p className="text-red-600 font-medium">Error: {JSON.stringify(authStatus.error)}</p>
|
||||||
|
</div>
|
||||||
|
) : authStatus.data && (
|
||||||
|
<div className="bg-green-50 p-3 rounded border border-green-200">
|
||||||
|
<p className="text-green-600 font-medium">Success: Authentication successful</p>
|
||||||
|
<pre className="mt-2 text-sm bg-gray-50 p-2 rounded overflow-auto max-h-40">
|
||||||
|
{JSON.stringify(authStatus.data, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Products Endpoint Test */}
|
||||||
|
<div className="p-4 border rounded-lg">
|
||||||
|
<h3 className="text-xl font-semibold mb-2 text-gray-700">Products Endpoint</h3>
|
||||||
|
<p className="text-gray-600 mb-4">This test will run automatically after successful authentication.</p>
|
||||||
|
|
||||||
|
{productsStatus.loading ? (
|
||||||
|
<p className="text-gray-600">Testing products endpoint...</p>
|
||||||
|
) : productsStatus.error ? (
|
||||||
|
<div className="bg-red-50 p-3 rounded border border-red-200">
|
||||||
|
<p className="text-red-600 font-medium">Error: {JSON.stringify(productsStatus.error)}</p>
|
||||||
|
</div>
|
||||||
|
) : productsStatus.data && (
|
||||||
|
<div className="bg-green-50 p-3 rounded border border-green-200">
|
||||||
|
<p className="text-green-600 font-medium">Success: Products retrieved</p>
|
||||||
|
<pre className="mt-2 text-sm bg-gray-50 p-2 rounded overflow-auto max-h-40">
|
||||||
|
{JSON.stringify(productsStatus.data, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ApiTester;
|
13
frontend/src/components/Layout.jsx
Normal file
13
frontend/src/components/Layout.jsx
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import { Outlet } from 'react-router-dom';
|
||||||
|
import Navbar from './Navbar';
|
||||||
|
|
||||||
|
export default function Layout() {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-gray-50">
|
||||||
|
<Navbar />
|
||||||
|
<main className="max-w-7xl mx-auto">
|
||||||
|
<Outlet />
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
15
frontend/src/components/Layout/Layout.jsx
Normal file
15
frontend/src/components/Layout/Layout.jsx
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
import { Outlet } from 'react-router-dom';
|
||||||
|
import Navbar from './Navbar';
|
||||||
|
|
||||||
|
export default function Layout() {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-100">
|
||||||
|
<Navbar />
|
||||||
|
<main className="py-10">
|
||||||
|
<div className="max-w-7xl mx-auto sm:px-6 lg:px-8">
|
||||||
|
<Outlet />
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
165
frontend/src/components/Layout/Navbar.jsx
Normal file
165
frontend/src/components/Layout/Navbar.jsx
Normal file
@ -0,0 +1,165 @@
|
|||||||
|
import { Fragment } from 'react';
|
||||||
|
import { Link, useNavigate } from 'react-router-dom';
|
||||||
|
import { Disclosure, Menu, Transition } from '@headlessui/react';
|
||||||
|
import { Bars3Icon, XMarkIcon } from '@heroicons/react/24/outline';
|
||||||
|
import { useAuth } from '../../contexts/AuthContext';
|
||||||
|
|
||||||
|
function classNames(...classes) {
|
||||||
|
return classes.filter(Boolean).join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Navbar() {
|
||||||
|
const { currentUser, logout, hasRole } = useAuth();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
logout();
|
||||||
|
navigate('/login');
|
||||||
|
};
|
||||||
|
|
||||||
|
// Define navigation items based on user role
|
||||||
|
const getNavigationItems = () => {
|
||||||
|
const items = [
|
||||||
|
{ name: 'Dashboard', href: '/dashboard', current: false },
|
||||||
|
{ name: 'Products', href: '/products', current: false }
|
||||||
|
];
|
||||||
|
|
||||||
|
// Add Companies link for superadmin
|
||||||
|
if (hasRole('superadmin')) {
|
||||||
|
items.push({ name: 'Companies', href: '/companies', current: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add Users link for superadmin and companyadmin
|
||||||
|
if (hasRole(['superadmin', 'companyadmin'])) {
|
||||||
|
items.push({ name: 'Users', href: '/users', current: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
return items;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Disclosure as="nav" className="bg-gray-800">
|
||||||
|
{({ open }) => (
|
||||||
|
<>
|
||||||
|
<div className="mx-auto max-w-7xl px-2 sm:px-6 lg:px-8">
|
||||||
|
<div className="relative flex h-16 items-center justify-between">
|
||||||
|
<div className="absolute inset-y-0 left-0 flex items-center sm:hidden">
|
||||||
|
{/* Mobile menu button*/}
|
||||||
|
<Disclosure.Button className="relative inline-flex items-center justify-center rounded-md p-2 text-gray-400 hover:bg-gray-700 hover:text-white focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white">
|
||||||
|
<span className="absolute -inset-0.5" />
|
||||||
|
<span className="sr-only">Open main menu</span>
|
||||||
|
{open ? (
|
||||||
|
<XMarkIcon className="block h-6 w-6" aria-hidden="true" />
|
||||||
|
) : (
|
||||||
|
<Bars3Icon className="block h-6 w-6" aria-hidden="true" />
|
||||||
|
)}
|
||||||
|
</Disclosure.Button>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-1 items-center justify-center sm:items-stretch sm:justify-start">
|
||||||
|
<div className="flex flex-shrink-0 items-center">
|
||||||
|
<Link to="/" className="text-white font-bold text-xl">InInventer</Link>
|
||||||
|
</div>
|
||||||
|
<div className="hidden sm:ml-6 sm:block">
|
||||||
|
<div className="flex space-x-4">
|
||||||
|
{currentUser && getNavigationItems().map((item) => (
|
||||||
|
<Link
|
||||||
|
key={item.name}
|
||||||
|
to={item.href}
|
||||||
|
className={classNames(
|
||||||
|
item.current
|
||||||
|
? 'bg-gray-900 text-white'
|
||||||
|
: 'text-gray-300 hover:bg-gray-700 hover:text-white',
|
||||||
|
'rounded-md px-3 py-2 text-sm font-medium'
|
||||||
|
)}
|
||||||
|
aria-current={item.current ? 'page' : undefined}
|
||||||
|
>
|
||||||
|
{item.name}
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="absolute inset-y-0 right-0 flex items-center pr-2 sm:static sm:inset-auto sm:ml-6 sm:pr-0">
|
||||||
|
{currentUser ? (
|
||||||
|
<Menu as="div" className="relative ml-3">
|
||||||
|
<div>
|
||||||
|
<Menu.Button className="relative flex rounded-full bg-gray-800 text-sm focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-gray-800">
|
||||||
|
<span className="absolute -inset-1.5" />
|
||||||
|
<span className="sr-only">Open user menu</span>
|
||||||
|
<div className="h-8 w-8 rounded-full bg-gray-500 flex items-center justify-center text-white">
|
||||||
|
{currentUser.email.charAt(0).toUpperCase()}
|
||||||
|
</div>
|
||||||
|
</Menu.Button>
|
||||||
|
</div>
|
||||||
|
<Transition
|
||||||
|
as={Fragment}
|
||||||
|
enter="transition ease-out duration-100"
|
||||||
|
enterFrom="transform opacity-0 scale-95"
|
||||||
|
enterTo="transform opacity-100 scale-100"
|
||||||
|
leave="transition ease-in duration-75"
|
||||||
|
leaveFrom="transform opacity-100 scale-100"
|
||||||
|
leaveTo="transform opacity-0 scale-95"
|
||||||
|
>
|
||||||
|
<Menu.Items className="absolute right-0 z-10 mt-2 w-48 origin-top-right rounded-md bg-white py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
|
||||||
|
<Menu.Item>
|
||||||
|
{({ active }) => (
|
||||||
|
<div className="px-4 py-2 text-sm text-gray-700">
|
||||||
|
<div>{currentUser.email}</div>
|
||||||
|
<div className="text-xs text-gray-500 mt-1">
|
||||||
|
Role: {currentUser.role}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Menu.Item>
|
||||||
|
<Menu.Item>
|
||||||
|
{({ active }) => (
|
||||||
|
<button
|
||||||
|
onClick={handleLogout}
|
||||||
|
className={classNames(
|
||||||
|
active ? 'bg-gray-100' : '',
|
||||||
|
'block w-full text-left px-4 py-2 text-sm text-gray-700'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
Sign out
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</Menu.Item>
|
||||||
|
</Menu.Items>
|
||||||
|
</Transition>
|
||||||
|
</Menu>
|
||||||
|
) : (
|
||||||
|
<Link
|
||||||
|
to="/login"
|
||||||
|
className="text-gray-300 hover:bg-gray-700 hover:text-white rounded-md px-3 py-2 text-sm font-medium"
|
||||||
|
>
|
||||||
|
Login
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Disclosure.Panel className="sm:hidden">
|
||||||
|
<div className="space-y-1 px-2 pb-3 pt-2">
|
||||||
|
{currentUser && getNavigationItems().map((item) => (
|
||||||
|
<Link
|
||||||
|
key={item.name}
|
||||||
|
to={item.href}
|
||||||
|
className={classNames(
|
||||||
|
item.current
|
||||||
|
? 'bg-gray-900 text-white'
|
||||||
|
: 'text-gray-300 hover:bg-gray-700 hover:text-white',
|
||||||
|
'block rounded-md px-3 py-2 text-base font-medium'
|
||||||
|
)}
|
||||||
|
aria-current={item.current ? 'page' : undefined}
|
||||||
|
>
|
||||||
|
{item.name}
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Disclosure.Panel>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Disclosure>
|
||||||
|
);
|
||||||
|
}
|
28
frontend/src/components/LogoutButton.jsx
Normal file
28
frontend/src/components/LogoutButton.jsx
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
|
||||||
|
export default function LogoutButton() {
|
||||||
|
const { logout } = useAuth();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
// Clear all authentication data
|
||||||
|
localStorage.removeItem('token');
|
||||||
|
localStorage.removeItem('user');
|
||||||
|
|
||||||
|
// Call the context logout function
|
||||||
|
logout();
|
||||||
|
|
||||||
|
// Force a page reload to clear any in-memory state
|
||||||
|
window.location.href = '/login';
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={handleLogout}
|
||||||
|
className="bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded"
|
||||||
|
>
|
||||||
|
Force Logout
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
162
frontend/src/components/Navbar.jsx
Normal file
162
frontend/src/components/Navbar.jsx
Normal file
@ -0,0 +1,162 @@
|
|||||||
|
import { Fragment } from 'react';
|
||||||
|
import { Link, useNavigate, useLocation } from 'react-router-dom';
|
||||||
|
import { Disclosure, Menu, Transition } from '@headlessui/react';
|
||||||
|
import { Bars3Icon, XMarkIcon } from '@heroicons/react/24/outline';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
|
||||||
|
export default function Navbar() {
|
||||||
|
const { currentUser, logout } = useAuth();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const location = useLocation();
|
||||||
|
|
||||||
|
// Navigation items based on user role
|
||||||
|
const navigation = [
|
||||||
|
{ name: 'Dashboard', href: '/dashboard' },
|
||||||
|
{ name: 'Products', href: '/products' },
|
||||||
|
// Only show Users link for superadmin and companyadmin
|
||||||
|
...(currentUser && ['superadmin', 'companyadmin'].includes(currentUser.role)
|
||||||
|
? [{ name: 'Users', href: '/users' }]
|
||||||
|
: []),
|
||||||
|
// Only show Companies link for superadmin
|
||||||
|
...(currentUser && currentUser.role === 'superadmin'
|
||||||
|
? [{ name: 'Companies', href: '/companies' }]
|
||||||
|
: [])
|
||||||
|
];
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
logout();
|
||||||
|
navigate('/login');
|
||||||
|
};
|
||||||
|
|
||||||
|
const isActive = (href) => location.pathname === href;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Disclosure as="nav" className="bg-white shadow-lg border-b border-gray-100">
|
||||||
|
{({ open }) => (
|
||||||
|
<>
|
||||||
|
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
|
||||||
|
<div className="relative flex h-16 items-center justify-between">
|
||||||
|
<div className="absolute inset-y-0 left-0 flex items-center sm:hidden">
|
||||||
|
{/* Mobile menu button*/}
|
||||||
|
<Disclosure.Button className="inline-flex items-center justify-center rounded-lg p-2 text-gray-500 hover:bg-gray-100 hover:text-gray-700 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-primary-500 transition-colors">
|
||||||
|
<span className="sr-only">Open main menu</span>
|
||||||
|
{open ? (
|
||||||
|
<XMarkIcon className="block h-6 w-6" aria-hidden="true" />
|
||||||
|
) : (
|
||||||
|
<Bars3Icon className="block h-6 w-6" aria-hidden="true" />
|
||||||
|
)}
|
||||||
|
</Disclosure.Button>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-1 items-center justify-center sm:items-stretch sm:justify-start">
|
||||||
|
<div className="flex flex-shrink-0 items-center">
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<div className="h-10 w-10 bg-gradient-to-br from-primary-600 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
|
||||||
|
<span className="text-white text-xl font-bold">II</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-xl font-bold bg-gradient-to-r from-primary-600 to-purple-600 bg-clip-text text-transparent">
|
||||||
|
InInventer
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="hidden sm:ml-10 sm:block">
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
{navigation.map((item) => (
|
||||||
|
<Link
|
||||||
|
key={item.name}
|
||||||
|
to={item.href}
|
||||||
|
className={`
|
||||||
|
relative px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200
|
||||||
|
${isActive(item.href)
|
||||||
|
? 'text-primary-700 bg-primary-50'
|
||||||
|
: 'text-gray-600 hover:text-primary-600 hover:bg-gray-50'
|
||||||
|
}
|
||||||
|
`}
|
||||||
|
>
|
||||||
|
{item.name}
|
||||||
|
{isActive(item.href) && (
|
||||||
|
<span className="absolute bottom-0 left-0 right-0 h-0.5 bg-gradient-to-r from-primary-600 to-purple-600 rounded-full" />
|
||||||
|
)}
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="absolute inset-y-0 right-0 flex items-center pr-2 sm:static sm:inset-auto sm:ml-6 sm:pr-0">
|
||||||
|
{/* Profile dropdown */}
|
||||||
|
<Menu as="div" className="relative ml-3">
|
||||||
|
<div>
|
||||||
|
<Menu.Button className="flex items-center rounded-full bg-gradient-to-br from-primary-500 to-purple-500 p-0.5 text-sm focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-primary-500 transition-transform hover:scale-105">
|
||||||
|
<span className="sr-only">Open user menu</span>
|
||||||
|
<div className="h-9 w-9 rounded-full bg-white flex items-center justify-center">
|
||||||
|
<span className="text-sm font-semibold text-gray-700">
|
||||||
|
{currentUser?.email?.charAt(0).toUpperCase() || 'U'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</Menu.Button>
|
||||||
|
</div>
|
||||||
|
<Transition
|
||||||
|
as={Fragment}
|
||||||
|
enter="transition ease-out duration-200"
|
||||||
|
enterFrom="transform opacity-0 scale-95"
|
||||||
|
enterTo="transform opacity-100 scale-100"
|
||||||
|
leave="transition ease-in duration-150"
|
||||||
|
leaveFrom="transform opacity-100 scale-100"
|
||||||
|
leaveTo="transform opacity-0 scale-95"
|
||||||
|
>
|
||||||
|
<Menu.Items className="absolute right-0 z-10 mt-2 w-56 origin-top-right rounded-xl bg-white shadow-xl ring-1 ring-black ring-opacity-5 focus:outline-none overflow-hidden">
|
||||||
|
<div className="px-4 py-3 bg-gradient-to-r from-gray-50 to-gray-100 border-b border-gray-200">
|
||||||
|
<p className="text-sm font-medium text-gray-900">{currentUser?.email}</p>
|
||||||
|
<p className="text-xs text-gray-500 mt-0.5">
|
||||||
|
<span className="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium bg-primary-100 text-primary-700 capitalize">
|
||||||
|
{currentUser?.role}
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Menu.Item>
|
||||||
|
{({ active }) => (
|
||||||
|
<button
|
||||||
|
onClick={handleLogout}
|
||||||
|
className={`${
|
||||||
|
active ? 'bg-gray-50' : ''
|
||||||
|
} block w-full text-left px-4 py-3 text-sm text-gray-700 hover:text-danger-600 transition-colors`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center">
|
||||||
|
<svg className="mr-3 h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
|
||||||
|
</svg>
|
||||||
|
Sign out
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</Menu.Item>
|
||||||
|
</Menu.Items>
|
||||||
|
</Transition>
|
||||||
|
</Menu>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Disclosure.Panel className="sm:hidden">
|
||||||
|
<div className="space-y-1 px-2 pb-3 pt-2">
|
||||||
|
{navigation.map((item) => (
|
||||||
|
<Link
|
||||||
|
key={item.name}
|
||||||
|
to={item.href}
|
||||||
|
className={`
|
||||||
|
block rounded-lg px-3 py-2 text-base font-medium transition-colors
|
||||||
|
${isActive(item.href)
|
||||||
|
? 'bg-primary-50 text-primary-700'
|
||||||
|
: 'text-gray-600 hover:bg-gray-50 hover:text-primary-600'
|
||||||
|
}
|
||||||
|
`}
|
||||||
|
>
|
||||||
|
{item.name}
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Disclosure.Panel>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Disclosure>
|
||||||
|
);
|
||||||
|
}
|
50
frontend/src/components/ProtectedRoute.jsx
Normal file
50
frontend/src/components/ProtectedRoute.jsx
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
import { Navigate, Outlet, useLocation } from 'react-router-dom';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
|
||||||
|
export default function ProtectedRoute({ allowedRoles }) {
|
||||||
|
const { currentUser, loading } = useAuth();
|
||||||
|
const location = useLocation();
|
||||||
|
|
||||||
|
console.log('ProtectedRoute check:', {
|
||||||
|
path: location.pathname,
|
||||||
|
currentUser: currentUser ? { email: currentUser.email, role: currentUser.role } : null,
|
||||||
|
allowedRoles,
|
||||||
|
hasRequiredRole: currentUser && allowedRoles ? allowedRoles.includes(currentUser.role) : true
|
||||||
|
});
|
||||||
|
|
||||||
|
// If still loading, show nothing
|
||||||
|
if (loading) {
|
||||||
|
return <div className="flex justify-center items-center h-screen">Loading...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If not logged in, redirect to login
|
||||||
|
if (!currentUser) {
|
||||||
|
return <Navigate to="/login" state={{ from: location }} replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If roles are specified and user doesn't have the required role, show unauthorized
|
||||||
|
if (allowedRoles && !allowedRoles.includes(currentUser.role)) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||||
|
<div className="bg-white p-8 rounded-lg shadow-md">
|
||||||
|
<h2 className="text-2xl font-bold text-red-600 mb-4">Unauthorized Access</h2>
|
||||||
|
<p className="text-gray-700 mb-4">
|
||||||
|
You don't have permission to access this page.
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-gray-500 mb-4">
|
||||||
|
Required roles: {allowedRoles.join(', ')}
|
||||||
|
</p>
|
||||||
|
<a
|
||||||
|
href="/dashboard"
|
||||||
|
className="inline-block bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
|
||||||
|
>
|
||||||
|
Return to Dashboard
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If all checks pass, render the child routes
|
||||||
|
return <Outlet />;
|
||||||
|
}
|
139
frontend/src/contexts/AuthContext.jsx
Normal file
139
frontend/src/contexts/AuthContext.jsx
Normal file
@ -0,0 +1,139 @@
|
|||||||
|
import { createContext, useState, useEffect, useContext } from 'react';
|
||||||
|
import axios from 'axios';
|
||||||
|
|
||||||
|
const AuthContext = createContext();
|
||||||
|
|
||||||
|
export const useAuth = () => useContext(AuthContext);
|
||||||
|
|
||||||
|
export const AuthProvider = ({ children }) => {
|
||||||
|
const [currentUser, setCurrentUser] = useState(null);
|
||||||
|
const [token, setToken] = useState(localStorage.getItem('token'));
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
// Configure axios defaults
|
||||||
|
// When running in Docker with Nginx, we don't need to specify the full URL
|
||||||
|
// as Nginx will handle the routing based on the path
|
||||||
|
axios.defaults.baseURL = import.meta.env.VITE_API_URL || '';
|
||||||
|
|
||||||
|
// Set auth token if it exists
|
||||||
|
if (token) {
|
||||||
|
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load user and set up authentication state
|
||||||
|
useEffect(() => {
|
||||||
|
console.log('AuthContext: Loading user from localStorage...');
|
||||||
|
const loadUser = async () => {
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
const savedUser = localStorage.getItem('user');
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
console.log('AuthContext: Token found in localStorage');
|
||||||
|
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
||||||
|
|
||||||
|
if (savedUser) {
|
||||||
|
try {
|
||||||
|
console.log('AuthContext: User found in localStorage, parsing...');
|
||||||
|
const parsedUser = JSON.parse(savedUser);
|
||||||
|
console.log('AuthContext: User parsed successfully:', parsedUser);
|
||||||
|
|
||||||
|
// Set user from localStorage immediately for better UX
|
||||||
|
setCurrentUser(parsedUser);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('AuthContext: Error parsing user from localStorage:', error);
|
||||||
|
localStorage.removeItem('user');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify with server in the background
|
||||||
|
try {
|
||||||
|
const response = await axios.get('/api/auth/me');
|
||||||
|
console.log('AuthContext: Server verification successful:', response.data);
|
||||||
|
|
||||||
|
// The /api/auth/me endpoint returns { success: true, data: user }
|
||||||
|
const userData = response.data.data || response.data;
|
||||||
|
|
||||||
|
setCurrentUser(userData);
|
||||||
|
localStorage.setItem('user', JSON.stringify(userData));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('AuthContext: Server verification failed:', error);
|
||||||
|
// If server verification fails, clear everything
|
||||||
|
localStorage.removeItem('token');
|
||||||
|
localStorage.removeItem('user');
|
||||||
|
delete axios.defaults.headers.common['Authorization'];
|
||||||
|
setCurrentUser(null);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log('AuthContext: No token found in localStorage');
|
||||||
|
setCurrentUser(null);
|
||||||
|
delete axios.defaults.headers.common['Authorization'];
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
loadUser();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Login function
|
||||||
|
const login = async (email, password) => {
|
||||||
|
try {
|
||||||
|
const res = await axios.post('/api/auth/login', { email, password });
|
||||||
|
const { token: newToken, user } = res.data;
|
||||||
|
|
||||||
|
console.log('Login successful:', { token: newToken, user });
|
||||||
|
|
||||||
|
// Save token and user to localStorage
|
||||||
|
localStorage.setItem('token', newToken);
|
||||||
|
localStorage.setItem('user', JSON.stringify(user));
|
||||||
|
|
||||||
|
// Set axios default header
|
||||||
|
axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`;
|
||||||
|
|
||||||
|
setToken(newToken);
|
||||||
|
setCurrentUser(user);
|
||||||
|
|
||||||
|
return user;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Login error:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Logout function
|
||||||
|
const logout = () => {
|
||||||
|
localStorage.removeItem('token');
|
||||||
|
localStorage.removeItem('user');
|
||||||
|
delete axios.defaults.headers.common['Authorization'];
|
||||||
|
setToken(null);
|
||||||
|
setCurrentUser(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check if user has required role
|
||||||
|
const hasRole = (requiredRoles) => {
|
||||||
|
if (!currentUser) return false;
|
||||||
|
|
||||||
|
if (Array.isArray(requiredRoles)) {
|
||||||
|
return requiredRoles.includes(currentUser.role);
|
||||||
|
}
|
||||||
|
|
||||||
|
return currentUser.role === requiredRoles;
|
||||||
|
};
|
||||||
|
|
||||||
|
const value = {
|
||||||
|
currentUser,
|
||||||
|
token,
|
||||||
|
loading,
|
||||||
|
login,
|
||||||
|
logout,
|
||||||
|
hasRole
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthContext.Provider value={value}>
|
||||||
|
{!loading && children}
|
||||||
|
</AuthContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AuthContext;
|
151
frontend/src/index.css
Normal file
151
frontend/src/index.css
Normal file
@ -0,0 +1,151 @@
|
|||||||
|
@tailwind base;
|
||||||
|
@tailwind components;
|
||||||
|
@tailwind utilities;
|
||||||
|
|
||||||
|
/* Modern CSS Variables */
|
||||||
|
:root {
|
||||||
|
--primary-50: #eff6ff;
|
||||||
|
--primary-100: #dbeafe;
|
||||||
|
--primary-200: #bfdbfe;
|
||||||
|
--primary-300: #93bbfd;
|
||||||
|
--primary-400: #60a5fa;
|
||||||
|
--primary-500: #3b82f6;
|
||||||
|
--primary-600: #2563eb;
|
||||||
|
--primary-700: #1d4ed8;
|
||||||
|
--primary-800: #1e40af;
|
||||||
|
--primary-900: #1e3a8a;
|
||||||
|
|
||||||
|
--gray-50: #f9fafb;
|
||||||
|
--gray-100: #f3f4f6;
|
||||||
|
--gray-200: #e5e7eb;
|
||||||
|
--gray-300: #d1d5db;
|
||||||
|
--gray-400: #9ca3af;
|
||||||
|
--gray-500: #6b7280;
|
||||||
|
--gray-600: #4b5563;
|
||||||
|
--gray-700: #374151;
|
||||||
|
--gray-800: #1f2937;
|
||||||
|
--gray-900: #111827;
|
||||||
|
|
||||||
|
--success-50: #f0fdf4;
|
||||||
|
--success-500: #22c55e;
|
||||||
|
--success-600: #16a34a;
|
||||||
|
|
||||||
|
--danger-50: #fef2f2;
|
||||||
|
--danger-500: #ef4444;
|
||||||
|
--danger-600: #dc2626;
|
||||||
|
|
||||||
|
--warning-50: #fffbeb;
|
||||||
|
--warning-500: #f59e0b;
|
||||||
|
--warning-600: #d97706;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Base Styles */
|
||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||||
|
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||||
|
sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Modern Button Styles */
|
||||||
|
.btn {
|
||||||
|
@apply inline-flex items-center justify-center px-4 py-2.5 border border-transparent text-sm font-medium rounded-lg focus:outline-none focus:ring-2 focus:ring-offset-2 transition-all duration-200 transform hover:scale-105;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
@apply bg-gradient-to-r from-primary-600 to-primary-700 text-white hover:from-primary-700 hover:to-primary-800 focus:ring-primary-500 shadow-lg hover:shadow-xl;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
@apply bg-white text-gray-700 border-gray-300 hover:bg-gray-50 focus:ring-primary-500 shadow-sm hover:shadow-md;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
@apply bg-gradient-to-r from-danger-500 to-danger-600 text-white hover:from-danger-600 hover:to-danger-700 focus:ring-danger-500 shadow-lg hover:shadow-xl;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Modern Card Styles */
|
||||||
|
.card {
|
||||||
|
@apply bg-white rounded-xl shadow-lg hover:shadow-xl transition-shadow duration-300 overflow-hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header {
|
||||||
|
@apply px-6 py-4 bg-gradient-to-r from-gray-50 to-gray-100 border-b border-gray-200;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-body {
|
||||||
|
@apply p-6;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Modern Form Styles */
|
||||||
|
.form-input {
|
||||||
|
@apply block w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 transition-colors duration-200;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-label {
|
||||||
|
@apply block text-sm font-semibold text-gray-700 mb-2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-error {
|
||||||
|
@apply mt-2 text-sm text-danger-600 flex items-center;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Modern Alert Styles */
|
||||||
|
.alert {
|
||||||
|
@apply p-4 rounded-lg flex items-start space-x-3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-error {
|
||||||
|
@apply bg-danger-50 text-danger-800 border border-danger-200;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-success {
|
||||||
|
@apply bg-success-50 text-success-800 border border-success-200;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-warning {
|
||||||
|
@apply bg-warning-50 text-warning-800 border border-warning-200;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Animations */
|
||||||
|
@keyframes fadeIn {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(10px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.animate-fadeIn {
|
||||||
|
animation: fadeIn 0.3s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Custom Scrollbar */
|
||||||
|
::-webkit-scrollbar {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-track {
|
||||||
|
background: var(--gray-100);
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
background: var(--gray-400);
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: var(--gray-500);
|
||||||
|
}
|
12
frontend/src/main.jsx
Normal file
12
frontend/src/main.jsx
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
import { StrictMode } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
// Import both CSS files to ensure styles are applied
|
||||||
|
import './styles/global.css'
|
||||||
|
import './index.css'
|
||||||
|
import App from './App.jsx'
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')).render(
|
||||||
|
<StrictMode>
|
||||||
|
<App />
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
197
frontend/src/pages/auth/Login.jsx
Normal file
197
frontend/src/pages/auth/Login.jsx
Normal file
@ -0,0 +1,197 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { useAuth } from '../../contexts/AuthContext';
|
||||||
|
import axios from 'axios';
|
||||||
|
|
||||||
|
export default function Login() {
|
||||||
|
const [email, setEmail] = useState(''); // Remove pre-filled email
|
||||||
|
const [password, setPassword] = useState(''); // Remove pre-filled password
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [authState, setAuthState] = useState({
|
||||||
|
hasToken: false,
|
||||||
|
hasUser: false,
|
||||||
|
tokenValue: null,
|
||||||
|
userValue: null
|
||||||
|
});
|
||||||
|
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { login, currentUser } = useAuth();
|
||||||
|
|
||||||
|
// Check and display current auth state for debugging
|
||||||
|
useEffect(() => {
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
const user = localStorage.getItem('user');
|
||||||
|
|
||||||
|
try {
|
||||||
|
setAuthState({
|
||||||
|
hasToken: !!token,
|
||||||
|
hasUser: !!user,
|
||||||
|
tokenValue: token ? `${token.substring(0, 10)}...` : null,
|
||||||
|
userValue: user ? JSON.parse(user) : null
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('Login page loaded with auth state:', {
|
||||||
|
hasToken: !!token,
|
||||||
|
hasUser: !!user,
|
||||||
|
currentUser
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error parsing user data:', error);
|
||||||
|
}
|
||||||
|
}, [currentUser]);
|
||||||
|
|
||||||
|
const handleSubmit = async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
try {
|
||||||
|
setError('');
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
console.log('Attempting login with:', { email, password: '***' });
|
||||||
|
|
||||||
|
// Try direct API call first
|
||||||
|
try {
|
||||||
|
const response = await axios.post('/api/auth/login', { email, password });
|
||||||
|
console.log('Login response:', response.data);
|
||||||
|
|
||||||
|
// Check if the response has the expected structure
|
||||||
|
if (response.data && response.data.success === true) {
|
||||||
|
const { token, user } = response.data;
|
||||||
|
|
||||||
|
console.log('Extracted token and user:', { tokenExists: !!token, user });
|
||||||
|
|
||||||
|
// Save token to localStorage
|
||||||
|
localStorage.setItem('token', token);
|
||||||
|
|
||||||
|
// Set axios default headers for future requests
|
||||||
|
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
||||||
|
|
||||||
|
// Update auth context manually
|
||||||
|
localStorage.setItem('user', JSON.stringify(user));
|
||||||
|
|
||||||
|
console.log('Login successful, redirecting based on role:', user.role);
|
||||||
|
|
||||||
|
// Force reload to ensure auth context is properly updated
|
||||||
|
window.location.href = '/dashboard';
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
console.error('Unexpected response structure:', response.data);
|
||||||
|
throw new Error('Invalid response structure from server');
|
||||||
|
}
|
||||||
|
} catch (directApiError) {
|
||||||
|
console.error('Direct API call failed:', directApiError);
|
||||||
|
console.error('Error details:', directApiError.response ? directApiError.response.data : 'No response data');
|
||||||
|
|
||||||
|
// If the error is a 401, show appropriate message
|
||||||
|
if (directApiError.response?.status === 401) {
|
||||||
|
setError('Invalid email or password');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw directApiError;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
setError('Failed to log in. Please check your credentials.');
|
||||||
|
console.error('Login error:', error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 via-white to-purple-50 py-12 px-4 sm:px-6 lg:px-8">
|
||||||
|
<div className="max-w-md w-full space-y-8 animate-fadeIn">
|
||||||
|
{/* Logo and Title */}
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="mx-auto h-20 w-20 bg-gradient-to-br from-blue-600 to-purple-600 rounded-2xl flex items-center justify-center shadow-2xl">
|
||||||
|
<span className="text-white text-3xl font-bold">II</span>
|
||||||
|
</div>
|
||||||
|
<h2 className="mt-6 text-4xl font-extrabold text-gray-900 tracking-tight">
|
||||||
|
InInventer
|
||||||
|
</h2>
|
||||||
|
<p className="mt-2 text-base text-gray-600">
|
||||||
|
Sign in to manage your inventory
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Login Form */}
|
||||||
|
<div className="mt-8 bg-white rounded-2xl shadow-2xl overflow-hidden">
|
||||||
|
<div className="px-8 py-10">
|
||||||
|
{error && (
|
||||||
|
<div className="alert alert-error mb-6 animate-fadeIn">
|
||||||
|
<svg className="w-5 h-5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
|
||||||
|
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
|
||||||
|
</svg>
|
||||||
|
<span>{error}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="email" className="form-label">
|
||||||
|
Email address
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="email"
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
autoComplete="email"
|
||||||
|
required
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
className="form-input"
|
||||||
|
placeholder="Enter your email"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="password" className="form-label">
|
||||||
|
Password
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
required
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
className="form-input"
|
||||||
|
placeholder="Enter your password"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="w-full btn btn-primary text-base py-3"
|
||||||
|
>
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex items-center justify-center">
|
||||||
|
<svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||||
|
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||||
|
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||||
|
</svg>
|
||||||
|
Signing in...
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
'Sign in'
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Footer */}
|
||||||
|
<div className="px-8 py-4 bg-gray-50 border-t border-gray-100">
|
||||||
|
<p className="text-xs text-center text-gray-500">
|
||||||
|
© 2025 InInventer. All rights reserved.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
174
frontend/src/pages/companies/Companies.jsx
Normal file
174
frontend/src/pages/companies/Companies.jsx
Normal file
@ -0,0 +1,174 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import axios from 'axios';
|
||||||
|
import { useAuth } from '../../contexts/AuthContext';
|
||||||
|
import CompanyForm from './CompanyForm';
|
||||||
|
|
||||||
|
export default function Companies() {
|
||||||
|
const { currentUser } = useAuth();
|
||||||
|
const [companies, setCompanies] = useState([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState(null);
|
||||||
|
const [showForm, setShowForm] = useState(false);
|
||||||
|
const [currentCompany, setCurrentCompany] = useState(null);
|
||||||
|
|
||||||
|
// Fetch companies when component mounts
|
||||||
|
useEffect(() => {
|
||||||
|
fetchCompanies();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const fetchCompanies = async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const res = await axios.get('/api/companies');
|
||||||
|
setCompanies(res.data.data);
|
||||||
|
setError(null);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching companies:', error);
|
||||||
|
setError('Failed to load companies');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddCompany = () => {
|
||||||
|
setCurrentCompany(null);
|
||||||
|
setShowForm(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEditCompany = (company) => {
|
||||||
|
setCurrentCompany(company);
|
||||||
|
setShowForm(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteCompany = async (id) => {
|
||||||
|
if (window.confirm('Are you sure you want to delete this company? This action cannot be undone.')) {
|
||||||
|
try {
|
||||||
|
await axios.delete(`/api/companies/${id}`);
|
||||||
|
setCompanies(companies.filter(company => company._id !== id));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting company:', error);
|
||||||
|
if (error.response && error.response.data && error.response.data.message) {
|
||||||
|
setError(error.response.data.message);
|
||||||
|
} else {
|
||||||
|
setError('Failed to delete company');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFormSubmit = async (formData) => {
|
||||||
|
try {
|
||||||
|
if (currentCompany) {
|
||||||
|
// Update existing company
|
||||||
|
await axios.put(`/api/companies/${currentCompany._id}`, formData);
|
||||||
|
} else {
|
||||||
|
// Create new company
|
||||||
|
await axios.post('/api/companies', formData);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh company list
|
||||||
|
fetchCompanies();
|
||||||
|
setShowForm(false);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving company:', error);
|
||||||
|
setError('Failed to save company');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFormCancel = () => {
|
||||||
|
setShowForm(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Only superadmin can access this page
|
||||||
|
if (currentUser.role !== 'superadmin') {
|
||||||
|
return (
|
||||||
|
<div className="text-center py-10">
|
||||||
|
<p className="text-red-500">You don't have permission to access this page.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading && companies.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="text-center py-10">
|
||||||
|
<p className="text-gray-500">Loading companies...</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="mb-6 flex justify-between items-center">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-semibold text-gray-900">Companies</h1>
|
||||||
|
<p className="mt-1 text-sm text-gray-500">
|
||||||
|
Manage companies in the system
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleAddCompany}
|
||||||
|
className="btn-primary"
|
||||||
|
>
|
||||||
|
Add Company
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="bg-red-50 border-l-4 border-red-500 p-4 mb-4">
|
||||||
|
<div className="flex">
|
||||||
|
<div className="ml-3">
|
||||||
|
<p className="text-sm text-red-700">{error}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showForm ? (
|
||||||
|
<CompanyForm
|
||||||
|
company={currentCompany}
|
||||||
|
onSubmit={handleFormSubmit}
|
||||||
|
onCancel={handleFormCancel}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="bg-white shadow overflow-hidden sm:rounded-md">
|
||||||
|
{companies.length === 0 ? (
|
||||||
|
<div className="text-center py-10">
|
||||||
|
<p className="text-gray-500">No companies found. Add your first company!</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul className="divide-y divide-gray-200">
|
||||||
|
{companies.map((company) => (
|
||||||
|
<li key={company._id}>
|
||||||
|
<div className="px-4 py-4 sm:px-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<p className="text-sm font-medium text-blue-600 truncate">{company.name}</p>
|
||||||
|
<p className="text-sm text-gray-500">
|
||||||
|
Created: {new Date(company.createdAt).toLocaleDateString()}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<button
|
||||||
|
onClick={() => handleEditCompany(company)}
|
||||||
|
className="btn-secondary text-xs"
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDeleteCompany(company._id)}
|
||||||
|
className="btn-danger text-xs"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
87
frontend/src/pages/companies/CompanyForm.jsx
Normal file
87
frontend/src/pages/companies/CompanyForm.jsx
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
|
||||||
|
export default function CompanyForm({ company, onSubmit, onCancel }) {
|
||||||
|
const [formData, setFormData] = useState({
|
||||||
|
name: ''
|
||||||
|
});
|
||||||
|
const [errors, setErrors] = useState({});
|
||||||
|
|
||||||
|
// If editing, populate form with company data
|
||||||
|
useEffect(() => {
|
||||||
|
if (company) {
|
||||||
|
setFormData({
|
||||||
|
name: company.name || ''
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [company]);
|
||||||
|
|
||||||
|
const handleChange = (e) => {
|
||||||
|
const { name, value } = e.target;
|
||||||
|
setFormData({
|
||||||
|
...formData,
|
||||||
|
[name]: value
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const validateForm = () => {
|
||||||
|
const newErrors = {};
|
||||||
|
|
||||||
|
if (!formData.name.trim()) {
|
||||||
|
newErrors.name = 'Company name is required';
|
||||||
|
}
|
||||||
|
|
||||||
|
setErrors(newErrors);
|
||||||
|
return Object.keys(newErrors).length === 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
if (validateForm()) {
|
||||||
|
onSubmit(formData);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bg-white shadow sm:rounded-lg p-6">
|
||||||
|
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||||
|
{company ? 'Edit Company' : 'Add New Company'}
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<label htmlFor="name" className="block text-sm font-medium text-gray-700">
|
||||||
|
Company Name
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
name="name"
|
||||||
|
id="name"
|
||||||
|
value={formData.name}
|
||||||
|
onChange={handleChange}
|
||||||
|
className={`mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
|
||||||
|
errors.name ? 'border-red-300' : ''
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
{errors.name && <p className="mt-1 text-sm text-red-600">{errors.name}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end space-x-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onCancel}
|
||||||
|
className="btn-secondary"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="btn-primary"
|
||||||
|
>
|
||||||
|
{company ? 'Update Company' : 'Add Company'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
204
frontend/src/pages/dashboard/Dashboard.jsx
Normal file
204
frontend/src/pages/dashboard/Dashboard.jsx
Normal file
@ -0,0 +1,204 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
import axios from 'axios';
|
||||||
|
import { useAuth } from '../../contexts/AuthContext';
|
||||||
|
|
||||||
|
export default function Dashboard() {
|
||||||
|
const { currentUser } = useAuth();
|
||||||
|
const [stats, setStats] = useState({
|
||||||
|
products: 0,
|
||||||
|
users: 0
|
||||||
|
});
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchStats = async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
// Ensure token is set in axios headers
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (token) {
|
||||||
|
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch products count
|
||||||
|
const productsRes = await axios.get('/api/products');
|
||||||
|
const productsCount = productsRes.data.count || productsRes.data.data?.length || 0;
|
||||||
|
|
||||||
|
// Fetch users count if superadmin or companyadmin
|
||||||
|
let usersCount = 0;
|
||||||
|
if (['superadmin', 'companyadmin'].includes(currentUser.role)) {
|
||||||
|
const usersRes = await axios.get('/api/users');
|
||||||
|
usersCount = usersRes.data.count || usersRes.data.data?.length || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
setStats({
|
||||||
|
products: productsCount,
|
||||||
|
users: usersCount
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching dashboard stats:', error);
|
||||||
|
setError('Failed to load dashboard data');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (currentUser && currentUser._id) {
|
||||||
|
fetchStats();
|
||||||
|
}
|
||||||
|
}, [currentUser]);
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center min-h-[400px]">
|
||||||
|
<div className="text-center">
|
||||||
|
<svg className="animate-spin h-12 w-12 text-primary-600 mx-auto mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||||
|
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||||
|
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||||
|
</svg>
|
||||||
|
<p className="text-gray-500">Loading dashboard data...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<div className="alert alert-error mx-4 my-6">
|
||||||
|
<svg className="w-5 h-5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
|
||||||
|
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
|
||||||
|
</svg>
|
||||||
|
<span>{error}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="px-4 sm:px-6 lg:px-8 py-8 animate-fadeIn">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="mb-8">
|
||||||
|
<h1 className="text-3xl font-bold text-gray-900">
|
||||||
|
Welcome back, {currentUser.email.split('@')[0]}! 👋
|
||||||
|
</h1>
|
||||||
|
<p className="mt-2 text-gray-600">
|
||||||
|
Here's an overview of your inventory management system
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Stats Grid */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
|
||||||
|
{/* Users Card - only visible to superadmin and companyadmin */}
|
||||||
|
{['superadmin', 'companyadmin'].includes(currentUser.role) && (
|
||||||
|
<div className="bg-gradient-to-br from-green-500 to-green-600 rounded-2xl shadow-xl p-6 text-white transform transition-all duration-300 hover:scale-105">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="text-green-100 text-sm font-medium">Total Users</p>
|
||||||
|
<p className="text-4xl font-bold mt-2">{stats.users}</p>
|
||||||
|
<Link
|
||||||
|
to="/users"
|
||||||
|
className="inline-flex items-center mt-4 text-sm font-medium text-green-100 hover:text-white transition-colors"
|
||||||
|
>
|
||||||
|
Manage users
|
||||||
|
<svg className="ml-2 w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||||
|
</svg>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
<div className="bg-white/20 p-4 rounded-xl">
|
||||||
|
<svg className="h-12 w-12 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Products Card */}
|
||||||
|
<div className={`bg-gradient-to-br from-purple-500 to-purple-600 rounded-2xl shadow-xl p-6 text-white transform transition-all duration-300 hover:scale-105 ${!['superadmin', 'companyadmin'].includes(currentUser.role) ? 'md:col-span-2' : ''}`}>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="text-purple-100 text-sm font-medium">Total Products</p>
|
||||||
|
<p className="text-4xl font-bold mt-2">{stats.products}</p>
|
||||||
|
<Link
|
||||||
|
to="/products"
|
||||||
|
className="inline-flex items-center mt-4 text-sm font-medium text-purple-100 hover:text-white transition-colors"
|
||||||
|
>
|
||||||
|
Manage products
|
||||||
|
<svg className="ml-2 w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||||
|
</svg>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
<div className="bg-white/20 p-4 rounded-xl">
|
||||||
|
<svg className="h-12 w-12 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Quick Actions */}
|
||||||
|
<div className="card">
|
||||||
|
<div className="card-header">
|
||||||
|
<h2 className="text-lg font-semibold text-gray-900">Quick Actions</h2>
|
||||||
|
</div>
|
||||||
|
<div className="card-body">
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
|
<Link
|
||||||
|
to="/products"
|
||||||
|
className="flex items-center p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors group"
|
||||||
|
>
|
||||||
|
<div className="bg-primary-100 p-3 rounded-lg group-hover:bg-primary-200 transition-colors">
|
||||||
|
<svg className="h-6 w-6 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div className="ml-4">
|
||||||
|
<p className="text-sm font-medium text-gray-900">Add Product</p>
|
||||||
|
<p className="text-xs text-gray-500">Create a new inventory item</p>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
{['superadmin', 'companyadmin'].includes(currentUser.role) && (
|
||||||
|
<Link
|
||||||
|
to="/users"
|
||||||
|
className="flex items-center p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors group"
|
||||||
|
>
|
||||||
|
<div className="bg-green-100 p-3 rounded-lg group-hover:bg-green-200 transition-colors">
|
||||||
|
<svg className="h-6 w-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div className="ml-4">
|
||||||
|
<p className="text-sm font-medium text-gray-900">Add User</p>
|
||||||
|
<p className="text-xs text-gray-500">Create a new user account</p>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{currentUser.role === 'superadmin' && (
|
||||||
|
<Link
|
||||||
|
to="/companies"
|
||||||
|
className="flex items-center p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors group"
|
||||||
|
>
|
||||||
|
<div className="bg-purple-100 p-3 rounded-lg group-hover:bg-purple-200 transition-colors">
|
||||||
|
<svg className="h-6 w-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div className="ml-4">
|
||||||
|
<p className="text-sm font-medium text-gray-900">Manage Companies</p>
|
||||||
|
<p className="text-xs text-gray-500">View and edit companies</p>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
205
frontend/src/pages/products/ProductForm.jsx
Normal file
205
frontend/src/pages/products/ProductForm.jsx
Normal file
@ -0,0 +1,205 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
|
||||||
|
export default function ProductForm({ product, companies, currentUserRole, currentUserCompanyId, onSubmit, onCancel }) {
|
||||||
|
const [formData, setFormData] = useState({
|
||||||
|
name: '',
|
||||||
|
quantity: 0,
|
||||||
|
description: '',
|
||||||
|
companyId: currentUserRole !== 'superadmin' ? currentUserCompanyId : ''
|
||||||
|
});
|
||||||
|
const [errors, setErrors] = useState({});
|
||||||
|
|
||||||
|
// If editing, populate form with product data
|
||||||
|
useEffect(() => {
|
||||||
|
if (product) {
|
||||||
|
setFormData({
|
||||||
|
name: product.name || '',
|
||||||
|
quantity: product.quantity || 0,
|
||||||
|
description: product.description || '',
|
||||||
|
companyId: typeof product.companyId === 'object' ? product.companyId._id : product.companyId
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// For new products, set the companyId based on user role
|
||||||
|
setFormData(prev => ({
|
||||||
|
...prev,
|
||||||
|
companyId: currentUserRole !== 'superadmin' ? currentUserCompanyId : ''
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}, [product, currentUserRole, currentUserCompanyId]);
|
||||||
|
|
||||||
|
const handleChange = (e) => {
|
||||||
|
const { name, value } = e.target;
|
||||||
|
setFormData({
|
||||||
|
...formData,
|
||||||
|
[name]: name === 'quantity' ? parseInt(value, 10) || 0 : value
|
||||||
|
});
|
||||||
|
|
||||||
|
// Clear error for the field being edited
|
||||||
|
if (errors[name]) {
|
||||||
|
setErrors({
|
||||||
|
...errors,
|
||||||
|
[name]: ''
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const validateForm = () => {
|
||||||
|
const newErrors = {};
|
||||||
|
|
||||||
|
if (!formData.name.trim()) {
|
||||||
|
newErrors.name = 'Product name is required';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (formData.quantity < 0) {
|
||||||
|
newErrors.quantity = 'Quantity cannot be negative';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!formData.description.trim()) {
|
||||||
|
newErrors.description = 'Description is required';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!formData.companyId) {
|
||||||
|
newErrors.companyId = 'Company is required';
|
||||||
|
}
|
||||||
|
|
||||||
|
setErrors(newErrors);
|
||||||
|
return Object.keys(newErrors).length === 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
if (validateForm()) {
|
||||||
|
onSubmit(formData);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="card">
|
||||||
|
<div className="card-header">
|
||||||
|
<h2 className="text-xl font-semibold text-gray-900">
|
||||||
|
{product ? 'Edit Product' : 'Add New Product'}
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="card-body space-y-6">
|
||||||
|
<div>
|
||||||
|
<label htmlFor="name" className="form-label">
|
||||||
|
Product Name <span className="text-danger-500">*</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
name="name"
|
||||||
|
id="name"
|
||||||
|
value={formData.name}
|
||||||
|
onChange={handleChange}
|
||||||
|
className={`form-input ${errors.name ? 'border-danger-500 focus:ring-danger-500 focus:border-danger-500' : ''}`}
|
||||||
|
placeholder="Enter product name"
|
||||||
|
/>
|
||||||
|
{errors.name && (
|
||||||
|
<p className="form-error">
|
||||||
|
<svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
|
||||||
|
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
|
||||||
|
</svg>
|
||||||
|
{errors.name}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="quantity" className="form-label">
|
||||||
|
Quantity <span className="text-danger-500">*</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
name="quantity"
|
||||||
|
id="quantity"
|
||||||
|
value={formData.quantity}
|
||||||
|
onChange={handleChange}
|
||||||
|
min="0"
|
||||||
|
className={`form-input ${errors.quantity ? 'border-danger-500 focus:ring-danger-500 focus:border-danger-500' : ''}`}
|
||||||
|
placeholder="0"
|
||||||
|
/>
|
||||||
|
{errors.quantity && (
|
||||||
|
<p className="form-error">
|
||||||
|
<svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
|
||||||
|
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
|
||||||
|
</svg>
|
||||||
|
{errors.quantity}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="description" className="form-label">
|
||||||
|
Description <span className="text-danger-500">*</span>
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
name="description"
|
||||||
|
id="description"
|
||||||
|
rows={3}
|
||||||
|
value={formData.description}
|
||||||
|
onChange={handleChange}
|
||||||
|
className={`form-input resize-none ${errors.description ? 'border-danger-500 focus:ring-danger-500 focus:border-danger-500' : ''}`}
|
||||||
|
placeholder="Enter product description"
|
||||||
|
/>
|
||||||
|
{errors.description && (
|
||||||
|
<p className="form-error">
|
||||||
|
<svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
|
||||||
|
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
|
||||||
|
</svg>
|
||||||
|
{errors.description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Company selection - only for superadmin */}
|
||||||
|
{currentUserRole === 'superadmin' && (
|
||||||
|
<div>
|
||||||
|
<label htmlFor="companyId" className="form-label">
|
||||||
|
Company <span className="text-danger-500">*</span>
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
name="companyId"
|
||||||
|
id="companyId"
|
||||||
|
value={formData.companyId}
|
||||||
|
onChange={handleChange}
|
||||||
|
className={`form-input ${errors.companyId ? 'border-danger-500 focus:ring-danger-500 focus:border-danger-500' : ''}`}
|
||||||
|
>
|
||||||
|
<option value="">Select a company</option>
|
||||||
|
{companies.map((company) => (
|
||||||
|
<option key={company._id} value={company._id}>
|
||||||
|
{company.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{errors.companyId && (
|
||||||
|
<p className="form-error">
|
||||||
|
<svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
|
||||||
|
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
|
||||||
|
</svg>
|
||||||
|
{errors.companyId}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex justify-end space-x-3 pt-6 border-t border-gray-200">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onCancel}
|
||||||
|
className="btn btn-secondary"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="btn btn-primary"
|
||||||
|
>
|
||||||
|
{product ? 'Update Product' : 'Add Product'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
274
frontend/src/pages/products/Products.jsx
Normal file
274
frontend/src/pages/products/Products.jsx
Normal file
@ -0,0 +1,274 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import axios from 'axios';
|
||||||
|
import { useAuth } from '../../contexts/AuthContext';
|
||||||
|
import ProductForm from './ProductForm';
|
||||||
|
|
||||||
|
export default function Products() {
|
||||||
|
const { currentUser } = useAuth();
|
||||||
|
const [products, setProducts] = useState([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState(null);
|
||||||
|
const [showForm, setShowForm] = useState(false);
|
||||||
|
const [currentProduct, setCurrentProduct] = useState(null);
|
||||||
|
const [companies, setCompanies] = useState([]);
|
||||||
|
|
||||||
|
// Fetch products when component mounts
|
||||||
|
useEffect(() => {
|
||||||
|
if (currentUser && currentUser._id) {
|
||||||
|
// Ensure axios has the token in its default headers
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (token) {
|
||||||
|
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchProducts();
|
||||||
|
|
||||||
|
// If user is superadmin, fetch companies for filtering
|
||||||
|
if (currentUser.role === 'superadmin') {
|
||||||
|
fetchCompanies();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [currentUser]);
|
||||||
|
|
||||||
|
const fetchProducts = async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const res = await axios.get('/api/products');
|
||||||
|
console.log('Products response:', res.data);
|
||||||
|
|
||||||
|
if (res.data && res.data.data) {
|
||||||
|
setProducts(res.data.data);
|
||||||
|
setError(null);
|
||||||
|
} else {
|
||||||
|
console.error('Unexpected response format:', res.data);
|
||||||
|
setError('Invalid response format from server');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching products:', error);
|
||||||
|
if (error.response?.status === 401) {
|
||||||
|
setError('Authentication failed. Please log in again.');
|
||||||
|
} else {
|
||||||
|
setError(error.response?.data?.message || 'Failed to load products');
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchCompanies = async () => {
|
||||||
|
try {
|
||||||
|
const res = await axios.get('/api/companies');
|
||||||
|
console.log('Companies response:', res.data);
|
||||||
|
|
||||||
|
if (res.data && res.data.data) {
|
||||||
|
setCompanies(res.data.data);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching companies:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddProduct = () => {
|
||||||
|
setCurrentProduct(null);
|
||||||
|
setShowForm(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEditProduct = (product) => {
|
||||||
|
setCurrentProduct(product);
|
||||||
|
setShowForm(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteProduct = async (id) => {
|
||||||
|
if (window.confirm('Are you sure you want to delete this product?')) {
|
||||||
|
try {
|
||||||
|
await axios.delete(`/api/products/${id}`);
|
||||||
|
setProducts(products.filter(product => product._id !== id));
|
||||||
|
setError(null);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting product:', error);
|
||||||
|
setError(error.response?.data?.message || 'Failed to delete product');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFormSubmit = async (formData) => {
|
||||||
|
try {
|
||||||
|
if (currentProduct) {
|
||||||
|
// Update existing product
|
||||||
|
await axios.put(`/api/products/${currentProduct._id}`, formData);
|
||||||
|
} else {
|
||||||
|
// Create new product
|
||||||
|
await axios.post('/api/products', formData);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh product list
|
||||||
|
fetchProducts();
|
||||||
|
setShowForm(false);
|
||||||
|
setError(null);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving product:', error);
|
||||||
|
setError(error.response?.data?.message || 'Failed to save product');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFormCancel = () => {
|
||||||
|
setShowForm(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check if currentUser exists
|
||||||
|
if (!currentUser || !currentUser.role) {
|
||||||
|
return (
|
||||||
|
<div className="text-center py-10">
|
||||||
|
<p className="text-red-500">Authentication error. Please log in again.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading && products.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center min-h-[400px]">
|
||||||
|
<div className="text-center">
|
||||||
|
<svg className="animate-spin h-12 w-12 text-primary-600 mx-auto mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||||
|
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||||
|
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||||
|
</svg>
|
||||||
|
<p className="text-gray-500">Loading products...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="px-4 sm:px-6 lg:px-8 py-8 animate-fadeIn">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold text-gray-900">Products</h1>
|
||||||
|
<p className="mt-2 text-gray-600">
|
||||||
|
Manage your inventory items and stock levels
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleAddProduct}
|
||||||
|
className="mt-4 sm:mt-0 btn btn-primary"
|
||||||
|
>
|
||||||
|
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||||
|
</svg>
|
||||||
|
Add Product
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="alert alert-error mb-6">
|
||||||
|
<svg className="w-5 h-5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
|
||||||
|
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
|
||||||
|
</svg>
|
||||||
|
<span>{error}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showForm ? (
|
||||||
|
<div className="animate-fadeIn">
|
||||||
|
<ProductForm
|
||||||
|
product={currentProduct}
|
||||||
|
companies={companies}
|
||||||
|
currentUserRole={currentUser.role}
|
||||||
|
currentUserCompanyId={currentUser.companyId}
|
||||||
|
onSubmit={handleFormSubmit}
|
||||||
|
onCancel={handleFormCancel}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="card animate-fadeIn">
|
||||||
|
{products.length === 0 ? (
|
||||||
|
<div className="text-center py-12">
|
||||||
|
<svg className="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
|
||||||
|
</svg>
|
||||||
|
<h3 className="mt-2 text-sm font-medium text-gray-900">No products</h3>
|
||||||
|
<p className="mt-1 text-sm text-gray-500">Get started by creating a new product.</p>
|
||||||
|
<div className="mt-6">
|
||||||
|
<button onClick={handleAddProduct} className="btn btn-primary">
|
||||||
|
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||||
|
</svg>
|
||||||
|
Add Product
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="min-w-full divide-y divide-gray-200">
|
||||||
|
<thead className="bg-gray-50">
|
||||||
|
<tr>
|
||||||
|
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||||
|
Product
|
||||||
|
</th>
|
||||||
|
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||||
|
Quantity
|
||||||
|
</th>
|
||||||
|
{currentUser.role === 'superadmin' && (
|
||||||
|
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||||
|
Company
|
||||||
|
</th>
|
||||||
|
)}
|
||||||
|
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||||
|
Actions
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="bg-white divide-y divide-gray-200">
|
||||||
|
{products.map((product) => (
|
||||||
|
<tr key={product._id} className="hover:bg-gray-50 transition-colors">
|
||||||
|
<td className="px-6 py-4 whitespace-nowrap">
|
||||||
|
<div>
|
||||||
|
<div className="text-sm font-medium text-gray-900">{product.name}</div>
|
||||||
|
{product.description && (
|
||||||
|
<div className="text-sm text-gray-500 max-w-xs truncate">{product.description}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 whitespace-nowrap">
|
||||||
|
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||||
|
product.quantity > 10
|
||||||
|
? 'bg-green-100 text-green-800'
|
||||||
|
: product.quantity > 0
|
||||||
|
? 'bg-yellow-100 text-yellow-800'
|
||||||
|
: 'bg-red-100 text-red-800'
|
||||||
|
}`}>
|
||||||
|
{product.quantity} units
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
{currentUser.role === 'superadmin' && (
|
||||||
|
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||||
|
{product.companyId && typeof product.companyId === 'object' && product.companyId.name
|
||||||
|
? product.companyId.name
|
||||||
|
: '-'}
|
||||||
|
</td>
|
||||||
|
)}
|
||||||
|
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
|
||||||
|
<button
|
||||||
|
onClick={() => handleEditProduct(product)}
|
||||||
|
className="text-primary-600 hover:text-primary-900 mr-3"
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDeleteProduct(product._id)}
|
||||||
|
className="text-danger-600 hover:text-danger-900"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
215
frontend/src/pages/users/UserForm.jsx
Normal file
215
frontend/src/pages/users/UserForm.jsx
Normal file
@ -0,0 +1,215 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import axios from 'axios';
|
||||||
|
|
||||||
|
export default function UserForm({
|
||||||
|
user,
|
||||||
|
companies,
|
||||||
|
currentUserRole,
|
||||||
|
currentUserCompanyId,
|
||||||
|
onSubmit,
|
||||||
|
onCancel
|
||||||
|
}) {
|
||||||
|
const [formData, setFormData] = useState({
|
||||||
|
email: '',
|
||||||
|
password: '',
|
||||||
|
role: currentUserRole === 'superadmin' ? 'companyadmin' : 'employer',
|
||||||
|
companyId: currentUserCompanyId || ''
|
||||||
|
});
|
||||||
|
const [errors, setErrors] = useState({});
|
||||||
|
|
||||||
|
// If editing, populate form with user data
|
||||||
|
useEffect(() => {
|
||||||
|
if (user) {
|
||||||
|
setFormData({
|
||||||
|
email: user.email || '',
|
||||||
|
password: '', // Don't populate password field for security
|
||||||
|
role: user.role || '',
|
||||||
|
companyId: user.companyId?._id || user.companyId || ''
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
const handleChange = (e) => {
|
||||||
|
const { name, value } = e.target;
|
||||||
|
setFormData({
|
||||||
|
...formData,
|
||||||
|
[name]: value
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const validateForm = () => {
|
||||||
|
const newErrors = {};
|
||||||
|
|
||||||
|
if (!formData.email.trim()) {
|
||||||
|
newErrors.email = 'Email is required';
|
||||||
|
} else if (!/\S+@\S+\.\S+/.test(formData.email)) {
|
||||||
|
newErrors.email = 'Email is invalid';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user && !formData.password) {
|
||||||
|
newErrors.password = 'Password is required for new users';
|
||||||
|
} else if (!user && formData.password.length < 6) {
|
||||||
|
newErrors.password = 'Password must be at least 6 characters';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!formData.role) {
|
||||||
|
newErrors.role = 'Role is required';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only validate company if role is not superadmin
|
||||||
|
if (formData.role !== 'superadmin' && !formData.companyId) {
|
||||||
|
newErrors.companyId = 'Company is required for non-superadmin users';
|
||||||
|
}
|
||||||
|
|
||||||
|
setErrors(newErrors);
|
||||||
|
return Object.keys(newErrors).length === 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
if (validateForm()) {
|
||||||
|
// If password is empty and editing, remove it from the form data
|
||||||
|
const submitData = {...formData};
|
||||||
|
if (user && !submitData.password) {
|
||||||
|
delete submitData.password;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If role is superadmin, remove companyId
|
||||||
|
if (submitData.role === 'superadmin') {
|
||||||
|
submitData.companyId = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Submitting user form data:', submitData);
|
||||||
|
onSubmit(submitData);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Determine available roles based on current user's role
|
||||||
|
const availableRoles = () => {
|
||||||
|
if (currentUserRole === 'superadmin') {
|
||||||
|
return [
|
||||||
|
{ value: 'superadmin', label: 'Super Admin' },
|
||||||
|
{ value: 'companyadmin', label: 'Company Admin' },
|
||||||
|
{ value: 'employer', label: 'Employer' }
|
||||||
|
];
|
||||||
|
} else if (currentUserRole === 'companyadmin') {
|
||||||
|
return [
|
||||||
|
{ value: 'employer', label: 'Employer' }
|
||||||
|
];
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bg-white shadow sm:rounded-lg p-6">
|
||||||
|
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||||
|
{user ? 'Edit User' : 'Add New User'}
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<label htmlFor="email" className="block text-sm font-medium text-gray-700">
|
||||||
|
Email Address
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
name="email"
|
||||||
|
id="email"
|
||||||
|
value={formData.email}
|
||||||
|
onChange={handleChange}
|
||||||
|
className={`mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
|
||||||
|
errors.email ? 'border-red-300' : ''
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
{errors.email && <p className="mt-1 text-sm text-red-600">{errors.email}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="password" className="block text-sm font-medium text-gray-700">
|
||||||
|
{user ? 'New Password (leave blank to keep current)' : 'Password'}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
name="password"
|
||||||
|
id="password"
|
||||||
|
value={formData.password}
|
||||||
|
onChange={handleChange}
|
||||||
|
className={`mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
|
||||||
|
errors.password ? 'border-red-300' : ''
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
{errors.password && <p className="mt-1 text-sm text-red-600">{errors.password}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="role" className="block text-sm font-medium text-gray-700">
|
||||||
|
Role
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
name="role"
|
||||||
|
id="role"
|
||||||
|
value={formData.role}
|
||||||
|
onChange={handleChange}
|
||||||
|
className={`mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
|
||||||
|
errors.role ? 'border-red-300' : ''
|
||||||
|
}`}
|
||||||
|
disabled={user && currentUserRole === 'companyadmin'}
|
||||||
|
>
|
||||||
|
<option value="">Select a role</option>
|
||||||
|
{availableRoles().map((role) => (
|
||||||
|
<option key={role.value} value={role.value}>
|
||||||
|
{role.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{errors.role && <p className="mt-1 text-sm text-red-600">{errors.role}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Company selection - only for superadmin */}
|
||||||
|
{currentUserRole === 'superadmin' ? (
|
||||||
|
<div>
|
||||||
|
<label htmlFor="companyId" className="block text-sm font-medium text-gray-700">
|
||||||
|
Company
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
name="companyId"
|
||||||
|
id="companyId"
|
||||||
|
value={formData.companyId}
|
||||||
|
onChange={handleChange}
|
||||||
|
className={`mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
|
||||||
|
errors.companyId ? 'border-red-300' : ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<option value="">Select a company</option>
|
||||||
|
{companies.map((company) => (
|
||||||
|
<option key={company._id} value={company._id}>
|
||||||
|
{company.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{errors.companyId && <p className="mt-1 text-sm text-red-600">{errors.companyId}</p>}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<input type="hidden" name="companyId" value={currentUserCompanyId} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex justify-end space-x-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onCancel}
|
||||||
|
className="btn-secondary"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="btn-primary"
|
||||||
|
>
|
||||||
|
{user ? 'Update User' : 'Add User'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
280
frontend/src/pages/users/Users.jsx
Normal file
280
frontend/src/pages/users/Users.jsx
Normal file
@ -0,0 +1,280 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import axios from 'axios';
|
||||||
|
import { useAuth } from '../../contexts/AuthContext';
|
||||||
|
import UserForm from './UserForm';
|
||||||
|
|
||||||
|
export default function Users() {
|
||||||
|
const { currentUser } = useAuth();
|
||||||
|
const [users, setUsers] = useState([]);
|
||||||
|
const [companies, setCompanies] = useState([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState(null);
|
||||||
|
const [showForm, setShowForm] = useState(false);
|
||||||
|
const [currentUser_, setCurrentUser_] = useState(null);
|
||||||
|
|
||||||
|
// Fetch users when component mounts
|
||||||
|
useEffect(() => {
|
||||||
|
if (currentUser && currentUser._id) {
|
||||||
|
console.log('Current user in Users component:', currentUser);
|
||||||
|
// Ensure axios has the token in its default headers
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (token) {
|
||||||
|
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchUsers();
|
||||||
|
|
||||||
|
// If user is superadmin, fetch companies for the user form
|
||||||
|
if (currentUser.role === 'superadmin') {
|
||||||
|
fetchCompanies();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [currentUser]);
|
||||||
|
|
||||||
|
const fetchUsers = async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
// Ensure token is set in axios headers
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (token) {
|
||||||
|
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Fetching users with token:', token ? `${token.substring(0, 15)}...` : 'No token');
|
||||||
|
const res = await axios.get('/api/users');
|
||||||
|
console.log('Users response:', res.data);
|
||||||
|
|
||||||
|
if (res.data && res.data.data) {
|
||||||
|
setUsers(res.data.data);
|
||||||
|
setError(null);
|
||||||
|
} else {
|
||||||
|
console.error('Unexpected response format:', res.data);
|
||||||
|
setError('Invalid response format from server');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching users:', error);
|
||||||
|
if (error.response?.status === 401) {
|
||||||
|
setError('Authentication failed. Please log in again.');
|
||||||
|
} else {
|
||||||
|
setError(error.response?.data?.message || 'Failed to load users');
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchCompanies = async () => {
|
||||||
|
try {
|
||||||
|
// Ensure token is set in axios headers
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (token) {
|
||||||
|
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Fetching companies...');
|
||||||
|
const res = await axios.get('/api/companies');
|
||||||
|
console.log('Companies response:', res.data);
|
||||||
|
|
||||||
|
if (res.data && res.data.data) {
|
||||||
|
setCompanies(res.data.data);
|
||||||
|
} else {
|
||||||
|
console.error('Unexpected companies response format:', res.data);
|
||||||
|
setError('Invalid companies response format from server');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching companies:', error);
|
||||||
|
setError(error.response?.data?.message || 'Failed to load companies');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddUser = () => {
|
||||||
|
setCurrentUser_(null);
|
||||||
|
setShowForm(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEditUser = (user) => {
|
||||||
|
setCurrentUser_(user);
|
||||||
|
setShowForm(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteUser = async (id) => {
|
||||||
|
if (window.confirm('Are you sure you want to delete this user?')) {
|
||||||
|
try {
|
||||||
|
await axios.delete(`/api/users/${id}`);
|
||||||
|
setUsers(users.filter(user => user._id !== id));
|
||||||
|
setError(null);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting user:', error);
|
||||||
|
setError(error.response?.data?.message || 'Failed to delete user');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleResetPassword = async (id) => {
|
||||||
|
const newPassword = prompt('Enter new password (minimum 6 characters):');
|
||||||
|
|
||||||
|
if (newPassword && newPassword.length >= 6) {
|
||||||
|
try {
|
||||||
|
await axios.put(`/api/users/${id}/reset-password`, { newPassword });
|
||||||
|
alert('Password reset successful');
|
||||||
|
setError(null);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error resetting password:', error);
|
||||||
|
setError(error.response?.data?.message || 'Failed to reset password');
|
||||||
|
}
|
||||||
|
} else if (newPassword) {
|
||||||
|
alert('Password must be at least 6 characters');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFormSubmit = async (formData) => {
|
||||||
|
try {
|
||||||
|
if (currentUser_) {
|
||||||
|
// Update existing user
|
||||||
|
const response = await axios.put(`/api/users/${currentUser_._id}`, formData);
|
||||||
|
console.log('User updated:', response.data);
|
||||||
|
} else {
|
||||||
|
// Create new user
|
||||||
|
const response = await axios.post('/api/users', formData);
|
||||||
|
console.log('User created:', response.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh user list
|
||||||
|
fetchUsers();
|
||||||
|
setShowForm(false);
|
||||||
|
setError(null);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving user:', error);
|
||||||
|
if (error.response?.data?.message) {
|
||||||
|
setError(error.response.data.message);
|
||||||
|
} else if (error.response?.data?.errors && error.response.data.errors.length > 0) {
|
||||||
|
setError(error.response.data.errors.map(err => err.msg).join(', '));
|
||||||
|
} else {
|
||||||
|
setError('Failed to save user');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFormCancel = () => {
|
||||||
|
setShowForm(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check if currentUser exists and has a role property
|
||||||
|
if (!currentUser || !currentUser.role) {
|
||||||
|
return (
|
||||||
|
<div className="text-center py-10">
|
||||||
|
<p className="text-red-500">Authentication error. Please log in again.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only superadmin and companyadmin can access this page
|
||||||
|
if (!['superadmin', 'companyadmin'].includes(currentUser.role)) {
|
||||||
|
return (
|
||||||
|
<div className="text-center py-10">
|
||||||
|
<p className="text-red-500">You don't have permission to access this page.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading && users.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="text-center py-10">
|
||||||
|
<p className="text-gray-500">Loading users...</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="mb-6 flex justify-between items-center">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-semibold text-gray-900">Users</h1>
|
||||||
|
<p className="mt-1 text-sm text-gray-500">
|
||||||
|
Manage users in the system
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleAddUser}
|
||||||
|
className="btn-primary"
|
||||||
|
>
|
||||||
|
Add User
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="bg-red-50 border-l-4 border-red-500 p-4 mb-4">
|
||||||
|
<div className="flex">
|
||||||
|
<div className="ml-3">
|
||||||
|
<p className="text-sm text-red-700">{error}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showForm ? (
|
||||||
|
<UserForm
|
||||||
|
user={currentUser_}
|
||||||
|
companies={companies}
|
||||||
|
currentUserRole={currentUser.role}
|
||||||
|
currentUserCompanyId={currentUser.companyId}
|
||||||
|
onSubmit={handleFormSubmit}
|
||||||
|
onCancel={handleFormCancel}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="bg-white shadow overflow-hidden sm:rounded-md">
|
||||||
|
{users.length === 0 ? (
|
||||||
|
<div className="text-center py-10">
|
||||||
|
<p className="text-gray-500">No users found. Add your first user!</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul className="divide-y divide-gray-200">
|
||||||
|
{users.map((user) => (
|
||||||
|
<li key={user._id}>
|
||||||
|
<div className="px-4 py-4 sm:px-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<p className="text-sm font-medium text-blue-600 truncate">{user.email}</p>
|
||||||
|
<div className="flex space-x-2 mt-1">
|
||||||
|
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
|
||||||
|
{user.role}
|
||||||
|
</span>
|
||||||
|
{user.companyId && (
|
||||||
|
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
|
||||||
|
{typeof user.companyId === 'object' ? user.companyId.name : 'Company ID: ' + user.companyId}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<button
|
||||||
|
onClick={() => handleResetPassword(user._id)}
|
||||||
|
className="text-xs px-3 py-1 bg-yellow-100 text-yellow-800 rounded-md hover:bg-yellow-200"
|
||||||
|
>
|
||||||
|
Reset Password
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleEditUser(user)}
|
||||||
|
className="btn-secondary text-xs"
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDeleteUser(user._id)}
|
||||||
|
className="btn-danger text-xs"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
74
frontend/src/styles/global.css
Normal file
74
frontend/src/styles/global.css
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
/* Tailwind CSS directives */
|
||||||
|
@tailwind base;
|
||||||
|
@tailwind components;
|
||||||
|
@tailwind utilities;
|
||||||
|
|
||||||
|
/* Global styles */
|
||||||
|
body {
|
||||||
|
min-height: 100vh;
|
||||||
|
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Button styles */
|
||||||
|
@layer components {
|
||||||
|
.btn-primary {
|
||||||
|
@apply px-4 py-2 bg-blue-600 text-white font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
@apply px-4 py-2 bg-gray-200 text-gray-800 font-medium rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
@apply px-4 py-2 bg-red-600 text-white font-medium rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 transition-colors;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Layout styles */
|
||||||
|
@layer components {
|
||||||
|
.container {
|
||||||
|
@apply mx-auto px-4 sm:px-6 lg:px-8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
@apply bg-white shadow rounded-lg p-6;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Form styles */
|
||||||
|
@layer components {
|
||||||
|
.form-input {
|
||||||
|
@apply mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-label {
|
||||||
|
@apply block text-sm font-medium text-gray-700;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Table styles */
|
||||||
|
@layer components {
|
||||||
|
.table {
|
||||||
|
@apply min-w-full divide-y divide-gray-200;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-header {
|
||||||
|
@apply bg-gray-50;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-row {
|
||||||
|
@apply bg-white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-row:nth-child(even) {
|
||||||
|
@apply bg-gray-50;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-cell {
|
||||||
|
@apply px-6 py-4 whitespace-nowrap text-sm text-gray-500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-cell-header {
|
||||||
|
@apply px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider;
|
||||||
|
}
|
||||||
|
}
|
68
frontend/src/utils/apiTest.js
Normal file
68
frontend/src/utils/apiTest.js
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
import axios from 'axios';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utility functions to test API connectivity
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Test health endpoint
|
||||||
|
export const testHealthEndpoint = async () => {
|
||||||
|
try {
|
||||||
|
const response = await axios.get('/health');
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: response.data,
|
||||||
|
status: response.status
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Health endpoint error:', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error.response ? error.response.data : error.message,
|
||||||
|
status: error.response ? error.response.status : 500
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Test API authentication
|
||||||
|
export const testAuthEndpoint = async (credentials = { email: 'test@example.com', password: 'password123' }) => {
|
||||||
|
try {
|
||||||
|
const response = await axios.post('/api/auth/login', credentials);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: response.data,
|
||||||
|
status: response.status
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Auth endpoint error:', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error.response ? error.response.data : error.message,
|
||||||
|
status: error.response ? error.response.status : 500
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Test API products endpoint
|
||||||
|
export const testProductsEndpoint = async (token) => {
|
||||||
|
try {
|
||||||
|
const config = token ? {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`
|
||||||
|
}
|
||||||
|
} : {};
|
||||||
|
|
||||||
|
const response = await axios.get('/api/products', config);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: response.data,
|
||||||
|
status: response.status
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Products endpoint error:', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error.response ? error.response.data : error.message,
|
||||||
|
status: error.response ? error.response.status : 500
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
64
frontend/tailwind.config.js
Normal file
64
frontend/tailwind.config.js
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
export default {
|
||||||
|
content: [
|
||||||
|
"./index.html",
|
||||||
|
"./src/**/*.{js,ts,jsx,tsx}",
|
||||||
|
],
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
primary: {
|
||||||
|
50: '#eff6ff',
|
||||||
|
100: '#dbeafe',
|
||||||
|
200: '#bfdbfe',
|
||||||
|
300: '#93bbfd',
|
||||||
|
400: '#60a5fa',
|
||||||
|
500: '#3b82f6',
|
||||||
|
600: '#2563eb',
|
||||||
|
700: '#1d4ed8',
|
||||||
|
800: '#1e40af',
|
||||||
|
900: '#1e3a8a',
|
||||||
|
},
|
||||||
|
success: {
|
||||||
|
50: '#f0fdf4',
|
||||||
|
100: '#dcfce7',
|
||||||
|
200: '#bbf7d0',
|
||||||
|
300: '#86efac',
|
||||||
|
400: '#4ade80',
|
||||||
|
500: '#22c55e',
|
||||||
|
600: '#16a34a',
|
||||||
|
700: '#15803d',
|
||||||
|
800: '#166534',
|
||||||
|
900: '#14532d',
|
||||||
|
},
|
||||||
|
danger: {
|
||||||
|
50: '#fef2f2',
|
||||||
|
100: '#fee2e2',
|
||||||
|
200: '#fecaca',
|
||||||
|
300: '#fca5a5',
|
||||||
|
400: '#f87171',
|
||||||
|
500: '#ef4444',
|
||||||
|
600: '#dc2626',
|
||||||
|
700: '#b91c1c',
|
||||||
|
800: '#991b1b',
|
||||||
|
900: '#7f1d1d',
|
||||||
|
},
|
||||||
|
warning: {
|
||||||
|
50: '#fffbeb',
|
||||||
|
100: '#fef3c7',
|
||||||
|
200: '#fde68a',
|
||||||
|
300: '#fcd34d',
|
||||||
|
400: '#fbbf24',
|
||||||
|
500: '#f59e0b',
|
||||||
|
600: '#d97706',
|
||||||
|
700: '#b45309',
|
||||||
|
800: '#92400e',
|
||||||
|
900: '#78350f',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [
|
||||||
|
require('@tailwindcss/forms'),
|
||||||
|
],
|
||||||
|
}
|
21
frontend/vite.config.js
Normal file
21
frontend/vite.config.js
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
|
// https://vite.dev/config/
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
css: {
|
||||||
|
// Enable CSS modules for all CSS files
|
||||||
|
modules: {
|
||||||
|
localsConvention: 'camelCase',
|
||||||
|
},
|
||||||
|
// Ensure postcss processes CSS correctly
|
||||||
|
postcss: './postcss.config.js',
|
||||||
|
},
|
||||||
|
// Ensure assets are properly served
|
||||||
|
build: {
|
||||||
|
assetsDir: 'assets',
|
||||||
|
cssCodeSplit: true,
|
||||||
|
sourcemap: true,
|
||||||
|
},
|
||||||
|
})
|
7
nginx/Dockerfile
Normal file
7
nginx/Dockerfile
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
FROM nginx:alpine
|
||||||
|
|
||||||
|
COPY default.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80 443
|
||||||
|
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
83
nginx/default.conf
Normal file
83
nginx/default.conf
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
# Local development configuration
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name localhost;
|
||||||
|
|
||||||
|
# Frontend
|
||||||
|
location / {
|
||||||
|
proxy_pass http://frontend:80;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_cache_bypass $http_upgrade;
|
||||||
|
proxy_read_timeout 600s;
|
||||||
|
proxy_connect_timeout 600s;
|
||||||
|
proxy_send_timeout 600s;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Static assets
|
||||||
|
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
|
||||||
|
proxy_pass http://frontend:80;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_cache_bypass $http_upgrade;
|
||||||
|
expires 30d;
|
||||||
|
add_header Cache-Control "public, max-age=2592000";
|
||||||
|
access_log off;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Backend API
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://backend:5000/api/;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_cache_bypass $http_upgrade;
|
||||||
|
proxy_read_timeout 600s;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Also route /auth/ requests to the backend API
|
||||||
|
location /auth/ {
|
||||||
|
proxy_pass http://backend:5000/api/auth/;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_cache_bypass $http_upgrade;
|
||||||
|
proxy_read_timeout 600s;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Route /companies requests to the backend API
|
||||||
|
location /companies/ {
|
||||||
|
proxy_pass http://backend:5000/api/companies/;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_cache_bypass $http_upgrade;
|
||||||
|
proxy_read_timeout 600s;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Health check endpoint
|
||||||
|
location = /health {
|
||||||
|
proxy_pass http://backend:5000/health;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_cache_bypass $http_upgrade;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Note: For production deployment, you'll need to add SSL configuration
|
||||||
|
# See README.md for more information on production deployment
|
290
package-lock.json
generated
Normal file
290
package-lock.json
generated
Normal file
@ -0,0 +1,290 @@
|
|||||||
|
{
|
||||||
|
"name": "ininventer",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"dependencies": {
|
||||||
|
"axios": "^1.9.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/asynckit": {
|
||||||
|
"version": "0.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||||
|
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/axios": {
|
||||||
|
"version": "1.9.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
|
||||||
|
"integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"follow-redirects": "^1.15.6",
|
||||||
|
"form-data": "^4.0.0",
|
||||||
|
"proxy-from-env": "^1.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/call-bind-apply-helpers": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"es-errors": "^1.3.0",
|
||||||
|
"function-bind": "^1.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/combined-stream": {
|
||||||
|
"version": "1.0.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||||
|
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"delayed-stream": "~1.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/delayed-stream": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/dunder-proto": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"call-bind-apply-helpers": "^1.0.1",
|
||||||
|
"es-errors": "^1.3.0",
|
||||||
|
"gopd": "^1.2.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/es-define-property": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/es-errors": {
|
||||||
|
"version": "1.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
|
||||||
|
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/es-object-atoms": {
|
||||||
|
"version": "1.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
|
||||||
|
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"es-errors": "^1.3.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/es-set-tostringtag": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"es-errors": "^1.3.0",
|
||||||
|
"get-intrinsic": "^1.2.6",
|
||||||
|
"has-tostringtag": "^1.0.2",
|
||||||
|
"hasown": "^2.0.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/follow-redirects": {
|
||||||
|
"version": "1.15.9",
|
||||||
|
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
|
||||||
|
"integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "individual",
|
||||||
|
"url": "https://github.com/sponsors/RubenVerborgh"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"debug": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/form-data": {
|
||||||
|
"version": "4.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
|
||||||
|
"integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"asynckit": "^0.4.0",
|
||||||
|
"combined-stream": "^1.0.8",
|
||||||
|
"es-set-tostringtag": "^2.1.0",
|
||||||
|
"mime-types": "^2.1.12"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/function-bind": {
|
||||||
|
"version": "1.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||||
|
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/get-intrinsic": {
|
||||||
|
"version": "1.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||||
|
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"call-bind-apply-helpers": "^1.0.2",
|
||||||
|
"es-define-property": "^1.0.1",
|
||||||
|
"es-errors": "^1.3.0",
|
||||||
|
"es-object-atoms": "^1.1.1",
|
||||||
|
"function-bind": "^1.1.2",
|
||||||
|
"get-proto": "^1.0.1",
|
||||||
|
"gopd": "^1.2.0",
|
||||||
|
"has-symbols": "^1.1.0",
|
||||||
|
"hasown": "^2.0.2",
|
||||||
|
"math-intrinsics": "^1.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/get-proto": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"dunder-proto": "^1.0.1",
|
||||||
|
"es-object-atoms": "^1.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/gopd": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/has-symbols": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/has-tostringtag": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"has-symbols": "^1.0.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/hasown": {
|
||||||
|
"version": "2.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
|
||||||
|
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"function-bind": "^1.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/math-intrinsics": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/mime-db": {
|
||||||
|
"version": "1.52.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
||||||
|
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/mime-types": {
|
||||||
|
"version": "2.1.35",
|
||||||
|
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
|
||||||
|
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"mime-db": "1.52.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/proxy-from-env": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
|
||||||
|
"license": "MIT"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
5
package.json
Normal file
5
package.json
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"dependencies": {
|
||||||
|
"axios": "^1.9.0"
|
||||||
|
}
|
||||||
|
}
|
71
quick-deploy.sh
Executable file
71
quick-deploy.sh
Executable file
@ -0,0 +1,71 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Quick Deploy Script for InInventer
|
||||||
|
# This script uploads files and provides deployment commands
|
||||||
|
|
||||||
|
SERVER_IP="172.104.242.160"
|
||||||
|
SERVER_USER="root"
|
||||||
|
|
||||||
|
echo "======================================"
|
||||||
|
echo "InInventer Quick Deploy"
|
||||||
|
echo "======================================"
|
||||||
|
echo ""
|
||||||
|
echo "This script will:"
|
||||||
|
echo "1. Create deployment package"
|
||||||
|
echo "2. Upload files to your server"
|
||||||
|
echo "3. Provide deployment commands"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Create deployment package
|
||||||
|
echo "Creating deployment package..."
|
||||||
|
tar -czf ininventer-deploy.tar.gz \
|
||||||
|
--exclude='node_modules' \
|
||||||
|
--exclude='.git' \
|
||||||
|
--exclude='*.log' \
|
||||||
|
--exclude='.env' \
|
||||||
|
--exclude='docker-compose.override.yml' \
|
||||||
|
--exclude='ininventer-deploy.tar.gz' \
|
||||||
|
backend/ frontend/ nginx/ \
|
||||||
|
docker-compose.yml deploy.sh \
|
||||||
|
start-production.sh backup.sh DEPLOYMENT.md
|
||||||
|
|
||||||
|
echo "Package created: $(ls -lh ininventer-deploy.tar.gz | awk '{print $5}')"
|
||||||
|
|
||||||
|
# Upload files
|
||||||
|
echo ""
|
||||||
|
echo "Uploading files to server..."
|
||||||
|
echo "You will be prompted for the server password..."
|
||||||
|
|
||||||
|
# Create remote directory first
|
||||||
|
ssh ${SERVER_USER}@${SERVER_IP} "mkdir -p /tmp/ininventer-deploy"
|
||||||
|
|
||||||
|
# Upload all files
|
||||||
|
scp ininventer-deploy.tar.gz deploy.sh start-production.sh backup.sh ${SERVER_USER}@${SERVER_IP}:/tmp/ininventer-deploy/
|
||||||
|
|
||||||
|
if [ $? -eq 0 ]; then
|
||||||
|
echo ""
|
||||||
|
echo "✅ Files uploaded successfully!"
|
||||||
|
echo ""
|
||||||
|
echo "======================================"
|
||||||
|
echo "Now connect to your server and run:"
|
||||||
|
echo "======================================"
|
||||||
|
echo ""
|
||||||
|
echo "ssh ${SERVER_USER}@${SERVER_IP}"
|
||||||
|
echo ""
|
||||||
|
echo "# Once connected, run these commands:"
|
||||||
|
echo "cd /tmp/ininventer-deploy"
|
||||||
|
echo "chmod +x deploy.sh"
|
||||||
|
echo "./deploy.sh"
|
||||||
|
echo ""
|
||||||
|
echo "# After deploy.sh completes:"
|
||||||
|
echo "cd /opt/ininventer"
|
||||||
|
echo "tar -xzf /tmp/ininventer-deploy/ininventer-deploy.tar.gz"
|
||||||
|
echo "cp /tmp/ininventer-deploy/*.sh ."
|
||||||
|
echo "chmod +x *.sh"
|
||||||
|
echo "./start-production.sh"
|
||||||
|
echo ""
|
||||||
|
echo "======================================"
|
||||||
|
else
|
||||||
|
echo ""
|
||||||
|
echo "❌ Upload failed. Please check your connection and try again."
|
||||||
|
fi
|
38
server-setup.sh
Executable file
38
server-setup.sh
Executable file
@ -0,0 +1,38 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Server setup script for InInventer on Debian 12
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Update system
|
||||||
|
echo "Updating system packages..."
|
||||||
|
apt-get update
|
||||||
|
apt-get upgrade -y
|
||||||
|
|
||||||
|
# Install Docker
|
||||||
|
echo "Installing Docker..."
|
||||||
|
curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
|
||||||
|
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian bookworm stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y docker-ce docker-ce-cli containerd.io
|
||||||
|
systemctl enable docker
|
||||||
|
systemctl start docker
|
||||||
|
|
||||||
|
# Install Docker Compose
|
||||||
|
echo "Installing Docker Compose..."
|
||||||
|
curl -L "https://github.com/docker/compose/releases/download/v2.20.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
|
||||||
|
chmod +x /usr/local/bin/docker-compose
|
||||||
|
|
||||||
|
# Configure firewall
|
||||||
|
echo "Configuring firewall..."
|
||||||
|
apt-get install -y ufw
|
||||||
|
ufw allow 22/tcp
|
||||||
|
ufw allow 80/tcp
|
||||||
|
ufw allow 443/tcp
|
||||||
|
ufw --force enable
|
||||||
|
|
||||||
|
# Create application directory
|
||||||
|
echo "Creating application directory..."
|
||||||
|
mkdir -p /opt/ininventer
|
||||||
|
|
||||||
|
echo "Server setup complete!"
|
||||||
|
echo "Next, transfer your application files to /opt/ininventer and run the deployment script."
|
91
setup.sh
Executable file
91
setup.sh
Executable file
@ -0,0 +1,91 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# InInventer Setup Script
|
||||||
|
# This script helps set up the development environment
|
||||||
|
|
||||||
|
echo "==================================="
|
||||||
|
echo "InInventer Development Setup"
|
||||||
|
echo "==================================="
|
||||||
|
|
||||||
|
# Check if Docker is installed
|
||||||
|
if ! command -v docker &> /dev/null; then
|
||||||
|
echo "❌ Docker is not installed. Please install Docker first."
|
||||||
|
echo "Visit: https://docs.docker.com/get-docker/"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Check if Docker Compose is installed
|
||||||
|
if ! command -v docker-compose &> /dev/null; then
|
||||||
|
echo "❌ Docker Compose is not installed. Please install Docker Compose first."
|
||||||
|
echo "Visit: https://docs.docker.com/compose/install/"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "✅ Docker and Docker Compose are installed"
|
||||||
|
|
||||||
|
# Create .env file if it doesn't exist
|
||||||
|
if [ ! -f .env ]; then
|
||||||
|
echo ""
|
||||||
|
echo "Creating .env file from template..."
|
||||||
|
cp .env.example .env
|
||||||
|
echo "✅ Created .env file"
|
||||||
|
echo ""
|
||||||
|
echo "⚠️ IMPORTANT: Edit .env file and update the following:"
|
||||||
|
echo " - MONGO_INITDB_ROOT_USERNAME"
|
||||||
|
echo " - MONGO_INITDB_ROOT_PASSWORD"
|
||||||
|
echo " - JWT_SECRET (use: openssl rand -base64 64)"
|
||||||
|
echo " - SUPERADMIN_EMAIL"
|
||||||
|
echo " - SUPERADMIN_PASSWORD"
|
||||||
|
echo ""
|
||||||
|
read -p "Press Enter after you've updated .env file..."
|
||||||
|
else
|
||||||
|
echo "✅ .env file already exists"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create frontend .env if it doesn't exist
|
||||||
|
if [ ! -f frontend/.env ]; then
|
||||||
|
echo "Creating frontend/.env file..."
|
||||||
|
cp frontend/.env.example frontend/.env
|
||||||
|
echo "✅ Created frontend/.env file"
|
||||||
|
else
|
||||||
|
echo "✅ frontend/.env file already exists"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Pull Docker images
|
||||||
|
echo ""
|
||||||
|
echo "Pulling Docker images..."
|
||||||
|
docker-compose pull
|
||||||
|
|
||||||
|
# Start services
|
||||||
|
echo ""
|
||||||
|
echo "Starting services..."
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# Wait for services to be ready
|
||||||
|
echo ""
|
||||||
|
echo "Waiting for services to start..."
|
||||||
|
sleep 10
|
||||||
|
|
||||||
|
# Check if services are running
|
||||||
|
if docker-compose ps | grep -q "Up"; then
|
||||||
|
echo ""
|
||||||
|
echo "==================================="
|
||||||
|
echo "✅ Setup Complete!"
|
||||||
|
echo "==================================="
|
||||||
|
echo ""
|
||||||
|
echo "Access the application at:"
|
||||||
|
echo " - Frontend: http://localhost:3000"
|
||||||
|
echo " - Backend API: http://localhost:5000"
|
||||||
|
echo " - MongoDB: localhost:27017"
|
||||||
|
echo ""
|
||||||
|
echo "Login with the credentials you set in .env:"
|
||||||
|
echo " - Email: \$SUPERADMIN_EMAIL"
|
||||||
|
echo " - Password: \$SUPERADMIN_PASSWORD"
|
||||||
|
echo ""
|
||||||
|
echo "To view logs: docker-compose logs -f"
|
||||||
|
echo "To stop: docker-compose down"
|
||||||
|
else
|
||||||
|
echo ""
|
||||||
|
echo "❌ Services failed to start. Check logs with:"
|
||||||
|
echo "docker-compose logs"
|
||||||
|
fi
|
171
start-production.sh
Executable file
171
start-production.sh
Executable file
@ -0,0 +1,171 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# InInventer Production Start Script
|
||||||
|
# This script obtains SSL certificates and starts all services
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Load environment variables
|
||||||
|
source .env.production
|
||||||
|
|
||||||
|
# Color codes
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
RED='\033[0;31m'
|
||||||
|
NC='\033[0m'
|
||||||
|
|
||||||
|
print_status() {
|
||||||
|
echo -e "${GREEN}[STATUS]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
print_error() {
|
||||||
|
echo -e "${RED}[ERROR]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
print_warning() {
|
||||||
|
echo -e "${YELLOW}[WARNING]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create required directories
|
||||||
|
print_status "Creating required directories..."
|
||||||
|
mkdir -p certbot/conf
|
||||||
|
mkdir -p certbot/www
|
||||||
|
|
||||||
|
# Start containers with initial configuration
|
||||||
|
print_status "Starting containers with initial configuration..."
|
||||||
|
cp nginx/initial.conf nginx/production.conf
|
||||||
|
docker-compose -f docker-compose.production.yml --env-file .env.production up -d nginx
|
||||||
|
|
||||||
|
# Wait for nginx to be ready
|
||||||
|
print_status "Waiting for Nginx to be ready..."
|
||||||
|
sleep 5
|
||||||
|
|
||||||
|
# Obtain SSL certificates
|
||||||
|
print_status "Obtaining SSL certificates for $DOMAIN_NAME..."
|
||||||
|
docker-compose -f docker-compose.production.yml --env-file .env.production run --rm certbot certonly \
|
||||||
|
--webroot \
|
||||||
|
--webroot-path=/var/www/certbot \
|
||||||
|
--email $EMAIL_FOR_SSL \
|
||||||
|
--agree-tos \
|
||||||
|
--no-eff-email \
|
||||||
|
-d $DOMAIN_NAME
|
||||||
|
|
||||||
|
# Check if certificates were obtained successfully
|
||||||
|
if [ ! -f "./certbot/conf/live/$DOMAIN_NAME/fullchain.pem" ]; then
|
||||||
|
print_error "Failed to obtain SSL certificates!"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
print_status "SSL certificates obtained successfully!"
|
||||||
|
|
||||||
|
# Stop nginx
|
||||||
|
docker-compose -f docker-compose.production.yml --env-file .env.production down
|
||||||
|
|
||||||
|
# Create final Nginx configuration
|
||||||
|
print_status "Creating final Nginx configuration..."
|
||||||
|
cat > nginx/production.conf << EOL
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name $DOMAIN_NAME;
|
||||||
|
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/certbot;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
return 301 https://\$server_name\$request_uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
server_name $DOMAIN_NAME;
|
||||||
|
|
||||||
|
ssl_certificate /etc/letsencrypt/live/$DOMAIN_NAME/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/$DOMAIN_NAME/privkey.pem;
|
||||||
|
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
ssl_prefer_server_ciphers on;
|
||||||
|
|
||||||
|
client_max_body_size 10M;
|
||||||
|
|
||||||
|
# Security headers
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
|
add_header Referrer-Policy "no-referrer-when-downgrade" always;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://frontend:80;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade \$http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_cache_bypass \$http_upgrade;
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /api {
|
||||||
|
proxy_pass http://backend:5000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade \$http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_cache_bypass \$http_upgrade;
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EOL
|
||||||
|
|
||||||
|
# Start all services
|
||||||
|
print_status "Starting all services..."
|
||||||
|
docker-compose -f docker-compose.production.yml --env-file .env.production up -d
|
||||||
|
|
||||||
|
# Wait for services to be ready
|
||||||
|
print_status "Waiting for services to be ready..."
|
||||||
|
sleep 10
|
||||||
|
|
||||||
|
# Check service status
|
||||||
|
print_status "Checking service status..."
|
||||||
|
docker-compose -f docker-compose.production.yml ps
|
||||||
|
|
||||||
|
# Create systemd service
|
||||||
|
print_status "Creating systemd service..."
|
||||||
|
cat > /etc/systemd/system/ininventer.service << EOL
|
||||||
|
[Unit]
|
||||||
|
Description=InInventer Application
|
||||||
|
Requires=docker.service
|
||||||
|
After=docker.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
RemainAfterExit=yes
|
||||||
|
WorkingDirectory=/opt/ininventer
|
||||||
|
ExecStart=/usr/local/bin/docker-compose -f docker-compose.production.yml --env-file .env.production up -d
|
||||||
|
ExecStop=/usr/local/bin/docker-compose -f docker-compose.production.yml down
|
||||||
|
TimeoutStartSec=0
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOL
|
||||||
|
|
||||||
|
# Enable service
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable ininventer.service
|
||||||
|
|
||||||
|
print_status "Deployment complete!"
|
||||||
|
print_status "Your application is now available at: https://$DOMAIN_NAME"
|
||||||
|
print_warning "Default login credentials:"
|
||||||
|
echo " Email: admin@ininventer.com"
|
||||||
|
echo " Password: admin123"
|
||||||
|
print_warning "IMPORTANT: Change the default password immediately after first login!"
|
||||||
|
|
||||||
|
# Show container logs
|
||||||
|
print_status "Recent logs:"
|
||||||
|
docker-compose -f docker-compose.production.yml logs --tail=20
|
27
test-login.js
Normal file
27
test-login.js
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
const axios = require('axios');
|
||||||
|
|
||||||
|
async function testLogin() {
|
||||||
|
try {
|
||||||
|
console.log('Testing login with superadmin credentials...');
|
||||||
|
const response = await axios.post('http://localhost:8080/api/auth/login', {
|
||||||
|
email: 'admin@ininventer.com',
|
||||||
|
password: 'admin123'
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('Login successful!');
|
||||||
|
console.log('Response status:', response.status);
|
||||||
|
console.log('User data:', response.data.user);
|
||||||
|
console.log('Token received:', response.data.token ? 'Yes' : 'No');
|
||||||
|
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Login failed!');
|
||||||
|
console.error('Error status:', error.response?.status);
|
||||||
|
console.error('Error message:', error.response?.data);
|
||||||
|
console.error('Full error:', error.message);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
testLogin();
|
33
transfer.sh
Executable file
33
transfer.sh
Executable file
@ -0,0 +1,33 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Script to package and transfer InInventer to Linode server
|
||||||
|
SERVER_IP="172.104.242.160"
|
||||||
|
SERVER_USER="root"
|
||||||
|
REMOTE_DIR="/opt/ininventer"
|
||||||
|
|
||||||
|
echo "Packaging InInventer project..."
|
||||||
|
# Create a temporary directory for packaging
|
||||||
|
mkdir -p /tmp/ininventer-deploy
|
||||||
|
|
||||||
|
# Copy project files, excluding node_modules, .git, etc.
|
||||||
|
rsync -av --exclude 'node_modules' --exclude '.git' --exclude 'dist' \
|
||||||
|
--exclude '.env.local' --exclude '.env.development' \
|
||||||
|
/home/m3mo/IdeaProjects/ininventer/ /tmp/ininventer-deploy/
|
||||||
|
|
||||||
|
echo "Transferring files to $SERVER_IP..."
|
||||||
|
# Create the remote directory if it doesn't exist
|
||||||
|
ssh $SERVER_USER@$SERVER_IP "mkdir -p $REMOTE_DIR"
|
||||||
|
|
||||||
|
# Transfer files to the server
|
||||||
|
rsync -avz --progress /tmp/ininventer-deploy/ $SERVER_USER@$SERVER_IP:$REMOTE_DIR/
|
||||||
|
|
||||||
|
# Make scripts executable on the remote server
|
||||||
|
ssh $SERVER_USER@$SERVER_IP "chmod +x $REMOTE_DIR/deploy.sh $REMOTE_DIR/start-production.sh"
|
||||||
|
|
||||||
|
echo "Transfer complete!"
|
||||||
|
echo "Next steps:"
|
||||||
|
echo "1. SSH into your server: ssh $SERVER_USER@$SERVER_IP"
|
||||||
|
echo "2. Run the deployment script: cd $REMOTE_DIR && ./deploy.sh"
|
||||||
|
|
||||||
|
# Clean up
|
||||||
|
rm -rf /tmp/ininventer-deploy
|
Loading…
x
Reference in New Issue
Block a user