feat: add api-key auth
This commit is contained in:
parent
f85867dd3a
commit
6ffa4ec2a2
5 changed files with 23 additions and 4 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1,2 +1,3 @@
|
|||
node_modules
|
||||
data
|
||||
.env
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
"imports": {},
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"start": "NODE_OPTIONS='--experimental-sqlite' node --watch src/index.js",
|
||||
"start": "NODE_OPTIONS='--experimental-sqlite' node --watch --env-file=.env src/index.js",
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { DatabaseSync } from "node:sqlite"
|
||||
|
||||
const DATABASE_PATH = "/home/thomas/repos/eolas-api/data/eolas.db"
|
||||
const DATABASE_PATH = process.env.DB_PATH
|
||||
|
||||
const database = new DatabaseSync(DATABASE_PATH)
|
||||
|
||||
|
|
|
|||
|
|
@ -2,16 +2,17 @@ import express from "express"
|
|||
import entries from "./routes/entries.js"
|
||||
import tags from "./routes/tags.js"
|
||||
import cors from "cors"
|
||||
|
||||
import { validateApiKey } from "./middlewear/auth.js"
|
||||
const app = express()
|
||||
|
||||
const port = process.env.PORT || 3000
|
||||
|
||||
app.use(cors())
|
||||
app.use(express.json())
|
||||
app.use("/", validateApiKey)
|
||||
app.use("/entries", entries)
|
||||
app.use("/tags", tags)
|
||||
|
||||
app.listen(port, () => {
|
||||
console.info(`INFO Server running at http://localhost:${port}`)
|
||||
console.info(`INFO eolas-api server running at http://localhost:${port}`)
|
||||
})
|
||||
|
|
|
|||
17
src/middlewear/auth.js
Normal file
17
src/middlewear/auth.js
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
const validateApiKey = (req, res, next) => {
|
||||
const apiKey = req.headers["x-api-key"]
|
||||
|
||||
if (!apiKey) {
|
||||
return res.status(401).json({
|
||||
error: "API key is required.",
|
||||
})
|
||||
}
|
||||
|
||||
if (apiKey !== process.env.API_KEY) {
|
||||
return res.status(403).json({ error: "Invalid API key" })
|
||||
}
|
||||
|
||||
next()
|
||||
}
|
||||
|
||||
export { validateApiKey }
|
||||
Loading…
Add table
Reference in a new issue