-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
66 lines (56 loc) · 2.23 KB
/
auth.js
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
56
57
58
59
60
61
62
63
64
65
66
const Authority = require('../models/authority');
const Client = require('../models/client');
const atob = require('atob'); // To decode base64
// Middleware to authenticate client using Basic Auth
async function authClient(req, res, next) {
try {
// Check if the Authorization header is provided
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Basic ')) {
return res.status(401).json({ error: 'Missing or invalid Authorization header' });
}
// Decode the Basic Auth header
const base64Credentials = authHeader.split(' ')[1];
const credentials = atob(base64Credentials).split(':');
const apiKey = credentials[0];
const apiSecret = credentials[1];
if (!apiKey || !apiSecret) {
return res.status(401).json({ error: 'Invalid API credentials' });
}
// Check if the client exists with the given key and secret
const client = await Client.findOne({ key: apiKey, secret: apiSecret }).populate('authority');
if (!client) {
return res.status(401).json({ error: 'Invalid API credentials' });
}
// Check if the Origin header matches the client's origin
const requestOrigin = req.headers.origin;
if (requestOrigin !== client.origin) {
return res.status(403).json({ error: 'Origin not allowed' });
}
// Attach the client to the request object for further use
req.client = {
_id: client._id,
authority: client.authority
};
// Proceed to the next middleware or route handler
next();
} catch (error) {
console.error('Error in authClient middleware:', error);
res.status(500).json({ error: 'An error occurred while authenticating the client' });
}
}
// Middleware to ensure user authentication via session (for different routes)
async function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
const error = new Error("Unauthorized");
error.status = 401;
next(error);
}
}
// Export both functions from the module
module.exports = {
authClient,
ensureAuthenticated
};