Check Authentication on Creating Post

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 321:- Check Authentication on Creating Post

To check authentication on creating a post, we can use the ensureAuthenticated middleware that we have previously created. This middleware checks if the user is authenticated or not. If the user is authenticated, it will call the next function to continue with the request. Otherwise, it will redirect the user to the login page.

Here's an example of how we can use the ensureAuthenticated middleware to protect the create post route:

javascriptCopy code

const express = require('express'); const router = express.Router(); const { ensureAuthenticated } = require('../config/auth'); // GET request for creating a new post router.get('/new', ensureAuthenticated, (req, res) => {  res.render('posts/new'); }); // POST request for creating a new post router.post('/', ensureAuthenticated, (req, res) => {  // Code for saving the new post to the database }); module.exports = router;

In the above code, we are using the ensureAuthenticated middleware as the second argument to both the GET and POST routes. This ensures that only authenticated users can access these routes. If an unauthenticated user tries to access these routes, they will be redirected to the login page.

37. Database Relations (Posts, Comments)

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support