feat(auth): implement user authentication system
This commit is contained in:
parent
97116fed1c
commit
4847ab793a
7199 changed files with 38207 additions and 747767 deletions
27
src/app.js
Normal file
27
src/app.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const helmet = require('helmet');
|
||||
const authRoutes = require('./routes/auth');
|
||||
const { authenticateToken } = require('./middleware/auth');
|
||||
|
||||
const app = express();
|
||||
|
||||
// Middleware
|
||||
app.use(helmet());
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
|
||||
// Routes
|
||||
app.use('/api/auth', authRoutes);
|
||||
|
||||
// Protected route example
|
||||
app.get('/api/protected', authenticateToken, (req, res) => {
|
||||
res.json({ message: 'This is a protected route', user: req.user });
|
||||
});
|
||||
|
||||
// Health check
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({ status: 'OK', timestamp: new Date().toISOString() });
|
||||
});
|
||||
|
||||
module.exports = app;
|
||||
9
src/config/index.js
Normal file
9
src/config/index.js
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
// Configuration file
|
||||
require('dotenv').config();
|
||||
|
||||
const config = {
|
||||
JWT_SECRET: process.env.JWT_SECRET || 'default-secret-key-for-development',
|
||||
PORT: process.env.PORT || 3000,
|
||||
};
|
||||
|
||||
module.exports = config;
|
||||
21
src/middleware/auth.js
Normal file
21
src/middleware/auth.js
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
const jwt = require('jsonwebtoken');
|
||||
const { JWT_SECRET } = require('../config');
|
||||
|
||||
const authenticateToken = (req, res, next) => {
|
||||
const authHeader = req.headers['authorization'];
|
||||
const token = authHeader && authHeader.split(' ')[1];
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'Access token required' });
|
||||
}
|
||||
|
||||
jwt.verify(token, JWT_SECRET, (err, user) => {
|
||||
if (err) {
|
||||
return res.status(403).json({ error: 'Invalid or expired token' });
|
||||
}
|
||||
req.user = user;
|
||||
next();
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = { authenticateToken };
|
||||
86
src/routes/auth.js
Normal file
86
src/routes/auth.js
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
const express = require('express');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const bcrypt = require('bcrypt');
|
||||
const { JWT_SECRET } = require('../config');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Mock user database (in production, this would be a real database)
|
||||
const users = [];
|
||||
|
||||
// Register endpoint
|
||||
router.post('/register', async (req, res) => {
|
||||
try {
|
||||
const { username, email, password } = req.body;
|
||||
|
||||
// Check if user already exists
|
||||
const existingUser = users.find(u => u.email === email);
|
||||
if (existingUser) {
|
||||
return res.status(400).json({ error: 'User already exists' });
|
||||
}
|
||||
|
||||
// Hash password
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
|
||||
// Create user
|
||||
const newUser = {
|
||||
id: users.length + 1,
|
||||
username,
|
||||
email,
|
||||
password: hashedPassword
|
||||
};
|
||||
|
||||
users.push(newUser);
|
||||
|
||||
// Generate token
|
||||
const token = jwt.sign(
|
||||
{ id: newUser.id, email: newUser.email },
|
||||
JWT_SECRET,
|
||||
{ expiresIn: '24h' }
|
||||
);
|
||||
|
||||
res.status(201).json({
|
||||
message: 'User registered successfully',
|
||||
token,
|
||||
user: { id: newUser.id, username, email }
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Registration failed' });
|
||||
}
|
||||
});
|
||||
|
||||
// Login endpoint
|
||||
router.post('/login', async (req, res) => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
|
||||
// Find user
|
||||
const user = users.find(u => u.email === email);
|
||||
if (!user) {
|
||||
return res.status(400).json({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
// Check password
|
||||
const isValidPassword = await bcrypt.compare(password, user.password);
|
||||
if (!isValidPassword) {
|
||||
return res.status(400).json({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
// Generate token
|
||||
const token = jwt.sign(
|
||||
{ id: user.id, email: user.email },
|
||||
JWT_SECRET,
|
||||
{ expiresIn: '24h' }
|
||||
);
|
||||
|
||||
res.json({
|
||||
message: 'Login successful',
|
||||
token,
|
||||
user: { id: user.id, username: user.username, email: user.email }
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Login failed' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
8
src/server.js
Normal file
8
src/server.js
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
const app = require('./app');
|
||||
const { PORT } = require('./config');
|
||||
|
||||
const server = app.listen(PORT, () => {
|
||||
console.log(`Server running on port ${PORT}`);
|
||||
});
|
||||
|
||||
module.exports = server;
|
||||
Loading…
Add table
Add a link
Reference in a new issue