Skip to content

Commit

Permalink
started user api route cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Dragon1320 committed Jun 29, 2018
1 parent 6a232a0 commit 9020743
Show file tree
Hide file tree
Showing 6 changed files with 163 additions and 110 deletions.
2 changes: 1 addition & 1 deletion src/db/schemas/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const UserSchema = new Schema({
// _id: ObjectId,
discord_id: { type: String, required: true, unique: true, maxlength: 18, minlength: 18 },
admin: { type: Boolean, default: false },
scripts: [ Schema.Types.ObjectId ]
scripts: [ { type: Schema.Types.ObjectId, default: [] } ]
});

module.exports = mongoose.model("User", UserSchema);
42 changes: 36 additions & 6 deletions src/web/middlewares/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,21 @@ const { fetchSession, fetchUser } = require("../helpers");

const authSession = (req, res, next) => {

if (req.cookies === undefined || req.cookies.session === undefined) {
let token;

if (req.cookies !== undefined && req.cookies.session !== undefined) {
token = req.cookies.session;
}

if (req.headers["xxx-access-token"] !== undefined) {
token = req.headers["xxx-access-token"];
}

if (token === undefined) {
return res.json({ status: 401, message: "Unauthorized", error: "There was an issue fetching your session" });
}

fetchSession(req.cookies.session)
fetchSession(token)
.then(session_doc => {

if (session_doc.complete === false) {
Expand All @@ -26,11 +36,21 @@ const authSession = (req, res, next) => {

const authUser = (req, res, next) => {

if (req.cookies === undefined || req.cookies.session === undefined) {
let token;

if (req.cookies !== undefined && req.cookies.session !== undefined) {
token = req.cookies.session;
}

if (req.headers["xxx-access-token"] !== undefined) {
token = req.headers["xxx-access-token"];
}

if (token === undefined) {
return res.json({ status: 401, message: "Unauthorized", error: "There was an issue fetching your session" });
}

fetchSession(req.cookies.session)
fetchSession(token)
.then(session_doc => {

if (session_doc.complete === false) {
Expand Down Expand Up @@ -58,11 +78,21 @@ const authUser = (req, res, next) => {

const authAdmin = (req, res, next) => {

if (req.cookies === undefined || req.cookies.session === undefined) {
let token;

if (req.cookies !== undefined && req.cookies.session !== undefined) {
token = req.cookies.session;
}

if (req.headers["xxx-access-token"] !== undefined) {
token = req.headers["xxx-access-token"];
}

if (token === undefined) {
return res.json({ status: 401, message: "Unauthorized", error: "There was an issue fetching your session" });
}

fetchSession(req.cookies.session)
fetchSession(token)
.then(session_doc => {

if (session_doc.complete === false) {
Expand Down
8 changes: 4 additions & 4 deletions src/web/routes/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

const express = require("express");

const guilds = require("./guilds");
//const guilds = require("./guilds");
const logs = require("./logs");
const scripts = require("./scripts");
//const scripts = require("./scripts");
const users = require("./users");

const router = express.Router();

router.use("/guilds", guilds);
//router.use("/guilds", guilds);
router.use("/logs", logs);
router.use("/scripts", scripts);
//router.use("/scripts", scripts);
router.use("/users", users);

module.exports = router;
71 changes: 27 additions & 44 deletions src/web/routes/api/logs.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,65 +4,48 @@ const express = require("express");

const schemas = require("../../../db");
const Logger = require("../../../logger");
const { fetchSession, authLogin } = require("../../middlewares");
const { authAdmin } = require("../../middlewares");

const router = express.Router();
const apiLogger = new Logger();

router.get("/", fetchSession, authLogin, (req, res) => {
const limitDef = 20;
const limitMax = 50;

schemas.UserSchema
.findOne({
discord_id: req.session.discord.id
})
.then(userdoc => {
if (userdoc === null) {
return res.json({ status: 403, message: "Forbidden", error: "User doc not found" });
}
const pageDef = 0;

if (userdoc.admin === false) {
return res.json({ status: 403, message: "Forbidden", error: "Admin only path" });
}
router.get("/", authAdmin, async (req, res) => {

const limitDef = 20;
const limitMax = 50;

const pageDef = 0;

const page = req.query.page === undefined ? pageDef : req.query.page;
let limit = req.query.limit === undefined ? limitDef : parseInt(req.query.limit);

if (isNaN(limit)) {
limit = limitDef;
}
if (limit > limitMax) {
limit = limitMax;
}

const type = req.query.type === undefined ? null : req.query.type;

schemas.LogSchema
const type = req.query.type === undefined ? null : req.query.type;
const page = req.query.page === undefined ? pageDef : req.query.page;

let limit = req.query.limit === undefined ? limitDef : parseInt(req.query.limit);
if (isNaN(limit) === true) {
limit = limitDef;
}
if (limit > limitMax) {
limit = limitMax;
}

let log_schemas;
try {

log_schemas = await schemas.LogSchema
.find({
...(type === null ? {} : { type })
})
.skip(page * limit).limit(limit)
.skip(page * limit)
.limit(limit)
.select({
_id: 0,
__v: 0
})
.then(docs => {

res.json(docs);
})
.catch(err => {

res.json({ err });
});
})
.catch(err => {
} catch(error) {

res.json({ status: 500, message: "Internal Server Error", error });
}

res.json({ status: 500, message: "Internal Server Error", error: err });
});
res.json(log_schemas);
});

module.exports = router;
146 changes: 93 additions & 53 deletions src/web/routes/api/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,79 +4,118 @@ const express = require("express");

const schemas = require("../../../db");
const Logger = require("../../../logger");
const { fetchSession, authLogin, fetchUser, authAdmin } = require("../../middlewares");
const { authUser, authAdmin } = require("../../middlewares");

const router = express.Router();
const apiLogger = new Logger();

router.post("/", fetchSession, authLogin, (req, res) => {
router.post("/", authAdmin, async (req, res) => {

// Admin only.
// Get input.
const discord_id = req.body.discord_id === undefined ? null : req.body.discord_id;
const admin = req.body.admin === undefined ? false : req.body.admin;
const scripts = req.body.scripts === undefined ? [] : req.body.scripts;

schemas.UserSchema
.findOne({
discord_id: req.session.discord.id
})
.then(async doc => {
if (doc === null) {
return res.json({ status: 403, message: "Forbidden", error: "User doc not found" });
}
// Check discord id.
if (discord_id === null || discord_id.length !== 18) {
return res.json({ status: 400, message: "Bad Request", error: "Discord id not specified or incorrect" });
}

if (doc.admin === false) {
return res.json({ status: 403, message: "Forbidden", error: "Admin only path" });
}
let old_discord_id;
try {

const discord_id = req.body.discord_id === undefined ? null : req.body.discord_id;
const admin = req.body.admin === undefined ? null : req.body.admin;
const scripts = req.body.scripts === undefined ? null : req.body.scripts;
old_discord_id = await schemas.UserSchema
.findOne({
discord_id
});
} catch(error) {

// Make sure script ids are valid.
if (scripts instanceof Array && scripts.length > 0) {
return res.json({ status: 500, message: "Internal Server Error", error });
}

const status = await schemas.ScriptSchema
.find({
_id: { $in: scripts }
})
.then(docs => {
if (docs.length !== scripts.length) {
return -1;
}
if (old_discord_id !== null) {
return res.json({ status: 400, message: "Bad Request", error: "Duplicate discord id" });
}

return 0;
})
.catch(err => {
// Check scripts.
if (scripts instanceof Array === false) {
return res.json({ status: 400, message: "Bad Request", error: "Scripts should be an array" });
}

return err;
});
if (scripts.length > 0) {

if (status !== 0) {
return res.json({ status: 500, message: "Internal Server Error", error: status === -1 ? "Could not find script(s) specified" : status });
}
}
let script_docs;
try {

script_docs = await schemas.ScriptSchema
.find({
_id: { $in: scripts }
});
} catch(error) {

return res.json({ status: 500, message: "Internal Server Error", error });
}

const user = new schemas.UserSchema({
...(discord_id === null ? {} : { discord_id }),
...(admin === null ? {} : { admin }),
...(scripts === null ? {} : { scripts })
});
if (script_docs.length !== scripts.length) {
return res.json({ status: 400, message: "Bad Request", error: "Script(s) specified could not be found" });
}
}

user
.save()
.then(doc => {
// Create new user.
const user = new schemas.UserSchema({
discord_id,
admin,
scripts
});

res.json({ status: 200, message: "OK", error: null });
})
.catch(err => {
try {

await user.save();
} catch(error) {

return res.json({ status: 500, message: "Internal Server Error", error });
}

res.json({ status: 200, message: "OK", error: null });
});

router.route("/@me").get(authUser, (req, res) => {



}).put(authUser, (req, res) => {



}).patch(authUser, (req, res) => {



}).delete(authUser, (req, res) => {



});

router.route("/:discord_id").get(authAdmin, (req, res) => {



}).put(authAdmin, (req, res) => {



}).patch(authAdmin, (req, res) => {



}).delete(authAdmin, (req, res) => {


res.json({ status: 500, message: "Internal Server Error", error: err });
});
})
.catch(err => {

res.json({ status: 500, message: "Internal Server Error", error: err });
});
});

/*
router.route("/@me").get(fetchSession, authLogin, (req, res) => {
// Admin, user (limited).
Expand Down Expand Up @@ -524,5 +563,6 @@ router.route("/:discord_id").get(fetchSession, authLogin, (req, res) => {
});
});
*/

module.exports = router;
4 changes: 2 additions & 2 deletions src/web/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const jwt = require("jsonwebtoken");

const schemas = require("../../db");
const Logger = require("../../logger");
//const api = require("./api");
const api = require("./api");
const { authSession, authUser, authAdmin } = require("../middlewares");
const { fetchSession } = require("../helpers");

Expand All @@ -28,7 +28,7 @@ try {
apiLogger.fatalError(`Could not read config file: ${err}`);
}

//router.use("/api/v3", api);
router.use("/api/v3", api);

router.get("/auth/discord", async (req, res) => {

Expand Down

0 comments on commit 9020743

Please sign in to comment.