res render does not render the index.jade - node.js

I build an authentication method in Node which use Azure AD. I use h here fore the "javascript quickstart" template which Microsoft offers. The Goal is that the user(s) start with the login screen. When they successful authenticate with Azure AD then they will redirect to the landing page.
All works accept loading the landing page(index.jade).The user is still on the same page after authentication.
Below code which is responsible to render the (or redirect) the landing page
exports.login = function(req, res){
console.info('Check on User')
var user = req.body.user
if(user){
console.info('user exist')
console.info(user)
console.info('now render the index page jade')
//res.render('../views/index')
res.redirect('../views/index')
}
The location of the index file is "{projectlocation}/views/index.jade" The folder location where the redirect/render take place is "{projectlocation}/routes/login.js".
Below output of the code:
Check on User
user exist
{
'#odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/$entity',
displayName: 'username',
givenName: 'user',
jobTitle: '',
mail: 'user#user.com',
mobilePhone: '',
officeLocation: '',
preferredLanguage: 'nl-NL',
surname: 'user',
userPrincipalName: 'user#user.nl',
id: '666666-bbb-4444-5555-8tt874yy60oo'
}
now render the index page jade
POST /Aanmelden 200 239.783 ms - -
GET /views/index 404 0.829 ms - 31
I also try base on the comments to change the res.render to res.redirect
see the below code. Now i get some more output but still not the desire result.

Related

How to convert my Wordpress website to flutter application?

I am a college student and during my intern my client gave me this project to convert his wordpress website into a mobile application while including existing features as well as some new features. The website is news website. I am also provided with wordpress admin panel credentials.
However, I am having hardtime fetching all data of website in json form. I tried using the wordpress api url: "https://example.com/wp-json/wp/v2/posts" as well as
"https://example.com/wp-json/wp/v2/posts?perpage=100" and
"https://example.com/wp-json/wp/v2/posts/?filter[limit]=100"
but none of them provided with whole data, it only rendered 10 latest news posts.
I am looking to get whole access to the website data myself. Is there any possible way for that? I want comments from the users on that news post, number of shares, likes, the related news section below post, everything.
Do I have to ask for the organization's main api or is there any other way? I am fluent in flutter and node js.
Flutter WordPress
Flutter WordPress is a library that allows for easy communication between a Flutter app and the WordPress backend. It uses WordPress REST API v2 for this interaction.
If your app is going to make use of authentication or other admin level APIs then the developer recommends you use these two authenthentication wordpress plugins:
Application Passwords
JWT Authentication for WP REST API (recommended)
How to use Flutter WordPress
1.Go to your pubspec.yaml then add the following as a dependency:
flutter_wordpress: ^0.1.4
You can check for the latest version here.
2.Import it in your code:
import 'package:flutter_wordpress/flutter_wordpress.dart' as wp;
3.You instantiate WordPress:
wp.WordPress wordPress;
// adminName and adminKey is needed only for admin level APIs
wordPress = wp.WordPress(
baseUrl: 'http://localhost',
authenticator: wp.WordPressAuthenticator.JWT,
adminName: '',
adminKey: '',
);
4.You then authenticate the user:
Future<wp.User> response = wordPress.authenticateUser(
username: 'ChiefEditor',
password: 'chiefeditor#123',
);
response.then((user) {
createPost(user);
}).catchError((err) {
print('Failed to fetch user: $err');
});
5.Here's how you can fetch wordpress posts and show them in your flutter app:
Future<List<wp.Post>> posts = wordPress.fetchPosts(
params: wp.ParamsPostList(
context: wp.WordPressContext.view,
pageNum: 1,
perPage: 20,
order: wp.Order.desc,
orderBy: wp.PostsOrderBy.date,
),
fetchAuthor: true,
fetchFeaturedMedia: true,
fetchComments: true,
);
6.And here's how you can fetch users:
Future<List<wp.User>> users = wordPress.fetchUsers(
params: wp.ParamsUserList(
context: wp.WordPressContext.view,
pageNum: 1,
perPage: 30,
order: wp.Order.asc,
orderBy: wp.UsersOrderBy.name,
role: wp.UserRole.subscriber,
),
);
7.And here's how to fetch comments:
Future<List<wp.Comment>> comments = wordPress.fetchComments(
params: wp.ParamsCommentList(
context: wp.WordPressContext.view,
pageNum: 1,
perPage: 30,
includePostIDs: [1],
),
);
8.Then creating a wordpress post via flutter is easy:
void createPost(wp.User user) {
final post = wordPress.createPost(
post: new wp.Post(
title: 'First post as a Chief Editor',
content: 'Blah! blah! blah!',
excerpt: 'Discussion about blah!',
author: user.id,
commentStatus: wp.PostCommentStatus.open,
pingStatus: wp.PostPingStatus.closed,
status: wp.PostPageStatus.publish,
format: wp.PostFormat.standard,
sticky: true,
),
);
post.then((p) {
print('Post created successfully with ID: ${p.id}');
postComment(user, p);
}).catchError((err) {
print('Failed to create post: $err');
});
}
Then to post a comment:
void postComment(wp.User user, wp.Post post) {
final comment = wordPress.createComment(
comment: new wp.Comment(
author: user.id,
post: post.id,
content: "First!",
parent: 0,
),
);
comment.then((c) {
print('Comment successfully posted with ID: ${c.id}');
}).catchError((err) {
print('Failed to comment: $err');
});
}
Download full example here.

I want send user info except password from the express server along with jwt token

I'm creating a MERN stack ecommerce application where I want send all user info along with jwt token but except password I'm ok with token part & I know how to send user but i don't know how to exclude the password property while sending the user through res.json
enter image description here
Modified Answer -
#prathamesh
You can change the default behavior at the schema definition level using the select attribute of the field:
password: { type: String, select: false }
Then you can pull it in as needed in find and populate calls via field selection as '+password'. For example:
Users.findOne({_id: id}).select('+password').exec(...);
You can use the aggregation or select method in the mongoose.
const users = await User.find({}, {name: 1, email: 1});
or
const users = await User.find({}).select("name email");
or
const users = await User.aggregate([{"$project": {name: 1, email: 1}}]);
I use this way to save all attributes except password in another variable and then I show info.
let {password, ...foundUser} = user.toJSON();
response.setStatus(200).setRes(foundUser);

Security level access nodejs and passport

I am currently making a Timecard system for employees to use at the job I work at (just to make things a little less chaotic) and I would like to have regular users and managers. My basic structure that I want to achieve is this for the Schemas:
User
---name
---password
---isClockedIn
---phoneNumber
---isManager
--if isManager == true
--deleteUser
--addUser
--etc
Now, the current User schema I have is this:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = mongoose.Schema({
username: String,
password: String,
first_name: String,
middle_initial: String,
last_name: String,
phone: Number,
isManager: Boolean,
isLoggedIn: Boolean,
points_accrued: Number
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
I am not sure if I should add an extra schema for the Admin permissions or really how to go about giving a regular user that type of access.
Now for my routes, I want the user (Employee) and the Admin to see pretty much the same view, except the manager will have some additional links that will allow his to see all users, delete them, change timecards ect.
for now this is what my routes look like:
//INDEX SHOW USER INFO
router.get("/", middleware.isLoggedIn, middleware.isManager, function(req, res){
User.find({}, function(err, currentUser){
if(err){
console.log("error occured");
console.log(err);
} else {
res.render("users/index", {user: currentUser});
}
});
});
And then my middleware is going to look like this:
middlewareObj.isManager = function(req, res, next){
if(req.isAuthenticated() && req.isManager === true){
//Load Page for admins view example: see all employees clocked in and admins timesheet
return next();
} else {
//Load Page to only show current Users timesheet
return next();
}
now this begs the question, would it be better and more fluid for the first page to be the same for both user and admin (like show generic time info for that particular employee) and the if the user is an admin have a link show up that only they can access to make any low level changes, OR have the admin see all of that data on his homepage without clicking on a different link?
And further more, how can I make my middleware tell the route, and then the route tell the html (ejs in my case) what to show and what not to display.
I appreciate it and thank you!
For the first ask i think is only a business logic, so depend of you what you want. For experience i prefer the first way in case of small projects becouse is more fast to implement (show/hide element of same page), for complex projects can be usefull do also a different page only for the admin.
For the second ask, you can simply put a condition, assume, like your example, you pass the user to ejs.
<% if (user && user.isManage) { %>
<button>Admin button</button>
<% } %>

Internationalize nodejs jade templates

I'm trying to internationalize my nodejs express app using i18n-2 module. All is working but I have a question. Is there a way to translate string from my jade templates. Imagine I have 100 strings in my website. Do I have to send 100 translations to the template through the res.render invocation?
res.render('profile', {
title: 'My cool title',
user: req.user,
hello1: req.i18n.__("hello1"),
hello2: req.i18n.__("hello2"),
hello3: req.i18n.__("hello3"),
...
helloN: req.i18n.__("helloN")
});
Is there another way to do this? Somethin like the next code:
res.render('profile', {
title: 'My cool title',
user: req.user,
i18n: req.i18n // to be used inside jade
});
i18n-2 already registers helper objects in your Express locals, which are accessible form your Jade template. These helper methods are registered automatically: "__", "__n", "getLocale", and "isPreferredLocale". Without any additional configuration, should be able to do the following in your Jade template:
a(href="/") #{ __('home') }

Variables not showing content on Jade template

I am learning Node.js using a book. There was an example that as a learning experience I converted from what it was to a SQL version of it.
This single page is only intended to display user information. I load the user information on a middleware then pass it to the Jade template. Everything working up to this point.
When I want to render the template below, wherever I user content from the user object, it renders nothing.
h1= user.Name
h2 Bio
p= user.Bio
form(action="/users/" + encodeURIComponent(user.User), method="POST")
input(name="_method", type="hidden", value="DELETE")
input(type="submit", value="Delete")
To check if the object was without content, I added this 2 lines on the front
-console.log ( 'Inside Jade' )
-console.log ( user )
and the result in the console is:
Inside Jade
[ { Name: 'Jennifer Lopes',
User: 'jenny',
Password: 'asd',
Bio: 'Actress and singer' } ]
So this tells me that the information is there, but is not being rendered.
The code used to render the template is:
app.get ('/users/:name', loadUser, function ( req, res, next ) {
res.render ( 'users/profile', { title: 'User profile', user: req.user });
});
Can you please help me to understand what am I doing wrong? Thanks in advance.
A little hard to tell without seeing all your code, but per the output of your console it looks like user is actually an array of objects based upon the brackets, if you change your jade template to output something like user[0].Name does it give you your expected values?

Resources