Repository navigation
feat: Add JWT authentication and role-based authorization to APIs #64
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| const jwt = require('jsonwebtoken'); | ||
|
|
||
| // Secret key - in production, use environment variable | ||
| const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production'; | ||
|
|
||
| // Authentication middleware - verifies JWT token | ||
| const authenticate = (req, res, next) => { | ||
| try { | ||
| // Get token from Authorization header | ||
| const authHeader = req.headers.authorization; | ||
|
|
||
| if (!authHeader || !authHeader.startsWith('Bearer ')) { | ||
| return res.status(401).json({ | ||
| error: { | ||
| message: 'No token provided. Please include a Bearer token in Authorization header.' | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| // Extract token (remove 'Bearer ' prefix) | ||
| const token = authHeader.substring(7); | ||
|
|
||
| // Verify token | ||
| const decoded = jwt.verify(token, JWT_SECRET); | ||
|
|
||
| // Attach user info to request object | ||
| req.user = decoded; | ||
| next(); | ||
| } catch (error) { | ||
| if (error.name === 'JsonWebTokenError') { | ||
| return res.status(401).json({ | ||
| error: { | ||
| message: 'Invalid token' | ||
| } | ||
| }); | ||
| } | ||
| if (error.name === 'TokenExpiredError') { | ||
| return res.status(401).json({ | ||
| error: { | ||
| message: 'Token expired' | ||
| } | ||
| }); | ||
| } | ||
| return res.status(500).json({ | ||
| error: { | ||
| message: 'Authentication error' | ||
| } | ||
| }); | ||
| } | ||
| }; | ||
|
|
||
| // Authorization middleware - checks user roles | ||
| const authorize = (...allowedRoles) => { | ||
| return (req, res, next) => { | ||
| if (!req.user) { | ||
| return res.status(401).json({ | ||
| error: { | ||
| message: 'Authentication required' | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| const userRole = req.user.role; | ||
|
|
||
| if (!allowedRoles.includes(userRole)) { | ||
| return res.status(403).json({ | ||
| error: { | ||
| message: 'Access denied. Insufficient permissions.' | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| next(); | ||
| }; | ||
| }; | ||
|
|
||
| module.exports = { authenticate, authorize, JWT_SECRET }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| const express = require('express'); | ||
| const router = express.Router(); | ||
| const jwt = require('jsonwebtoken'); | ||
| const bcrypt = require('bcryptjs'); | ||
| const { JWT_SECRET } = require('../middleware/auth'); | ||
|
|
||
| // In-memory user store (use database in production) | ||
| // Pre-hashed passwords: admin123 and user123 | ||
| const users = [ | ||
| { | ||
| id: 1, | ||
| username: 'admin', | ||
| password: '$2a$10$rOzJqZqZqZqZqZqZqZqZqO', // Will be initialized with actual hash | ||
| role: 'admin' | ||
| }, | ||
| { | ||
| id: 2, | ||
| username: 'user', | ||
| password: '$2a$10$rOzJqZqZqZqZqZqZqZqZqO', // Will be initialized with actual hash | ||
| role: 'user' | ||
| } | ||
| ]; | ||
|
|
||
| // Initialize with hashed passwords (run once on server start) | ||
| async function initializeUsers() { | ||
| for (let user of users) { | ||
| if (user.username === 'admin' && user.password.startsWith('$2a$10$rOzJqZqZqZqZqZqZqZqZqO')) { | ||
| user.password = await bcrypt.hash('admin123', 10); | ||
| } else if (user.username === 'user' && user.password.startsWith('$2a$10$rOzJqZqZqZqZqZqZqZqZqO')) { | ||
| user.password = await bcrypt.hash('user123', 10); | ||
| } | ||
| } | ||
| } | ||
| initializeUsers(); | ||
|
|
||
|
Comment on lines
+27
to
+35
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| // Login endpoint | ||
| router.post('/login', async (req, res) => { | ||
| try { | ||
| const { username, password } = req.body; | ||
|
|
||
| if (!username || !password) { | ||
| return res.status(400).json({ | ||
| error: { | ||
| message: 'Username and password are required' | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| // Find user | ||
| const user = users.find(u => u.username === username); | ||
| if (!user) { | ||
| return res.status(401).json({ | ||
| error: { | ||
| message: 'Invalid credentials' | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| // Verify password | ||
| const isValidPassword = await bcrypt.compare(password, user.password); | ||
| if (!isValidPassword) { | ||
| return res.status(401).json({ | ||
| error: { | ||
| message: 'Invalid credentials' | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| // Generate JWT token | ||
| const token = jwt.sign( | ||
| { | ||
| id: user.id, | ||
| username: user.username, | ||
| role: user.role | ||
| }, | ||
| JWT_SECRET, | ||
| { expiresIn: '24h' } | ||
| ); | ||
|
|
||
| res.status(200).json({ | ||
| message: 'Login successful', | ||
| token: token, | ||
| user: { | ||
| id: user.id, | ||
| username: user.username, | ||
| role: user.role | ||
| } | ||
| }); | ||
| } catch (error) { | ||
| res.status(500).json({ | ||
| error: { | ||
| message: 'Login failed' | ||
| } | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| // Register endpoint | ||
| router.post('/register', async (req, res) => { | ||
| try { | ||
| const { username, password, role = 'user' } = req.body; | ||
|
|
||
| if (!username || !password) { | ||
| return res.status(400).json({ | ||
| error: { | ||
| message: 'Username and password are required' | ||
| } | ||
| }); | ||
| } | ||
|
adminvns marked this conversation as resolved.
|
||
|
|
||
| // Check if user exists | ||
| if (users.find(u => u.username === username)) { | ||
| return res.status(409).json({ | ||
| error: { | ||
| message: 'Username already exists' | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| // Hash password | ||
| const hashedPassword = await bcrypt.hash(password, 10); | ||
|
|
||
| // Create new user | ||
| const newUser = { | ||
| id: users.length + 1, | ||
| username, | ||
| password: hashedPassword, | ||
| role: role || 'user' | ||
| }; | ||
|
|
||
| users.push(newUser); | ||
|
|
||
| // Generate token | ||
| const token = jwt.sign( | ||
| { | ||
| id: newUser.id, | ||
| username: newUser.username, | ||
| role: newUser.role | ||
| }, | ||
| JWT_SECRET, | ||
| { expiresIn: '24h' } | ||
| ); | ||
|
|
||
| res.status(201).json({ | ||
| message: 'User registered successfully', | ||
| token: token, | ||
| user: { | ||
| id: newUser.id, | ||
| username: newUser.username, | ||
| role: newUser.role | ||
| } | ||
| }); | ||
| } catch (error) { | ||
| res.status(500).json({ | ||
| error: { | ||
| message: 'Registration failed' | ||
| } | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| module.exports = router; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please add a default test case for /order where we will just verify the error:
message: 'No token provided. Please include a Bearer token in Authorization header.'