forked from github/copilot-cli-for-beginners
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
55 lines (43 loc) · 1.57 KB
/
Copy pathauth.js
File metadata and controls
55 lines (43 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* Authentication API endpoints
*/
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const JWT_SECRET = 'your-secret-key'; // TODO: Move to environment variable
// Login
router.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findByEmail(email);
if (!user || user.password !== password) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = jwt.sign({ userId: user.id }, JWT_SECRET, { expiresIn: '24h' });
res.json({ token, user: { id: user.id, name: user.name, email: user.email } });
});
// Register
router.post('/register', async (req, res) => {
const { name, email, password } = req.body;
const existingUser = await User.findByEmail(email);
if (existingUser) {
return res.status(400).json({ error: 'Email already registered' });
}
const user = await User.create({ name, email, password });
const token = jwt.sign({ userId: user.id }, JWT_SECRET, { expiresIn: '24h' });
res.status(201).json({ token, user: { id: user.id, name: user.name, email: user.email } });
});
// Verify token
router.get('/verify', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
res.json({ valid: true, userId: decoded.userId });
} catch (error) {
res.status(401).json({ error: 'Invalid token' });
}
});
module.exports = router;