Compare commits
5 Commits
Author | SHA1 | Date |
---|---|---|
|
c749adff34 | |
|
68f77317a3 | |
|
a468f037c6 | |
|
66aff04910 | |
|
da3da0c7c6 |
|
@ -0,0 +1,52 @@
|
||||||
|
import jwt from "jsonwebtoken";
|
||||||
|
import passport from "passport";
|
||||||
|
import jwtSecret from "../config/jwtConfig";
|
||||||
|
import { db } from "../db.mjs";
|
||||||
|
import logger from "../logger.mjs";
|
||||||
|
|
||||||
|
module.exports = (app) => {
|
||||||
|
app.post("/loginUser", (req, res, next) => {
|
||||||
|
passport.authenticate("login", (err, users, info) => {
|
||||||
|
if (err) {
|
||||||
|
logger.error(`error ${err}`);
|
||||||
|
}
|
||||||
|
if (info !== undefined) {
|
||||||
|
logger.error(info.message);
|
||||||
|
if (info.message === "bad username") {
|
||||||
|
res.status(401).send(info.message);
|
||||||
|
} else {
|
||||||
|
res.status(403).send(info.message);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
req.logIn(users, async () => {
|
||||||
|
let user = await db("users")
|
||||||
|
.select("*")
|
||||||
|
.where({ username: req.body.username });
|
||||||
|
user = user[0];
|
||||||
|
const token = jwt.sign({ id: user.id }, jwtSecret.secret, {
|
||||||
|
expiresIn: 60 * 60,
|
||||||
|
});
|
||||||
|
res.status(200).send({
|
||||||
|
auth: true,
|
||||||
|
token,
|
||||||
|
message: "user found & logged in",
|
||||||
|
});
|
||||||
|
// User.findOne({
|
||||||
|
// where: {
|
||||||
|
// username: req.body.username,
|
||||||
|
// },
|
||||||
|
// }).then((user) => {
|
||||||
|
// const token = jwt.sign({ id: user.id }, jwtSecret.secret, {
|
||||||
|
// expiresIn: 60 * 60,
|
||||||
|
// });
|
||||||
|
// res.status(200).send({
|
||||||
|
// auth: true,
|
||||||
|
// token,
|
||||||
|
// message: "user found & logged in",
|
||||||
|
// });
|
||||||
|
// });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})(req, res, next);
|
||||||
|
});
|
||||||
|
};
|
|
@ -0,0 +1,3 @@
|
||||||
|
export default {
|
||||||
|
secret: "jwt-secret",
|
||||||
|
};
|
|
@ -0,0 +1,166 @@
|
||||||
|
import bcrypt from "bcrypt";
|
||||||
|
import jwtSecret from "./jwtConfig";
|
||||||
|
const BCRYPT_SALT_ROUNDS = 12;
|
||||||
|
import { db } from "../db.mjs";
|
||||||
|
import logger from "../logger.mjs";
|
||||||
|
|
||||||
|
const passport = require("passport");
|
||||||
|
const LocalStrategy = require("passport-local").Strategy;
|
||||||
|
const JWTstrategy = require("passport-jwt").Strategy;
|
||||||
|
const ExtractJWT = require("passport-jwt").ExtractJwt;
|
||||||
|
const User = require("../sequelize");
|
||||||
|
|
||||||
|
passport.use(
|
||||||
|
"register",
|
||||||
|
new LocalStrategy(
|
||||||
|
{
|
||||||
|
usernameField: "username",
|
||||||
|
passwordField: "password",
|
||||||
|
passReqToCallback: true,
|
||||||
|
session: false,
|
||||||
|
},
|
||||||
|
async (req, username, password, done) => {
|
||||||
|
try {
|
||||||
|
let user = await db("users").where({ username }).select("*");
|
||||||
|
if (user.length > 0) {
|
||||||
|
logger.warn("username already taken");
|
||||||
|
return done(null, false, { message: "username already taken" });
|
||||||
|
}
|
||||||
|
user = user[0];
|
||||||
|
const hashedPwd = await bcrypt.hash(password, BCRYPT_SALT_ROUNDS);
|
||||||
|
const userCreated = await db("users").insert({
|
||||||
|
username,
|
||||||
|
password: hashedPwd,
|
||||||
|
});
|
||||||
|
logger.info(`user ${username} created`);
|
||||||
|
return done(null, userCreated);
|
||||||
|
|
||||||
|
// User.findOne({
|
||||||
|
// where: {
|
||||||
|
// [Op.or]: [
|
||||||
|
// {
|
||||||
|
// username,
|
||||||
|
// },
|
||||||
|
// { email: req.body.email },
|
||||||
|
// ],
|
||||||
|
// },
|
||||||
|
// }).then((user) => {
|
||||||
|
// if (user != null) {
|
||||||
|
// console.log("username or email already taken");
|
||||||
|
// return done(null, false, {
|
||||||
|
// message: "username or email already taken",
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// bcrypt.hash(password, BCRYPT_SALT_ROUNDS).then((hashedPassword) => {
|
||||||
|
// User.create({
|
||||||
|
// username,
|
||||||
|
// password: hashedPassword,
|
||||||
|
// email: req.body.email,
|
||||||
|
// }).then((user) => {
|
||||||
|
// console.log("user created");
|
||||||
|
// return done(null, user);
|
||||||
|
// });
|
||||||
|
// });
|
||||||
|
// });
|
||||||
|
} catch (err) {
|
||||||
|
return done(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
passport.use(
|
||||||
|
"login",
|
||||||
|
new LocalStrategy(
|
||||||
|
{
|
||||||
|
usernameField: "username",
|
||||||
|
passwordField: "password",
|
||||||
|
session: false,
|
||||||
|
},
|
||||||
|
async (username, password, done) => {
|
||||||
|
try {
|
||||||
|
const user = db("users").select("*").where({ username });
|
||||||
|
|
||||||
|
if (user.length === 0) {
|
||||||
|
logger.info(`username ${username} does not exist`);
|
||||||
|
return done(null, false, { message: "bad username" });
|
||||||
|
}
|
||||||
|
user = user[0];
|
||||||
|
const pwdMatch = await bcrypt.compare(password, user.password);
|
||||||
|
if (pwdMatch !== true) {
|
||||||
|
logger.info(`passwords do not match`);
|
||||||
|
return done(null, false, { message: "passwords do not match" });
|
||||||
|
}
|
||||||
|
logger.info(`password found and authenticated`);
|
||||||
|
return done(null, user);
|
||||||
|
} catch (err) {
|
||||||
|
done(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
// User.findOne({
|
||||||
|
// where: {
|
||||||
|
// username,
|
||||||
|
// },
|
||||||
|
// }).then((user) => {
|
||||||
|
// if (user === null) {
|
||||||
|
// return done(null, false, { message: "bad username" });
|
||||||
|
// }
|
||||||
|
// bcrypt.compare(password, user.password).then((response) => {
|
||||||
|
// if (response !== true) {
|
||||||
|
// console.log("passwords do not match");
|
||||||
|
// return done(null, false, { message: "passwords do not match" });
|
||||||
|
// }
|
||||||
|
// console.log("user found & authenticated");
|
||||||
|
// return done(null, user);
|
||||||
|
// });
|
||||||
|
// });
|
||||||
|
// } catch (err) {
|
||||||
|
// done(err);
|
||||||
|
// }
|
||||||
|
// },
|
||||||
|
// ),
|
||||||
|
// );
|
||||||
|
|
||||||
|
const opts = {
|
||||||
|
jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme("JWT"),
|
||||||
|
secretOrKey: jwtSecret.secret,
|
||||||
|
};
|
||||||
|
|
||||||
|
passport.use(
|
||||||
|
"jwt",
|
||||||
|
new JWTstrategy(opts, async (jwt_payload, done) => {
|
||||||
|
try {
|
||||||
|
let user = await db("users").select("*").where({ id: jwt_payload.id });
|
||||||
|
if (user.length === 1) {
|
||||||
|
logger.info("user found");
|
||||||
|
done(null, user[0]);
|
||||||
|
} else {
|
||||||
|
logger.info("user not found");
|
||||||
|
done(null, false);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
done(err);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// User.findOne({
|
||||||
|
// where: {
|
||||||
|
// id: jwt_payload.id,
|
||||||
|
// },
|
||||||
|
// }).then((user) => {
|
||||||
|
// if (user) {
|
||||||
|
// console.log("user found in db in passport");
|
||||||
|
// done(null, user);
|
||||||
|
// } else {
|
||||||
|
// console.log("user not found in db");
|
||||||
|
// done(null, false);
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
// } catch (err) {
|
||||||
|
// done(err);
|
||||||
|
// }
|
||||||
|
// }),
|
||||||
|
// );
|
25
logger.mjs
25
logger.mjs
|
@ -1,6 +1,6 @@
|
||||||
import pino from 'pino'
|
import pino from "pino";
|
||||||
import path from 'path'
|
import path from "path";
|
||||||
import { fileURLToPath } from 'url';
|
import { fileURLToPath } from "url";
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
const __dirname = path.dirname(__filename);
|
const __dirname = path.dirname(__filename);
|
||||||
|
|
||||||
|
@ -15,14 +15,15 @@ const __dirname = path.dirname(__filename);
|
||||||
// }]
|
// }]
|
||||||
// })
|
// })
|
||||||
export default pino(
|
export default pino(
|
||||||
{
|
{
|
||||||
level: 'fatal',
|
level: "info",
|
||||||
formatters: {
|
formatters: {
|
||||||
level: (label) => {
|
level: (label) => {
|
||||||
return { level: label.toUpperCase() };
|
return { level: label.toUpperCase() };
|
||||||
},
|
|
||||||
},
|
},
|
||||||
timestamp: pino.stdTimeFunctions.isoTime,
|
|
||||||
},
|
},
|
||||||
//pino.destination(`${__dirname}/app.log`)
|
timestamp: pino.stdTimeFunctions.isoTime,
|
||||||
);
|
},
|
||||||
|
//pino.destination(`${__dirname}/app.log`)
|
||||||
|
);
|
||||||
|
|
||||||
|
|
|
@ -1,85 +1,81 @@
|
||||||
import express from "express";
|
import express from "express";
|
||||||
import logger from "../logger.mjs";
|
import logger from "../logger.mjs";
|
||||||
import Story from "./Story.mjs"
|
import Story from "./Story.mjs";
|
||||||
import Publication from "./Publication.mjs"
|
import Publication from "./Publication.mjs";
|
||||||
import Submission from "./Submission.mjs";
|
import Submission from "./Submission.mjs";
|
||||||
|
import passport from "passport";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export const getEndpoints = (dbObject) => {
|
export const getEndpoints = (dbObject) => {
|
||||||
const router = express.Router()
|
const router = express.Router();
|
||||||
|
|
||||||
router.get('/stories', (req,res)=>{
|
router.get("/stories", (_, res) => {
|
||||||
res.statusCode=200
|
res.statusCode = 200;
|
||||||
res.send(dbObject.stories)
|
res.send(dbObject.stories);
|
||||||
return
|
return;
|
||||||
})
|
});
|
||||||
|
|
||||||
router.get('/publications', (req,res)=>{
|
router.get("/publications", (_, res) => {
|
||||||
res.statusCode=200
|
res.statusCode = 200;
|
||||||
res.send(dbObject.publications)
|
res.send(dbObject.publications);
|
||||||
return
|
return;
|
||||||
})
|
});
|
||||||
|
|
||||||
router.get('/submissions', (req,res)=>{
|
router.get("/submissions", (_, res) => {
|
||||||
res.statusCode=200
|
res.statusCode = 200;
|
||||||
res.send(dbObject.submissions)
|
res.send(dbObject.submissions);
|
||||||
return
|
return;
|
||||||
})
|
});
|
||||||
router.get('/responses', (req,res)=>{
|
router.get("/responses", (_, res) => {
|
||||||
res.statusCode=200
|
res.statusCode = 200;
|
||||||
res.send(dbObject.responses)
|
res.send(dbObject.responses);
|
||||||
return
|
return;
|
||||||
})
|
});
|
||||||
router.get('/genres', (req,res)=>{
|
router.get("/genres", (_, res) => {
|
||||||
res.statusCode=200
|
res.statusCode = 200;
|
||||||
res.send(dbObject.genres)
|
res.send(dbObject.genres);
|
||||||
return
|
return;
|
||||||
})
|
});
|
||||||
|
|
||||||
return router
|
return router;
|
||||||
}
|
};
|
||||||
|
|
||||||
export const postEndpoints = (db,data) => {
|
export const postEndpoints = (db, data) => {
|
||||||
const router = express.Router()
|
const router = express.Router();
|
||||||
endpoint(router,Story,'create','insert',db,data)
|
protectedEndpoint(router, Story, "create", "insert", db, data);
|
||||||
endpoint(router,Story,'edit','update',db,data)
|
protectedEndpoint(router, Story, "edit", "update", db, data);
|
||||||
endpoint(router,Story,'delete','update',db,data)
|
protectedEndpoint(router, Story, "delete", "update", db, data);
|
||||||
endpoint(router,Submission,'create','insert',db,data)
|
protectedEndpoint(router, Submission, "create", "insert", db, data);
|
||||||
endpoint(router,Submission,'edit','update',db,data)
|
protectedEndpoint(router, Submission, "edit", "update", db, data);
|
||||||
endpoint(router,Submission,'delete','update',db,data)
|
protectedEndpoint(router, Submission, "delete", "update", db, data);
|
||||||
endpoint(router,Publication,'create','insert',db,data)
|
protectedEndpoint(router, Publication, "create", "insert", db, data);
|
||||||
endpoint(router,Publication,'edit','update',db,data)
|
protectedEndpoint(router, Publication, "edit", "update", db, data);
|
||||||
endpoint(router,Publication,'delete','del',db,data)
|
protectedEndpoint(router, Publication, "delete", "del", db, data);
|
||||||
return router
|
return router;
|
||||||
}
|
};
|
||||||
|
|
||||||
|
const protectedEndpoint = (router, Entity, path, method, db, data) => {
|
||||||
|
router.post(
|
||||||
const endpoint = (router,Entity,path,method,db,data) =>{
|
`/${Entity.name.toLowerCase()}/${path}`,
|
||||||
router.post(`/${Entity.name.toLowerCase()}/${path}`, async (req,res) => {
|
passport.authenticate("jwt", { session: false }, (_, res) => {
|
||||||
try {
|
res.json({ message: "protected endpoint" });
|
||||||
logger.trace({data:req.body},"POST request received")
|
}),
|
||||||
const entity = new Entity(req.body)
|
async (req, res) => {
|
||||||
await entity[method](db,data)
|
try {
|
||||||
res.sendStatus(200)
|
logger.trace({ data: req.body }, "POST request received");
|
||||||
data.init()
|
const entity = new Entity(req.body);
|
||||||
return
|
await entity[method](db, data);
|
||||||
} catch (error) {
|
res.sendStatus(200);
|
||||||
logger.error(error)
|
data.init();
|
||||||
if(error instanceof TypeError){
|
return;
|
||||||
res.sendStatus(400)
|
} catch (error) {
|
||||||
return
|
logger.error(error);
|
||||||
}
|
if (error instanceof TypeError) {
|
||||||
res.sendStatus(500)
|
res.sendStatus(400);
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
})
|
res.sendStatus(500);
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
11
package.json
11
package.json
|
@ -14,16 +14,21 @@
|
||||||
"chai-as-promised": "^7.1.1",
|
"chai-as-promised": "^7.1.1",
|
||||||
"chai-http": "^4.4.0",
|
"chai-http": "^4.4.0",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
|
"eslint": "^8.57.0",
|
||||||
"express": "^4.18.2",
|
"express": "^4.18.2",
|
||||||
|
"helmet": "^7.1.0",
|
||||||
|
"jsonwebtoken": "^9.0.2",
|
||||||
"knex": "^2.5.1",
|
"knex": "^2.5.1",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
"luxon": "^3.4.3",
|
"luxon": "^3.4.3",
|
||||||
"mocha": "^10.2.0",
|
"mocha": "^10.2.0",
|
||||||
|
"mongodb": "^6.5.0",
|
||||||
|
"mongoose": "^8.2.2",
|
||||||
|
"passport": "^0.7.0",
|
||||||
|
"passport-jwt": "^4.0.1",
|
||||||
|
"passport-local": "^1.0.0",
|
||||||
"pino": "^8.15.0",
|
"pino": "^8.15.0",
|
||||||
"pino-http": "^8.5.0",
|
"pino-http": "^8.5.0",
|
||||||
"sqlite3": "^5.1.6"
|
"sqlite3": "^5.1.6"
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"eslint": "^8.57.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,41 @@
|
||||||
|
import passport from "passport";
|
||||||
|
import User from "../sequelize";
|
||||||
|
|
||||||
|
module.exports = (app) => {
|
||||||
|
app.get("/findUser", (req, res, next) => {
|
||||||
|
passport.authenticate("jwt", { session: false }, (err, user, info) => {
|
||||||
|
if (err) {
|
||||||
|
console.log(err);
|
||||||
|
}
|
||||||
|
if (info !== undefined) {
|
||||||
|
console.log(info.message);
|
||||||
|
res.status(401).send(info.message);
|
||||||
|
} else if (user.username === req.query.username) {
|
||||||
|
User.findOne({
|
||||||
|
where: {
|
||||||
|
username: req.query.username,
|
||||||
|
},
|
||||||
|
}).then((userInfo) => {
|
||||||
|
if (userInfo != null) {
|
||||||
|
console.log("user found in db from findUsers");
|
||||||
|
res.status(200).send({
|
||||||
|
auth: true,
|
||||||
|
first_name: userInfo.first_name,
|
||||||
|
last_name: userInfo.last_name,
|
||||||
|
email: userInfo.email,
|
||||||
|
username: userInfo.username,
|
||||||
|
password: userInfo.password,
|
||||||
|
message: "user found in db",
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.error("no user exists in db with that username");
|
||||||
|
res.status(401).send("no user exists in db with that username");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.error("jwt id and username do not match");
|
||||||
|
res.status(403).send("username and jwt token do not match");
|
||||||
|
}
|
||||||
|
})(req, res, next);
|
||||||
|
});
|
||||||
|
};
|
44
server.mjs
44
server.mjs
|
@ -1,36 +1,34 @@
|
||||||
import express from "express"
|
import express from "express";
|
||||||
import pinoHTTP from 'pino-http'
|
import pinoHTTP from "pino-http";
|
||||||
import logger from "./logger.mjs";
|
import logger from "./logger.mjs";
|
||||||
import bodyParser from "body-parser";
|
import bodyParser from "body-parser";
|
||||||
import { Data } from "./objects/Data.mjs";
|
import { Data } from "./objects/Data.mjs";
|
||||||
import { db } from "./db.mjs";
|
import { db } from "./db.mjs";
|
||||||
import { getEndpoints, postEndpoints } from "./objects/Endpoints.mjs";
|
import { getEndpoints, postEndpoints } from "./objects/Endpoints.mjs";
|
||||||
import cors from 'cors'
|
import cors from "cors";
|
||||||
|
import helmet from "helmet";
|
||||||
|
import passport from "passport";
|
||||||
|
|
||||||
const app = express()
|
const app = express();
|
||||||
const port = 4000
|
const port = 4000;
|
||||||
const corsOptions={
|
|
||||||
origin: ['http://localhost:5173']
|
|
||||||
}
|
|
||||||
app.use(cors())
|
|
||||||
app.use(pinoHTTP({logger}))
|
|
||||||
app.use(bodyParser.json())
|
|
||||||
|
|
||||||
|
app.use(cors());
|
||||||
|
app.use(pinoHTTP({ logger }));
|
||||||
|
app.use(bodyParser.json());
|
||||||
|
|
||||||
|
app.use(bodyParser.urlencoded({ extended: false }));
|
||||||
|
app.use(helmet());
|
||||||
|
app.use(passport.initialize());
|
||||||
|
|
||||||
|
const data = new Data(db);
|
||||||
|
await data.init();
|
||||||
|
|
||||||
const data = new Data(db)
|
app.use("/api", getEndpoints(data));
|
||||||
await data.init()
|
app.use("/api", postEndpoints(db, data));
|
||||||
|
|
||||||
|
|
||||||
app.use('/api',getEndpoints(data))
|
|
||||||
app.use('/api',postEndpoints(db,data) )
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
app.listen(port, (err) => {
|
app.listen(port, (err) => {
|
||||||
if (err) logger.error(err);
|
if (err) logger.error(err);
|
||||||
logger.info("Server listening on PORT " + port)
|
logger.info("Server listening on PORT " + port);
|
||||||
})
|
});
|
||||||
|
|
||||||
export default app
|
export default app;
|
||||||
|
|
BIN
submissions
BIN
submissions
Binary file not shown.
Loading…
Reference in New Issue