the correct userID to create a forum (onetoMany-Mongoose)

Viewed 54

At the moment I am working on a small app in Node Js. with which a user can create forums. The relationship of user to forum is oneToMany. If the user is not an admin he is not allowed to create a forum. The request checks whether a token is transmitted.

I have prepared the following simple test in a .http file:

POST http://localhost:8080/forum
Authorization: {{adminToken}}
Content-Type: application/json

{
 "forumName": "first forum",
 "forumDescription": "a lovely first forum"
}

UserService.js

const User = require('./UserModel');
const bcrypt = require('bcrypt')



/*CRUD*/
/*----------------------------------------------------------------------------------------*/
/*Create User*/
function createUser(req, res, next) {

    let user = new User({
        userID: req.body.userID,
        userName: req.body.userName,
        password: req.body.password,
        isAdministrator: req.body.isAdministrator
    });
    user.save().then(function() {
        res.send(user);
    }).catch(err => {
        console.log(err);
    });


}
/*Read one User*/

function getByUserId(req, res, next) {

    let userIDD = req.body.userID;
    User.findOne({
        userID: userIDD
    }, function(err, result) {
        if (err) {
            console.log("Fehler bei Suche: " + err)
        } else {
            
            console.log("Alles gut gelaufen.");
            res.send(result)
        }
    })
}
/*Update User*/

function updateUser(req, res, next) {
    let search = req.body.userID;
    let user = User.updateOne({
            userID: search
        }, {
            userID: req.body.userID,
            userName: req.body.userName,
            password: req.body.password,
            isAdministrator: req.body.isAdministrator
        },
        function(err, result) {
            if (err) {
                console.log("Fehler bei Suche: " + err)
            } else {
                console.log("Alles gut gelaufen.");
                res.send(result);
            }
        });

}


/*----------------------------------------------------------------------------------------*/

/*Delete User*/

function deleteByUserId(req, res, next) {

    let userIDD = req.body.userID;
    User.deleteOne({
        userID: userIDD
    }, function(err, result) {
        if (err) {
            console.log("Fehler bei Suche: " + err)
        } else {
            console.log("Alles gut gelaufen.");
            res.send(result)
        }
    })
}

/*Crud End*/
/*----------------------------------------------------------------------------------------*/
module.exports = {
    
    createUser,
    getByUserId,
    
    updateUser,
    deleteByUserId
}

ForumService.js

const Forum = require('./ForumModel');
const userService=require('../user/UserService')





/*CRUD*/
/*----------------------------------------------------------------------------------------*/
/*Create User*/

    function createForum(req, res, next) {
    
        
        
        
     
    
        let forum = new Forum({
            forumName: req.body.forumName,
            forumDescription: req.body.forumDescription,
            //don't know how to get userID
            ownerID: req.body.ownerID
        });
        forum.save().then(function() {
            res.send(forum);
        }).catch(err => {
            console.log(err);
        });
    
    
    }
    
    module.exports = {
        createForum
    }

Forum-Route.js

var express = require('express');
var router = express.Router();

var forumService = require('./ForumService')
var authenticationService=require('../authentication/AuthenticationService')

/*crud-routes*/
/*---------------------------------------------------------------------*/

/*create*/
router.post('/forum',authenticationService.isAuthenticated,forumService.createForum)

module.exports = router;

Forum-Model:

var mongoose = require('mongoose')
const Schema=mongoose.Schema;



const ForumSchema = new mongoose.Schema({

    forumName: {
        type: String
    },
    forumDescription: {
        type: String
    },
    ownerID: {
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    }},{
        timestamps: true
    });

    const Forum = mongoose.model("Forum", ForumSchema);
    module.exports = Forum;

isAuthenticated-Function:

 function isAuthenticated(req, res, next) {
        const bearerHeader = req.headers['authorization'];
      
        if (bearerHeader) {
          const bearer = bearerHeader.split(' ');
          const bearerToken = bearer[1];
          req.token = bearerToken;
          next();
        } else {
          // nicht Admin
          res.status(500).json({ error: "Not authorised." });
        }
      }

My question is: How do I get the UserID to create a Forum ?

Update: I have found an indirect way to assign the ownerID. First it is checked in the req.body if an ownerID is stored. If this is not the case, it is assumed that it is the admin. The admin object is searched in the user database and assigned to the ownerID. If someone knows a more elegant way, please let me know.

Update function createForums

function createForum(req, res, next) {
  
 if(!req.body.ownerID){
     let query=User.findOne({userID: "admin"});
     
    query.exec(function(err,user){
        if(user){
            
       let forum = new Forum({
        forumName: req.body.forumName,
        forumDescription: req.body.forumDescription,
        //don't know how to get userID
        ownerID: user
    });
    forum.save().then(function() {
        res.send(forum);
    }).catch(err => {
        console.log(err);
    });
}})}else{
    let query=User.findOne({userID: req.body.userID});
     
    query.exec(function(err,user){
        if(user){
            
       let forum = new Forum({
        forumName: req.body.forumName,
        forumDescription: req.body.forumDescription,
        //don't know how to get userID
        ownerID: user
    });
    forum.save().then(function() {
        res.send(forum);
    }).catch(err => {
        console.log(err);
    });

}})}}
0 Answers
Related