Commit 77870571 authored by Tandin Wangchen's avatar Tandin Wangchen

initial folder structure

parent 07e711e3
......@@ -4,6 +4,9 @@ const dotenv = require('dotenv');
const cors = require('cors');
const bodyParser = require('body-parser');
const videoApi = require('./src/routes/video.routes');
dotenv.config();
const app = express();
app.use(cors());
......@@ -34,7 +37,6 @@ mongoose.connect(MONGODB_URI, {
mongoose.connection.once('open', () => {
console.log('Database Connected...');
initial();
console.log('######################################################');
});
......@@ -42,62 +44,12 @@ app.route('/').get((req, res) => {
res.send('Research Project');
});
require('./src/routes/auth.routes')(app);
require('./src/routes/user.routes')(app);
// Api calls
app.use('/video', videoApi());
// End of api calls
app.listen(PORT, () => {
console.log('######################################################');
console.log(`Server is ON and running on PORT : ${PORT}`);
console.log('...Wait DB connecting...');
console.log('Connecting to Database...');
});
\ No newline at end of file
const db = require("./src/modules");
const Role = db.role;
function initial() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "manager"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'manager' to roles collection");
});
new Role({
name: "student"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'student' to roles collection");
});
new Role({
name: "admin"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'admin' to roles collection");
console.log('######################################################');
});
}
});
}
\ No newline at end of file
This diff is collapsed.
......@@ -4,6 +4,8 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"start:dev": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
......@@ -24,6 +26,7 @@
},
"devDependencies": {
"formidable": "^1.2.2",
"slugify": "^1.6.0"
"slugify": "^1.6.0",
"nodemon": "^2.0.15"
}
}
const jwt = require("jsonwebtoken");
const config = require("../config/auth.config");
const db = require("../modules");
const User = db.user;
const Role = db.role;
verifyToken = (req, res, next) => {
let token = req.headers["x-access-token"];
if (!token) {
return res.status(403).send({ message: "No token provided!" });
}
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.status(401).send({ message: "Unauthorized!" });
}
req.userId = decoded.id;
next();
});
};
isAdmin = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
Role.find(
{
_id: { $in: user.roles }
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "admin") {
next();
return;
}
}
res.status(403).send({ message: "Require Admin Role!" });
return;
}
);
});
};
isManager = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
Role.find(
{
_id: { $in: user.roles }
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "manager") {
next();
return;
}
}
res.status(403).send({ message: "Require Manager Role!" });
return;
}
);
});
};
isStudent = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
Role.find(
{
_id: { $in: user.roles }
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "student") {
next();
return;
}
}
res.status(403).send({ message: "Require Student Role!" });
return;
}
);
});
};
const authJwt = {
verifyToken,
isAdmin,
isStudent,
isManager
};
module.exports = authJwt;
\ No newline at end of file
const authJwt = require('./authJwt');
const verifySignUp = require('./verifySignUp');
module.exports = {
authJwt,
verifySignUp
};
\ No newline at end of file
const db = require("../modules");
const ROLES = db.ROLES;
const User = db.user;
checkDuplicateUsernameOrEmail = (req, res, next) => {
// Username
User.findOne({
username: req.body.username
}).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (user) {
res.status(400).send({ message: "Failed! Username is already in use!" });
return;
}
// Email
User.findOne({
email: req.body.email
}).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (user) {
res.status(400).send({ message: "Failed! Email is already in use!" });
return;
}
next();
});
});
};
checkRolesExisted = (req, res, next) => {
if (req.body.roles) {
for (let i = 0; i < req.body.roles.length; i++) {
if (!ROLES.includes(req.body.roles[i])) {
res.status(400).send({
message: `Failed! Role ${req.body.roles[i]} does not exist!`
});
return;
}
}
}
next();
};
const verifySignUp = {
checkDuplicateUsernameOrEmail,
checkRolesExisted
};
module.exports = verifySignUp;
\ No newline at end of file
module.exports = {
secret: "SPM-secret-key"
};
\ No newline at end of file
// for now its empty
\ No newline at end of file
const config = require('../config/auth.config');
const db = require('../modules');
const User = db.user;
const Role = db.role;
var jwt = require("jsonwebtoken");
var bcrypt = require('bcryptjs');
exports.signup = (req, res) => {
const user = new User({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8),
number : req.body.number
});
user.save((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (req.body.roles) {
Role.find(
{
name: { $in: req.body.roles }
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = roles.map(role => role._id);
user.save(err => {
if (err) {
res.status(500).send({ message: err });
return;
}
res.send({ message: "User was registered successfully!" });
});
}
);
}
else {
Role.findOne({ name: "user" }, (err, role) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = [role._id];
user.save(err => {
if (err) {
res.status(500).send({ message: err });
return;
}
res.send({ message: "User was registered successfully!" });
});
});
}
});
};
exports.signin = (req, res) => {
User.findOne({
username: req.body.username
})
.populate("roles", "-__v")
.exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (!user) {
return res.status(404).send({ message: "User Not found." });
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({
accessToken: null,
message: "Invalid Password!"
});
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400 // 24 hours
});
var authorities = [];
for (let i = 0; i < user.roles.length; i++) {
authorities.push("ROLE_" + user.roles[i].name.toUpperCase());
}
res.status(200).send({
id: user._id,
username: user.username,
email: user.email,
roles: authorities,
number: user.number,
accessToken: token
});
});
};
\ No newline at end of file
exports.allAccess = (req, res) => {
res.status(200).send("Public Content.");
};
exports.userBoard = (req, res) => {
res.status(200).send("User Content.");
};
exports.adminBoard = (req, res) => {
res.status(200).send("Admin Content.");
};
exports.studentBoard = (req, res) => {
res.status(200).send("Student Content.");
};
exports.managerBoard = (req, res) => {
res.status(200).send("Manager Content.");
};
\ No newline at end of file
const Video = require('../modules/video.model');
const create = async (req, res) => {
if(req.body) {
const videoPayload = new Video(req.body);
await videoPayload.save()
.then(data=>{
res.status(200).send({data: data});
})
.catch(error =>{
res.status(500).send({error: error.message});
});
}
}
const getAll = async (req, res) => {
await Video.find({})
.populate('name')
.then(data=>{
res.status(200).send({data: data});
})
.catch(error =>{
res.status(500).send({error: error.message});
});
}
const getById = async (req, res) => {
if (req.params && req.params.id) {
await Video.findById(req.params.id)
.populate('name')
.then(response => {
res.status(200).send({ data: response });
})
.catch(error => {
res.status(500).send({ error: error.message });
});
}
}
const updateById = async (req, res) => {
const id = req.params.id;
const {name} = req.body;
const updateVideo = {
name
}
await Video.findByIdAndUpdate(id, updateVideo)
.then(() => {
res.status(200).send({status: "Updated"})
}).catch((err) => {
console.log(err);
res.status(500).send({status: " Error", error:err.message});
})
}
const deleteById = async (req, res) => {
const id = req.params.id
await Video.findByIdAndRemove(id).exec()
res.send("Deleted");
}
module.exports = {
create,
getAll,
getById,
updateById,
deleteById,
}
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
db.user = require("./user.model");
db.role = require("./role.model");
db.ROLES = ["student", "admin", "manager", "user"];
module.exports = db;
\ No newline at end of file
const mongoose = require("mongoose");
const Role = mongoose.model(
"Role",
new mongoose.Schema({
name: String
})
);
module.exports = Role;
\ No newline at end of file
const mongoose = require("mongoose");
const User = mongoose.model(
"User",
new mongoose.Schema({
username: String,
email: String,
password: String,
number: Number,
roles: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Role"
}
]
},{timestamps: true})
);
module.exports = User;
\ No newline at end of file
const mongoose = require('mongoose');
const VideoSchema = new mongoose.Schema({
name: {
type: String,
required: true,
min: 2,
max: 450
},
});
module.exports = mongoose.model('videos', VideoSchema);
\ No newline at end of file
const { verifySignUp } = require("../middlewares")
const controller = require('../controllers/auth.controller');
module.exports = function(app) {
app.use(function(req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});
app.post(
"/api/auth/signup",
[
verifySignUp.checkDuplicateUsernameOrEmail,
verifySignUp.checkRolesExisted
],
controller.signup
);
app.post("/api/auth/signin", controller.signin);
};
const { authJwt } = require('../middlewares');
const controller = require("../controllers/user.controller");
module.exports = function(app) {
app.use(function(req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});
app.get("/api/test/all", controller.allAccess);
app.get("/api/test/user", [authJwt.verifyToken], controller.userBoard);
app.get(
"/api/test/student",
[authJwt.verifyToken, authJwt.isStudent],
controller.studentBoard
);
app.get(
"/api/test/manager",
[authJwt.verifyToken, authJwt.isManager],
controller.managerBoard
);
app.get(
"/api/test/admin",
[authJwt.verifyToken, authJwt.isAdmin],
controller.adminBoard
);
};
\ No newline at end of file
const express = require('express');
const router = express.Router();
const controller = require('../controllers/video.controller');
module.exports = function () {
router.post('/', controller.create);
router.get('/', controller.getAll);
router.get('/:id', controller.getById);
router.put('/:id', controller.updateById);
router.delete('/:id', controller.deleteById);
return router;
}
\ No newline at end of file
pip install fastapi
pip install "uvicorn[standard]"
uvicorn main:app --reload
Ready Made Swagger Doc
http://127.0.0.1:8000/docs
http://127.0.0.1:8000/redoc
\ No newline at end of file
# services and controller file
\ No newline at end of file
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: Optional[bool] = None
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
\ No newline at end of file
# model and DB area
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment