OpenAuth_server/src/api/admin/regcode.ts

34 lines
1.2 KiB
TypeScript
Raw Normal View History

2018-11-06 19:48:50 +00:00
import { Request, Router } from "express";
import promiseMiddleware from "../../helper/promiseMiddleware";
import RegCode from "../../models/regcodes";
import { randomBytes } from "crypto";
import moment = require("moment");
import { GetUserMiddleware } from "../middlewares/user";
import { HttpStatusCode } from "../../helper/request_error";
const RegCodeRoute: Router = Router();
RegCodeRoute.use(GetUserMiddleware(true, true), (req: Request, res, next) => {
if (!req.isAdmin) res.sendStatus(HttpStatusCode.FORBIDDEN)
else next()
});
RegCodeRoute.route("/")
.get(promiseMiddleware(async (req, res) => {
let regcodes = await RegCode.find({});
res.json(regcodes);
}))
.delete(promiseMiddleware(async (req, res) => {
let { id } = req.query;
await RegCode.delete(id);
res.json({ success: true });
}))
.post(promiseMiddleware(async (req, res) => {
let regcode = RegCode.new({
token: randomBytes(10).toString("hex"),
valid: true,
validTill: moment().add("1", "month").toDate()
})
await RegCode.save(regcode);
res.json({ code: regcode.token });
}))
export default RegCodeRoute;