Open In App

User Management System Backend

User Management System Backend includes numerous endpoints for performing user-dealing tasks. The backend could be constructed with the use of NodeJS and MongoDB with ExpressJS . The software will offer an endpoint for consumer management. API will be capable of registering, authenticating, and controlling customers. In this article we will be building the backend of the User Management System.

Preview of final output: Let us have a look at how the final output will look like:



Backend Options

Prerequisites:

Approach to create User Management System Backend:

Functionalities:

Steps to create User Management System:

Step 1: First, we will initiate the Node project using below command. Go to project folder and run below command.

npm init

Step 2: Install the required dependencies as mentioned below using below npm command.



npm i body-parser express mongoose nodemon

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.18.2",
"mongoose": "^8.0.3",
"nodemon": "^3.0.2"
}

Example Code : Write the following code in index.js file.




//index.js
 
const express = require('express');
const bodyParser = require('body-parser')
const app = express();
const mongoose = require('mongoose');
const port = 5000;
 
app.use(bodyParser.urlencoded({ extended: false }))
 
app.use(bodyParser.json())
 
main().catch(err => console.log(err));
 
async function main() {
    await mongoose.connect(<YOUR CONNECTION STRING MONGODB>);
}
 
        const userSchema = new mongoose.Schema({
            name: String,
        username: String,
        age: Number,
        email: String,
        phone: String,
        password: String
})
 
        const User = mongoose.model('user', userSchema, 'usermanagement');
 
        function authenticate(requser, user){
    if(requser.password === user.password)
        {
        return true;
    }
        return false;
}
 
 
 
app.get('/', (req, res) => {
            res.send("Welcome To User Management Backend");
})
 
app.options('/',(req,res)=>{
            res.send({
                "GET": {
                    '/': "returns API home",
                    '/getusers': "returns all users"
                },
                "POST": {
                    '/register': "register user",
                    '/authenticate': "authenticates user"
                },
                "PUT": {
                    '/updateuser': "update specified user"
                },
                "DELETE": {
                    '/deleteuser': "deletes specified user"
                },
                "OPTIONS": {
                    '/': "Backend Options"
                }
            })
        })
 
app.get('/getusers', async (req, res) => {
    const users = await User.find({ });
        res.send(users);
})
 
app.post('/register', async (req, res) => {
    var userdata = req.body;
        var user = new User(userdata);
 
        await user.save().then(function (user) {
        if (user) {
            console.log(user.name + " saved to user collection.");
        res.send({
            status: 200,
            message: "User "+user.name+" Created Successfully" });
        }
    }, function (err) {
            console.log(err);
        res.send({status: 500, message: "Internal server error" });
    });
})
 
app.post('/authenticate', (req, res) => {
    var requser=req.body;
 
        User.where({username: requser.username }).findOne().then((user) => {
        if (user) {
            if(authenticate(requser ,user))
        {
            res.send({ status: 200, message: "Authorized" });
            }
        else
        {
            res.send({ status: 401, message: "Not Authorized" });
            }
        }
        else {
            res.send({ status: 500, message: "User Not Found" });
        }
    }).catch(function (err) {
            res.send({ status: 500, message: 'Internal Server Error' });
    });
})
 
app.put('/updateuser', async (req, res) => {
    var userdata = req.body;
 
        User.where({username: userdata.username }).findOne().then((user) => {
        if (user) {
            User.where({ username: userdata.username })
                .updateOne({
                    name: userdata.name,
                    age: userdata.age,
                    email: userdata.email,
                    phone: userdata.phone,
                    password: userdata.password
                   }).then(function (user) {
                if (user) {
                    User.where({ username: userdata.username })
                        .findOne().then((user) => {
                        res.send({
                            status: 200,
                            newuser: user,
                            message: "User Updated Successfully"
                        });
                    })
                }
            }, function (err) {
                console.log(err);
                res.send({ status: 500, message: "Internal server error" });
            });
        }
        else {
            res.send({ status: 500, message: "User Not Found" });
        }
    }).catch(function (err) {
            res.send({ status: 500, message: 'Internal Server Error' });
    });
})
 
app.delete('/deleteuser', async (req, res) => {
    var username = req.body.username;
 
        User.where({username: username }).findOne().then((user) => {
        if (user) {
            User.where({ username: username })
                .deleteOne().then(function (del) {
                if (del.deletedCount === 1) {
                    res.send({
                        status: 200,
                        message: "User Deleted Successfully"
                    });
                }
            }, function (err) {
                console.log(err);
                res.send({ status: 500, message: "Internal server error" });
            });
        }
        else {
            res.send({ status: 500, message: "User Not Found" });
        }
    }).catch(function (err) {
            res.send({ status: 500, message: 'Internal Server Error' });
    });
})
 
app.listen(port, () => {
            console.log("Server started at port" + port);
})

Steps to run the application :

Now open terminal and run below command in project folder.

nodemon index.js

Final Output:


Article Tags :