Check whether or not a user is admin - node.js

I'm trying to make it so that when a user has admin he should have access to the router. But unfortunately, it does not work, I'm getting an error that isAdmin is not defined, but I have it in the database.
function isAdminLogged(req, res, next) {
if (req.User.isAdmin==="true") return next();
res.redirect('/admin');
}
//ROUTES
app.get('/admin', isAdminLogged, (req, res) => {
res.render("admin", { title: "Admin Area" });
})
Also, I would love to make it when a user is an admin he can see a div in an index.hbs
<div class="home">
<h1>Home</h1>
Logout
</div>
{{#if user.isAdmin}}
<div>
<h1>Hello Guys</h1>
</div>
{{/if}}
I'm new to express and I'm trying my best to understand, thank you in advance!

I have built authentication, and using mongodb but EJS template instead of Handlebars. I think if you go through it then that will help you a lot.
Here is the link to my repo CAMP.
The information that you have provided may be not sufficient to solve your issue from my side.

Related

How to res.render/send a variable after a redirect?

I want to send a message variable that says something like succeeded or failed wihtout the use of passport or sessions.
When it fails I can just do this:
res.status(401).render('register', {
message: 'Your username/email or password is incorrect.'
})
So I was thinking this was possible:
res.redirect('/');
res.render('', { message: 'Login success.'});
But it turns out it isn't:
Error: Cannot set headers after they are sent to the client
Are there any simple sollutions?
I tried making a router.get('/message/redirect :route') but I realised I ran into the same problem there too.
You are redirecting before rendering. So the render method can't send headers because you have already redirected them. You need to call either redirect or render, not both at once. you can do it like this.
res.render('/', { message: 'Login success.'});
remove this line
res.redirect('/');
In your EJS file just call <%= message %> to access the message. There is a better way of dealing with confirmation/error messages. Use Flash.
npm install express-flash
Then before rendering, call the flash. Flash takes two arguments, a name of the message and the message itself, Like this
req.flash("MessageName", "Login success");
res.redirect(pathName);
Make sure to use flash
const flash = require('express-flash');
app = express();
app.use(flash());
app.use((req, res, next) => {
res.locals.MessageName= req.flash("MessageName");
next();
});
To access the message in EJS file just call <%= MessageName %>
Here is sample from my code:
In the server file:
req.flash("error", "Something went wrong");
res.redirect('back');
In the EJS file:
<div class="flash">
<% if(error && error.length > 0){ %>
<div class="flash_error">
<h1 class="flash_error--text"><%= error %></h1>
</div>
<% } %>
</div>
Read this for more information

How to create a custom path in URL using nodeJS/expressJS

I'd like to be able to create a custom path. for example, if a user clicks a button [create room], the browser redirects the user to: http://www.example.com/[room_id]/index.html
Is there anyway to implement this? The user would be submitting a form, with a button. something along those lines.
basically here is what i have
index.html
<form method='POST' name='path_id' id='clickedButtom'>
<input id="pickName" class="center-align" type='text'>
<input id='rea2dy' value=" Ready >" type='submit'>
</form>
server.js
app.get('path_id', function(req, res) {
res.send('hello');
});
//I was the path_id to be a random string of letters and numbers basically
For all the URLs you're talking about, you can define a single Express route in advance like this that will have code inside the route to look at the room id and act accordingly:
app.post('/createRoom, (req, res) => {
// do whatever you do here to create the room data structure on the server
// and assign it an ID
let roomID = ...;
res.redirect(`/${roomID}/index.html`);
});
app.get('/:roomID/index.html', (req, res) => {
let roomID = req.params.roomID;
// now render whatever you want the user to see for this particular room
res.send(...);
});

Cannot POST /addfriend error using Express

I am trying to create a simple form handler using express. Here is a similar question but I can't related it with my problem. I have written all of my file Here anyone can check it by using all of my file. For better understanding I copy my code here:
app.js code:
const express = require('express');
const app = express();
//routes
app.get('/',function(req,res){
res.send('This is root dir');
});
app.get('/friends',function(req,res){
var friends=['sakib','emon','rayhan'];
res.render('friends.ejs',{friends:friends});
});
app.get('/addfriend',function(req,res){
res.send('ADD friend page launch!!!!!');
});
app.listen(3000,function(){
console.log("server has started on port 3000!!!");
});
ejs(friends.ejs) code:
<h1>Here is list of your Friend:</h1>
<%friends.forEach(function(friend){%>
<li><%=friend%></li>
<%});%>
<form action="/addfriend" method="POST">
<input type="text" name="friend" placeholder="name">
<button>
Submit
</button>
</form>
When I type any name in the input box and clicked Submit it didn't post to /addfriend. I didn't understand where is my problem. Please goto input box(link) after started the server.
For better understand what's my actual problem is then please use goorm IDE(shared file) where I uploaded everything.
You are using get request instead of post for addfriend.
app.post('/addfriend',function(req,res){
console.log("I'm called wohoo!");
res.send('ADD friend page launch!!!!!');
});

Passing req.user to template not working with ejs and express

I am using EJS and Express to take and check if the current user exists and if not show one thing instead of the other. My issue is that I am setting req.user to res.locals.currentUser but it is not passing through to the template so I can output it as well as check if it exists.
in my app.js
app.use(function(req, res, next){
res.locals.currentUser = req.user;
next();
});
my ejs file
<% if(!currentUser){ %>
<li>Login</li>
<li>Sign Up</li>
<% } else { %>
<li>Signed In As <%= currentUser.email %></li>
<li>Profile</li>
<li>Logout</li>
<% } %>
This evaluates always to false therefore showing the first section of the if statement.
What is wrong here to make it so I can't test or see the user data in my ejs view? When I console.log the currentUser is returns undefined.
Some information that might be important, I am using a redis session store instead of mongo store. I also am using body-parser not cookieparser.
I was facing the same issue while using Passport in node.js with ejs templating.
The solution is to place it below the passport lines of code( that is serialize and deserialize).
These functions are responsible for saving the user to "req.user", and thus if the app.use is placed above it, the code won't work as req.user is null until this.
Adios

what is use of router and model in loopback

hello guys i m new to loopback so can anyone help me with this basic. i had created a some code but don't know how this flow (from route to model)
here is route.js code for login
var path = require('path');
module.exports = function(app) {
app.get('/', function(req, res) {
res.render('login');
});
app.post('/login', function(req, res) {
//from here i should go to login model
});
};
here is my login.ejs
<form action="/login" method="post">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<input type="submit" name="" value="Submit">
</form>
now my question is that how i can use login model from route.js (url is like "login") i know i can use this type as describe below in route.js but i want that first it go to router and from then i go to login model more description eg it go through "/login" route from there it go to login model where i want to add insert login after that if it response success then it go to "/home" else it go to "/"
"var User = app.models.user;"
i what something like this in user.js (model)
module.exports = function(User) {
//here i want to accept login form method and insert it into dataabase
};
or this is not possible or it is incorrect way i don't know much so please help
what is different between if i use business login in router and model i m new so please help.
First go to the loopBack documentation and read it carefully how to create models and its control flow , surely you will get clear picture
https://loopback.io/doc/en/lb2/Project-layout-reference.html

Resources