-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add API key authentication in CLI
- Loading branch information
1 parent
d2d7638
commit e068efc
Showing
4 changed files
with
180 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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 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 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,28 @@ | ||
const express = require('express'); | ||
const router = express.Router(); | ||
|
||
const VALID_API_KEY = 'my-secret-api-key'; | ||
const VALID_KEY_NAME = 'api-key'; | ||
|
||
const apiKeyAuthMiddleware = (req, res, next) => { | ||
const apiKeyFromHeader = req.headers[VALID_KEY_NAME.toLowerCase()]; | ||
const apiKeyFromQuery = req.query[VALID_KEY_NAME]; | ||
|
||
const apiKey = apiKeyFromHeader || apiKeyFromQuery; | ||
|
||
if (!apiKey) { | ||
return res.status(401).json({ error: 'API key missing' }); | ||
} | ||
|
||
if (apiKey !== VALID_API_KEY) { | ||
return res.status(403).json({ error: 'Invalid API key' }); | ||
} | ||
|
||
next(); | ||
}; | ||
|
||
router.post('/protected', apiKeyAuthMiddleware, (req, res) => { | ||
res.status(200).json({ message: 'You have accessed a protected route!' }); | ||
}); | ||
|
||
module.exports = router; |
This file contains 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