server initial commit
This commit is contained in:
40
server/app.js
Normal file
40
server/app.js
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
console.log("starting server...");
|
||||||
|
import path from "path";
|
||||||
|
import {fileURLToPath} from "url";
|
||||||
|
import express from "express";
|
||||||
|
import cors from "cors";
|
||||||
|
import userRouter from "./routes/users.js";
|
||||||
|
import errorHandler from "./middlewares/ErrorHandler.js";
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
import db from "./models/db.js";
|
||||||
|
|
||||||
|
try {
|
||||||
|
await db.pool.query('SELECT 1');
|
||||||
|
console.log('Database connection successful.');
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Database connection failed:', err);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
const port = process.env.PORT || 3000;
|
||||||
|
|
||||||
|
app.use(express.json());
|
||||||
|
app.use(cors({
|
||||||
|
origin: ['https://ijylaw.li0nhunter.com', 'https://ijylaw.com', "https://www.ijylaw.com", "http://localhost:5173"],
|
||||||
|
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
||||||
|
credentials: true
|
||||||
|
}));
|
||||||
|
app.get('/', (req, res) => {
|
||||||
|
res.send("Hello! You've reached ijy law backend. Unless you are a developer, you probably shouldn't be here.");
|
||||||
|
});
|
||||||
|
app.use("/api/users", userRouter);
|
||||||
|
app.use(errorHandler);
|
||||||
|
|
||||||
|
app.listen(port, () => {
|
||||||
|
console.log(`Server is running at http://localhost:${port}`);
|
||||||
|
});
|
||||||
0
server/controllers/index.js
Normal file
0
server/controllers/index.js
Normal file
16
server/controllers/users.js
Normal file
16
server/controllers/users.js
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import db from "../models/db.js";
|
||||||
|
import users from "../models/users.js";
|
||||||
|
|
||||||
|
/** * Fetches all users from the database.
|
||||||
|
* @return {Promise<User[]>}
|
||||||
|
*/
|
||||||
|
const getAllUsers = async () => {
|
||||||
|
try {
|
||||||
|
return await users.getAllUsers();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching users:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default { getAllUsers };
|
||||||
44
server/middlewares/AuthHandler.js
Normal file
44
server/middlewares/AuthHandler.js
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
import jwt from "jsonwebtoken";
|
||||||
|
/** @typedef {import("express").Request} Request */
|
||||||
|
/** @typedef {import("express").Response} Response */
|
||||||
|
/** @typedef {import("express").NextFunction} NextFunction */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Express middleware to verify JWT and check for the admin role.
|
||||||
|
* @param {Request} req
|
||||||
|
* @param {Response} res
|
||||||
|
* @param {NextFunction} next
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export default async (req, res, next) => {
|
||||||
|
const token = req.headers.authorization;
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
res.status(401).send({data: null, error: "Token missing"});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const payload = await new Promise((resolve, reject) => {
|
||||||
|
jwt.verify(token, process.env.JWT_SECRET || "super-secret-key", (err, decoded) => {
|
||||||
|
if (err) return reject(err);
|
||||||
|
return resolve(decoded);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
// Check if payload has id and role and if the role is admin
|
||||||
|
if (!payload || !payload.id || !payload.role) {
|
||||||
|
res.status(401).json({data: null, error: "Invalid token"});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (payload.role !== "admin") {
|
||||||
|
res.status(403).json({data: null, error: "admins only"});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof Error && err.message === 'jwt expired') {
|
||||||
|
res.status(401).json({data: null, message: "Token expired", error: err});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.status(401).json({data: null, message: "Invalid token", error: err});
|
||||||
|
}
|
||||||
|
};
|
||||||
17
server/middlewares/ErrorHandler.js
Normal file
17
server/middlewares/ErrorHandler.js
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
/** @typedef {import("express").Request} Request */
|
||||||
|
/** @typedef {import("express").Response} Response */
|
||||||
|
/** @typedef {import("express").NextFunction} NextFunction */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Express error handler middleware.
|
||||||
|
* @param {Error & {status?: number}} err
|
||||||
|
* @param {Request} req
|
||||||
|
* @param {Response} res
|
||||||
|
* @param {NextFunction} next
|
||||||
|
*/
|
||||||
|
export default (err, req, res, next) => {
|
||||||
|
console.error(err);
|
||||||
|
res.status(err.status || 500).json({
|
||||||
|
message: err.message || 'Internal Server Error',
|
||||||
|
});
|
||||||
|
};
|
||||||
31
server/models/db.js
Normal file
31
server/models/db.js
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
import dotenv from 'dotenv';
|
||||||
|
import {Pool} from 'pg';
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
const pool = new Pool(process.env.DATABASE_URL ? {connectionString: process.env.DATABASE_URL} : {
|
||||||
|
user: process.env.DB_USER,
|
||||||
|
host: process.env.DB_HOST,
|
||||||
|
database: process.env.DB_NAME,
|
||||||
|
password: process.env.DB_PASSWORD,
|
||||||
|
port: parseInt(process.env.DB_PORT || '5432', 10),
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generic query function for PostgreSQL database.
|
||||||
|
* @param {string} text
|
||||||
|
* @param {any[]} [params]
|
||||||
|
* @return {Promise<any[]>}
|
||||||
|
*/
|
||||||
|
async function query(text, params= []) {
|
||||||
|
const start = Date.now();
|
||||||
|
const res = await pool.query(text, params).then(qr => qr);
|
||||||
|
const duration = Date.now() - start;
|
||||||
|
if (params) for (let i = 0; i < params.length; i++) text = text.replace("$".concat(String(i + 1)), params[i]);
|
||||||
|
console.log('executed query', {text, duration, rows: res.rowCount});
|
||||||
|
return res.rows;
|
||||||
|
}
|
||||||
|
export default {
|
||||||
|
pool,
|
||||||
|
query
|
||||||
|
};
|
||||||
23
server/models/users.js
Normal file
23
server/models/users.js
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
import db from "./db.js";
|
||||||
|
/** @typedef User
|
||||||
|
* @property {number} id - The unique identifier for the user.
|
||||||
|
* @property {string} username - The username of the user.
|
||||||
|
* @property {string} password - The hashed password of the user.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches all users from the database.
|
||||||
|
* @return {Promise<User[]>}
|
||||||
|
*/
|
||||||
|
const getAllUsers = async () => {
|
||||||
|
try {
|
||||||
|
return await db.query('SELECT * FROM users').then((users) => users);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching users:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default {
|
||||||
|
getAllUsers
|
||||||
|
}
|
||||||
1485
server/package-lock.json
generated
Normal file
1485
server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
21
server/package.json
Normal file
21
server/package.json
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"name": "server",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": false,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"start": "node app.js"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"bcryptjs": "^3.0.2",
|
||||||
|
"cors": "^2.8.5",
|
||||||
|
"dotenv": "^16.5.0",
|
||||||
|
"express": "^4.18.2",
|
||||||
|
"jsonwebtoken": "^9.0.2",
|
||||||
|
"nodemailer": "^7.0.3",
|
||||||
|
"pg": "^8.16.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"jsdoc": "^4.0.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
9
server/routes/index.js
Normal file
9
server/routes/index.js
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import express from 'express';
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
/* GET home page. */
|
||||||
|
router.get('/', function(req, res, next) {
|
||||||
|
res.render('index', { title: 'Express' });
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
8
server/routes/users.js
Normal file
8
server/routes/users.js
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import express from 'express';
|
||||||
|
const router = express.Router();
|
||||||
|
import userController from '../controllers/users.js';
|
||||||
|
import AuthHandler from "../middlewares/AuthHandler.js";
|
||||||
|
/* GET users listing. */
|
||||||
|
router.get('/', AuthHandler, userController.getAllUsers);
|
||||||
|
|
||||||
|
export default router;
|
||||||
Reference in New Issue
Block a user