A high-level step-by-step tutorial on how to create an API with a role-based authorization system using Node.js and MongoDB:
- Set up a Node.js project: Create a new directory for your project and run
npm init
to initialize a new Node.js project. Then, install the required dependencies:
cssnpm install express body-parser jsonwebtoken bcrypt
Create a database: You can use any database of your choice, but in this tutorial, we will use MongoDB. Install and set up MongoDB on your local machine or use a cloud-based service like MongoDB Atlas.
Define the user schema: Create a new file called
user.js
and define the user schema using Mongoose:
javascriptconst mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
role: {
type: String,
enum: ['admin', 'user'],
default: 'user'
}
});
module.exports = mongoose.model('User', userSchema);
- Set up the API routes: Create a new file called
routes.js
and define the API routes using Express:
javascriptconst express = require('express');
const router = express.Router();
const UserController = require('./controllers/user.controller');
router.post('/register', UserController.register);
router.post('/login', UserController.login);
router.get('/users', UserController.getUsers);
module.exports = router;
- Define the controller methods: Create a new file called
user.controller.js
and define the controller methods for user registration, login, and getting users:
javascriptconst bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const UserController = {};
UserController.register = async (req, res) => {
try {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const user = await User.create({ username, password: hashedPassword });
res.json(user);
} catch (error) {
res.status(500).json({ error: 'Something went wrong' });
}
};
UserController.login = async (req, res) => {
try {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (!user) {
return res.status(401).json({ error: 'Incorrect username or password' });
}
const isPasswordCorrect = await bcrypt.compare(password, user.password);
if (!isPasswordCorrect) {
return res.status(401).json({ error: 'Incorrect username or password' });
}
const token = jwt.sign({ username }, 'secret_key');
res.json({ token });
} catch (error) {
res.status(500).json({ error: 'Something went wrong' });
}
};
UserController.getUsers = async (req, res) => {
try {
const users = await User.find({}, { password: 0 });
res.json(users);
} catch (error) {
res.status(500).json({ error: 'Something went wrong' });
}
};
module.exports = UserController;
- Set up the role-based authorization middleware: Create a new file called
auth.js
and define the role-based authorization middleware using Express and JWT:
javascriptconst jwt = require('jsonwebtoken');
const auth = (roles) => {
return (req, res, next) => {
try {
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, 'secret_key
No comments:
Post a Comment
Thanks for your comments