58 lines
1.6 KiB
JavaScript
58 lines
1.6 KiB
JavaScript
const express = require('express');
|
|
const jwt = require('jsonwebtoken');
|
|
|
|
const app = express();
|
|
app.use(express.json());
|
|
|
|
const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret-ne-koristiti-u-produkciji';
|
|
|
|
const users = [
|
|
{ id: 'u0', username: 'student', password: 'fpmoz2024', name: 'Demo Student', role: 'student' }
|
|
];
|
|
|
|
function authenticate(req, res, next) {
|
|
const authHeader = req.headers.authorization || '';
|
|
const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null;
|
|
|
|
if (!token) {
|
|
return res.status(401).json({ error: 'Missing bearer token' });
|
|
}
|
|
|
|
try {
|
|
req.user = jwt.verify(token, JWT_SECRET);
|
|
return next();
|
|
} catch (error) {
|
|
return res.status(401).json({ error: 'Invalid token' });
|
|
}
|
|
}
|
|
|
|
app.post('/auth/login', (req, res) => {
|
|
const { username, password } = req.body;
|
|
const user = users.find((candidate) => candidate.username === username && candidate.password === password);
|
|
|
|
if (!user) {
|
|
return res.status(401).json({ error: 'Invalid username or password' });
|
|
}
|
|
|
|
const token = jwt.sign(
|
|
{ sub: user.id, username: user.username, role: user.role },
|
|
JWT_SECRET,
|
|
{ algorithm: 'HS256', expiresIn: '15m' }
|
|
);
|
|
|
|
return res.json({ token });
|
|
});
|
|
|
|
app.get('/api/users', authenticate, (req, res) => {
|
|
res.setHeader('X-Served-By', 'users-api');
|
|
return res.json([
|
|
{ id: 'u0', username: 'student', name: 'Demo Student' },
|
|
{ id: 'u1', username: 'student1', name: 'Student Jedan' },
|
|
{ id: 'u2', username: 'student2', name: 'Student Dva' }
|
|
]);
|
|
});
|
|
|
|
app.listen(3001, () => {
|
|
console.log('users-api na portu 3001');
|
|
});
|