S
S
Slava1912019-10-11 20:08:10
JavaScript
Slava191, 2019-10-11 20:08:10

How to prevent unauthorized users from CREATE and DELETE operations in mongodb?

I am writing an application in Node.js. I want to make sure that only users authorized in the system can add data to some collections (authorization using the passport-local strategy).
For example, there is a collection of user questions "questions". A question can only be added by a user logged in to the system.
Now I do the following: Before each request I write if(!ctx.isAuthenticated()) return;
It looks like this:

//страница обрабатывающая запрос

const Questions = require('../../models/questions.js');

exports.post = async (ctx, next) => {

if(!ctx.isAuthenticated()) return;

const insertedQuestion = new Questions({
text:ctx.request.body.text
})

ctx.body = await  insertedQuestion.save()

}

//questionsSchema

const mongoose = require('../libs/mongoose');

const questionsSchema = new mongoose.Schema({
    text: String,
})

module.exports = mongoose.model('Questions', questionsSchema);

I am haunted and do not leave the feeling that such a task should be solved somehow differently, for example, to proxy the save () operation and check if the user is authorized there. What is the best way to solve this kind of problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Adel Khalitov, 2019-11-02
@adelkhalitov

There is too much in one module, passport js will authorize hang up sessions, acl will do the rights, work out the logic in it. The passport has an isAutentificate method, add it to the routes as middleware, make routes in general, separate the logic. What kind of nonsense and not code?)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question