Skip to content
Permalink
Browse files
Json schema validation
  • Loading branch information
ryklovae committed Feb 3, 2023
1 parent 945f7ba commit be9e1e5875bb80d91c24d153eb6d900577b40979
Show file tree
Hide file tree
Showing 12 changed files with 165 additions and 8 deletions.
@@ -1,3 +1,5 @@
node_modules/

config.js

.env
@@ -0,0 +1,30 @@
const {Validator, ValidationError} = require('jsonschema');
const v = new Validator();


exports.makeKoaValidator = schema => {
return async (ctx, next) => {
// define the controller here
// using the passed-in schema to validate against

const validationOptions = {
throwError: true,
allowUnknownAttributes: false
};

const body = ctx.request.body;

try {
v.validate(body, schema, validationOptions);
await next();
} catch (error) {
if (error instanceof ValidationError) {
ctx.body = error;
ctx.status = 400;
} else {
throw error;
}
}

}
}
@@ -9,6 +9,15 @@ const fetchPromise = fetch('https://kiwipanel-gravitycrater-3000.codio-box.uk/ap
});
fetchPromise.then(res => res.json()).then(res => console.log(res))

const fetchPromise = fetch('https://kiwipanel-gravitycrater-3000.codio-box.uk/api/v1/articles', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({title: "new post", allText: 'content', authorID: 1})
});
fetchPromise.then(res => res.json()).then(res => console.log(res))

const fetchPromise = fetch('https://kiwipanel-gravitycrater-3000.codio-box.uk/api/v1/articles', {
method: 'GET'
});
@@ -55,7 +55,7 @@ exports.getById = async function getById (id) {
/*let query = "SELECT * FROM articles WHERE ID = ?";
let values = [id];
let data = await db.run_query(query, values);*/
let data = Article.findAll({
let data = await Article.findAll({
where: {
ID: id
}
@@ -74,7 +74,7 @@ exports.getAll = async function getAll (page, limit, order) {
let data = await db.run_query(query);
return data;*/

let data = Article.findAll()
let data = await Article.findAll()

return data;
}
@@ -52,14 +52,21 @@ sequelize.sync().then(() => {

//get a single user by the (unique) username
exports.findByUsername = async function findByUsername(username) {
const query = "SELECT * FROM users WHERE username = ?;";
const user = await db.run_query(query, username);
/*const query = "SELECT * FROM users WHERE username = ?;";
const user = await db.run_query(query, username);*/

let user = await User.findAll({
where: {
username: username
}
});

return user;
}

//get all users
exports.getAll = async function getAll() {
let data = User.findAll()
let data = await User.findAll()
return data;
}

Some generated files are not rendered by default. Learn more.

@@ -14,6 +14,7 @@
"license": "ISC",
"dependencies": {
"bcrypt": "^5.1.0",
"jsonschema": "^1.4.1",
"koa": "^2.14.1",
"koa-bodyparser": "^4.3.0",
"koa-passport": "^5.0.0",
@@ -2,12 +2,13 @@ const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const model = require('../models/articles');
const auth = require('../controllers/auth');
const validator = require('../controllers/validation');


const schema = require('../schemas/article.schema.js');
const router = Router({prefix: '/api/v1/articles'});

router.get('/', auth, getAll);
router.post('/', bodyParser(), createArticle);
router.post('/', bodyParser(), validator.makeKoaValidator(schema), createArticle);
router.get('/:id([0-9]{1,})', getById);
router.put('/:id([0-9]{1,})', bodyParser(), updateArticle);
router.del('/:id([0-9]{1,})', deleteArticle);
@@ -2,11 +2,14 @@ const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const model = require('../models/users');

const schema = require('../schemas/user.schema.js');
const validator = require('../controllers/validation');

const router = Router({prefix: '/api/v1/users'});

router.get('/', getAllUsers);
router.get('/asd', updatePassword);
router.post('/', bodyParser(), createUser);
router.post('/', bodyParser(), validator.makeKoaValidator(schema), createUser);
router.del('/:id([0-9]{1,})', deleteUser);

async function getAllUsers(ctx) {
@@ -0,0 +1,35 @@
module.exports = {
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "/article",
"title": "Article",
"description": "An article in the blog",
"type": "object",
"properties": {
"title": {
"description": "Main title of the blog article",
"type": "string"
},
"allText": {
"description": "Body text of the blog article",
"type": "string"
},
"summary": {
"description": "Optional short text summary of article",
"type": "string"
},
"imageURL": {
"description": "URL for main image to show in article",
"type": "uri"
},
"published": {
"description": "Is the article published or not",
"type": "boolean"
},
"authorID": {
"description": "User ID of the article author",
"type": "integer",
"minimum": 0
},
},
"required": ["title", "allText", "authorID"]
}
@@ -0,0 +1,34 @@
module.exports = {
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "/user",
"title": "User",
"description": "A user of the blog",
"type": "object",
"properties": {
"username": {
"description": "Username",
"type": "string"
},
"email": {
"description": "User's email",
"type": "string"
},
"firstName": {
"description": "User's first name",
"type": "string"
},
"lastName": {
"description": "User's last name",
"type": "string"
},
"password": {
"description": "User's password",
"type": "string"
},
"about": {
"description": "Information about the user",
"type": "string",
},
},
"required": ["username", "email", "password"]
}
@@ -0,0 +1,21 @@
var JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;

var opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'secret';


passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({id: jwt_payload.sub}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
// or you could create a new account
}
});
}));

0 comments on commit be9e1e5

Please sign in to comment.