You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
1.7 KiB
69 lines
1.7 KiB
const express = require("express"); |
|
const jwt = require("jsonwebtoken"); |
|
const bodyParser = require("body-parser"); |
|
const { Model } = require("objection"); |
|
const knexConfig = require("./knexfile"); |
|
const User = require("./model/User"); |
|
|
|
require("dotenv").config(); |
|
|
|
const knex = require("knex")(knexConfig); |
|
|
|
Model.knex(knex); |
|
|
|
const app = express(); |
|
|
|
app.use(bodyParser.json()); |
|
app.use(bodyParser.urlencoded({ extended: true })); |
|
|
|
app.use(require("express-form-data").parse()); |
|
|
|
app.use(require("cors")()); |
|
|
|
app.use((req, res, next) => { |
|
req.body = { ...req.body, ...req.query }; |
|
next(); |
|
}); |
|
|
|
// Logging Middleware |
|
app.use((req, res, next) => { |
|
console.log(new Date().toUTCString(), req.method, req.path); |
|
next(); |
|
}); |
|
|
|
// Authorization middleware |
|
app.use(async (req, res, next) => { |
|
if (req.path === "/auth/register" || req.path === "/auth/login") |
|
return next(); |
|
|
|
const authHeader = req.header("Authorization"); |
|
|
|
let token = authHeader?.replace("Bearer ", ""); |
|
|
|
// Try to get token if request is from frontend |
|
if (!token) { |
|
token = req.cookies?.token; |
|
} |
|
|
|
// Try to get token from body |
|
if (!token) { |
|
token = req.body.token; |
|
} |
|
|
|
if (!token) return res.status(401).send("Invalid token"); |
|
|
|
try { |
|
const verified = jwt.verify(token, process.env.AUTH_SECRET); |
|
req.userId = verified._id; |
|
const user = await User.query().findById(req.userId); |
|
req.user = user; |
|
next(); |
|
} catch (err) { |
|
res.status(401).json(err); |
|
} |
|
}); |
|
|
|
app.use("/auth", require("./routes/auth")); |
|
app.use("/redirects", require("./routes/redirects")); |
|
|
|
app.listen(8080, () => console.log("Listening on 8080"));
|
|
|