I'm using MEAN Stack. I made login/signup and profile page. I'm saving user id in cookies and now I want to send my id in server.
I'm getting my id from cookies like that:
userId = $cookies.get('userId')
How can i send this information to server ? I must find this information in DB with id like that:
var userId = "receivedId";
User.UserModel.findOne({ _id: userId }, function(err, data) {
var User = {_id: data._id, user: data.user, date: data.date};
res.send(User); //I know how to send from server to client.
});
Please, check your web server documentation. If you're using express, you'll have to configure cookie-parser middleware first. After that you'll be able to access client cookies using req.cookies. – Leonid Beschastny
answers author is: Leonid Beschastny
thank you. it works!
Related
Hi i am trying do a very simple backend where admin can modify other users account but its not working. I understand this is happening because parse has some default security settings that does not allow this. Below is the code snippet from the update route of the web app:
//UPDATE ROUTE
router.put("/:id", function(req, res){
var Users = Parse.Object.extend("User");
var query = new Parse.Query(Users);
// find and update the correct user
query.get(req.params.id).then(function(user) {
user.set("name", req.body.name);
user.save().then(function(doctor) {
console.log("user has been updated");
res.redirect("/doctors/"+ req.params.id);
}, function(error) {
console.log(error.message);
});
}, function(error) {
console.log("user could not be retrieved!");
});
});
The Error Message is : Cannot modify user HeFxUOj7q9. HeFxUOj7q9 is the Objectid for the user which i am trying to update from another account(admin account)
I have an admin account already created on the parse server User class but I can't figure out how to update other accounts using the admin account. I am using parse server on nodeJs. I would really appreciate any help offered. Thanks in advance.
When you're initializing parse, you should include the masterKey and call useMasterKey like so:
Parse.initialize("YOUR_APP_ID", "YOUR_JAVASCRIPT_KEY", "YOUR_MASTERKEY");
Parse.serverURL = 'http://YOUR_PARSE_SERVER:1337/parse';
Parse.Cloud.useMasterKey();
However, be wary of doing this for endpoints that are publicly accessible, and never include your master key on a client-side application.
I am new to node js and tried passport for authentication, i found it hard to understand the work flow.
so my question is what is actually req.user where it came from ?
is it something constant related to passport and can't be changed to anything else like req.profile ?
Secondly in the following html code
<p>
<strong>id</strong>: <%= user._id %><br>
<strong>username</strong>: <%= user.local.username %><br>
<strong>password</strong>: <%= user.local.password %>
</p>
From where html is populating user object, neither my database schema nor my passport contain the word user
This is my database schema
local:{
username : String,
password : String
}
Thanks
I'll show you where req.user comes from without using passport. First thing you need to understand is a middleware in express is just a function that takes in request, response and a next function.
let's say I have an endpoint:
POST /auth/login that takes a username and password.
This endpoint could return an access token (random string generated by you and stored on the database, if you don't want to store on your database you could look into JWT).
Ok, now that you have that access token after login success.
You can pass it along with other requests to your server.
Let's say another endpoint:
GET /auth/profile which is protected and only can be access with the right access token.
But what is protecting the route? It's a middleware.
Below we define a checkAuth middleware.
function checkAuth(req, res, next) {
// here I can retrieve accessToken from the request header
const accessToken = req.get('accessToken')
// with this accessToken I can query the database and check if this access token is correct or not
findUserWithTheAccessToken(accessToken)
.then(user => {
if (user) {
// Here's the answer to your question where `req.user` comes from.
req.user = user
next() // call next() so it can go to the request handler
} else {
throw new Error('Invalid access token.')
}
})
}
// then your router would look something like the following
router.get('/auth/profile', checkAuth, handler) // implement your handler ☺️
You can always check express website to learn more.
passport=> Passport is authentication middleware for Node.js. and its easy to implement.
login page send username and password to passport.
It will check with your database which is configured by you.
get success then the passport will store user details into req session form that you can retrieve it wherever you want by using your req
I'm trying to create a private messaging system using socket.io
In order to associate the users with their sockets, most sites are suggesting something like this:
var people = {};
client.on('connection', function(socket) {
//join the server
socket.on('add user', function(user_id) {
//create user-socket map
people[user_id] = socket.id;
});
});
In my opinion, the problem with the above code is that the user_id is sent from the client side, so if the user somehow modify it and send another user_id an impersonation will take place.
Also, I can't access req.user._id under client.on('connection'... so how am I supposed to get the user_id from the server's side? I'm using node.js, passport and express.
I would use jsonwebtoken and socketio-jwt modules for solving this security issue.
Server:
var secret = 'shhhhhh';
app.get('/getJWT', function(req, res) {
/* Do your authentication here using header and get the userId */
var userId = 'someId';
var jwt = require('jsonwebtoken');
var token = jwt.sign({ 'userId': userId }, secret);
res.json({
token: token
});
});
var socketioJwt = require('socketio-jwt');
io.use(socketioJwt.authorize({
secret: secret,
handshake: true
}));
io.sockets.on('connection', function (socket) {
var userId = socket.decoded_token.userId;
/* your logic */
Client:
var token = "token you got from the /getJWT"
var c = io.connect('http://localhost:3000/', { query: "token=" + token });
As the token is encoded with a secret, client cannot change and send it.
Refer this article to know why this is better.
You're missing the most important part... Your code has to verify the usr is who he says he is. Plain and simple. I've done this multiple ways:
If users are logging in via PHP code, I move the session data to a mysql database. I then use a string on the PHP side to generate a response for a challenge to the client, who sends it to my web socket server. The WS server will challenge the client and look up the session information in the mysqldb. Done.
In my more recent developments, the actual login process is done via the web socket server. I verify the user credentials via whatever DB (in my instance, MySQL) and tie the username to the socket. Finished...
Do not purely rely on the javascript-based site to say "My name is." Otherwise, as you said, user impersonation becomes a walk in the park. You MUST validate that the user is who he says he is IF you're implementing a system where that matters. "Web sockets" themselves are not magical components that do this for you.
var people will be accessible on the same process.
When you want to scale with multiple socket server and balancing between them, then this idea for keeping people object locally will be not helpful.
Create authenticate event for authentication and set socket.userId and socket.isAuthenticate = true flag. In other events if socket.isAuthenticate is false, kick them out.
Make use of 'socket.io-redis' adpater for communication among many socket.io server. ( So when user1 from server1 send message to user2 which is in server2, will work ).
For socket - user association with multiple process, you can join Room with their userId, on authentication, join room like socket.join('myuserId');
and when to send message to that user, you can use io.to('myuserId').emit('message', "Hi How are you?"):
you can Send additional data on socket connection like this:
client side :
var c = io.connect('http://localhost:3000/', { query: "userId=value01" });
server side :
// extract userId param from connected url
io.on('connection', function(socket) {
var socket_param_userId = socket.handshake['query']['userId'];
console.log(socket_param_userId); //show value01
});
I'm building a website that makes use of Facebook connect. I'm authenticating users client-side with the javascript SDK and calling an AJAX method on my server every time a user logs in to check if the user is known to my app, and if the user is new to store their FBID in my database to register them as a new user.
My question is: Can the access token returned by Facebook to the Javascript SDK be used server-side (with the PHP SDK for example)? Can I send the access token string to the server via an AJAX call, store it in my database (along with a timestamp so I know how long it's valid for) and then use it to make calls to the graph API server-side? Is this even a logical thing to do?
Yes, this should work. Look at this question: How to properly handle session and access token with Facebook PHP SDK 3.0?
This is a workaround for the old JS and new PHP SDK. In my app I send the access token generated by the JS SDK via a form to my PHP. I have no doubts that this also works by sending the access token via ajax!
Using Jquery:
//Set an error message
var oops = ("Put your something went wrong message here.");
//Function to post the data to the server
function save(uid, accessToken){
$.post("../foo/bar", { uid: uid, access_token: accessToken, etc, etc }, function(data){
alert("Successfully connected to Facebook.");
location.reload();
}, "text");
}
function handler(x){
if (x.authResponse){
var token = x.authResponse.accessToken;
var uid = x.authResponse.id;
FB.api("/me/accounts", {access_token: token},
function(response){
if(response.data.length == 0) {
//Regular facebook user with one account (profile)
save(uid, token);
}else{
//Handle multiple accounts (if you want access to pages, groups, etc)
}
});
}else{
alert(oops);
}
}
FB.login(handler, {scope: 'The list of permissions you are requesting goes here'});
Any improvement suggestions are always appreciated.
I can't quite figure this out one... I have a SMTP server that's hosted on the same network as me, I can ping it and attempt to send emails, but the actual email never comes through. I'm using node_mailer... During the callback no error is returned... There is no authentication on the server as it's only used internally, and I'm not sure if that's maybe part of the problem. It works via ASP, but I'd like to get it working with Node.js
My script is basically just this:
email.send({
host : "theaddressoftheserver(can ping)",
port : "25",
domain : "theaddressoftheserver(can ping)",
to : "Some#internalEmail.com",
from : "Some#internalEmail.com",
subject : "Test",
body: "Test"
},
function(err, result){
if(err) console.log(err);
else console.log("Appears to have sent...");
});
I would recommend you to use Postmark.
Postmark helps small and large web applications deliver and track transactional email. Stop worrying about setup, delivery, and server maintenance. We already excel at this.
There are already two Postmark libraries for Node.js.
Postmark.js by Chris Williams
node-postmark by David Pitman
Example
var postmark = require("postmark")("YOURAPIKEY");
postmark.send({
"From": "donotreply#example.com",
"To": "target#example.us",
"Subject": "Test",
"TextBody": "Test Message"
});
I recently answered a similar question, it might help you:
https://stackoverflow.com/a/12623787/340736
Unfortunately, it's kind of hard to know exactly where your problem lies. Is the ASP-script on the same server? Have you tried running telnet against the server and sending it manually? Do the Node process have firewall restrictions?
One thing that comes to mind is that if you say that your ASP-script works, and that your SMTP-server uses no authentication. But could it be that is is, and that it is impersonating your user (the user in which the ASP-process is running under) and authenticating with that (AD authentication)..
Just a wild guess.
I figured node_mailer to send emails from a gmail account. I used code,
const transporter = createTransport({
service: gmail,
auth: {
user: process.env.MAILADDRESS,
pass: process.env.MAILPASSWORD
}
});
let mailOptions = {
from: process.env.MAILADDRESS,
to: recipient#email.com,
subject: 'verification code for verify email',
text: 'verification code
}
transporter.sendMail(mailOptions, function(err, info){
if (err) {
// something
} else {
// something
}
})
This is simple. In order to make this work I had to make sure Gmail account's Less secure app access on before using that email. I'm talking about the email that I user to send email. (Sender's email).
So my point is if there is any security option in your SMTP server that's hosted on your same network, you need to turn it off in order to node_mailer to use email address.