forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthenticateMerchant.js
More file actions
31 lines (26 loc) · 985 Bytes
/
Copy pathauthenticateMerchant.js
File metadata and controls
31 lines (26 loc) · 985 Bytes
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
'use strict';
const { createHash } = require('crypto');
const { getMerchantByApiKeyHash } = require('../db/merchantRepository');
/**
* Middleware: validates the merchant API key from the x-api-key header.
* Hashes the provided key and compares against the stored hash.
* Attaches the merchant record to req.merchant on success.
*/
async function authenticateMerchant(req, res, next) {
try {
const apiKey = req.headers['x-api-key'];
if (!apiKey) {
return res.status(401).json({ success: false, error: 'unauthorized', message: 'x-api-key header is required' });
}
const apiKeyHash = createHash('sha256').update(apiKey).digest('hex');
const merchant = await getMerchantByApiKeyHash(apiKeyHash);
if (!merchant) {
return res.status(401).json({ success: false, error: 'unauthorized', message: 'Invalid API key' });
}
req.merchant = merchant;
next();
} catch (err) {
next(err);
}
}
module.exports = { authenticateMerchant };