😊Users Me Route
Snippets and good practices for users
User me Route
router.get('/me', auth, UserController.me);Explanation
HTTP Method:
GETEndpoint:
/meMiddleware:
authThis middleware ensures the request is authenticated before proceeding.
Controller:
UserController.meThis method in the UserController handles the business logic for this route.
User me Controller
me ControllerThis method checks for the presence of an authenticated user in the request object. If the user is authenticated, it fetches the user data from the database, removes the password for security, and sends the user data in the response. If the user is not authenticated or if any error occurs, it sends the appropriate error response.
Controller Method
import bodyParser from 'body-parser'; // Import body-parser for parsing request bodies
import express from 'express'; // Import express for creating the server
import cors from 'cors'; // Import cors for enabling Cross-Origin Resource Sharing
import helmet from 'helmet'; // Import helmet for securing the app by setting various HTTP headers
import morgan from 'morgan'; // Import morgan for logging HTTP requests
// Defining the Express app
const app = express();
// Adding Helmet to enhance APIs security
app.use(helmet({
crossOriginEmbedderPolicy: false,
crossOriginOpenerPolicy: false,
crossOriginResourcePolicy: false,
}));
// Middleware to handle JSON parsing with a limit of 10mb
app.use((req, res, next) => {
if(req.originalUrl.startsWith('/raw')) {
next();
} else {
express.json({
limit: '10mb',
})(req, res, next);
}
});
//app.use(bodyParser.json({ limit: '10mb' }));
//app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));
//app.use(express.json());
// Enabling CORS for all requests
app.use(cors());
// Adding morgan to log HTTP requests in the 'combined' format
app.use(morgan('combined'));
// Custom respond method to standardize API responses
app.response.respond = function({
data = {},
result = 'success',
status = 200,
message = '',
props = {},
} = {}) {
const jsonResponse = {
result,
status,
data,
message,
};
// If props is an object, merge it with jsonResponse
if(typeof props === 'object') {
Object.assign(jsonResponse, props);
}
// If the status is not 2xx, set result to error
if(status < 200 || status > 299) {
jsonResponse.result = 'error';
}
return this.contentType('application/json')
.status(status)
.send(jsonResponse);
};
export default app;Controller Method
/**
* Retrieves the authenticated user's information.
*
* This method checks for the presence of an authenticated user in the request object.
* If the user is authenticated, it fetches the user data from the database, removes
* the password for security, and sends the user data in the response. If the user is
* not authenticated or if any error occurs, it sends the appropriate error response.
*
* @param {Object} req - The request object.
* @param {Object} res - The response object.
* @returns {void}
*/
static async me(req, res) {
try {
if(!req.user || !req.user.payload || !req.user.payload.id)
return res.respond({ status: 401, message: 'Unauthorized' });
// Get user from req
const signedUser = req.user.payload;
const user = await UserService.findById(signedUser.id);
if(!user) return res.respond({ status: 404, message: 'User not found' });
// delete password
delete user.password;
return res.respond({
data: user,
message: 'User retrieved successfully',
});
} catch(e) {
return res.respond({ status: 400, message: 'User me error: ' + e.message });
}
};Breakdown
Authorization Check: The function first checks if the
req.userobject and its necessary payload are present. If not, it responds with a401 Unauthorizedstatus and exits.Extract User Data: If the authorization check passes, it extracts the signed user data from
req.user.payload.Fetch User from Database: It then attempts to find the user in the database using the
UserService.findByIdmethod, passing the user's ID.User Existence Check: If no user is found, it responds with a
404 User not foundstatus and exits.Remove Sensitive Information: If the user is found, it removes the
passwordfield from the user object to ensure sensitive information is not exposed.Respond with User Data: Finally, it responds with the user data and a success message.
Error Handling: If any error occurs during the process, it catches the error and responds with a
400 User me errorstatus, including the error message.
This function ensures that only authorized users can retrieve their information while protecting sensitive data and providing appropriate error handling.
Last updated