Basically I am coding a bot for this website which requires logging into your steam account and I am unsure of why this does not work as I am using the request module in node.js to send a request to the login page which once your username and password are entered it should redirect to the site and then I can do what I want to do next. Currently the code I provided below shows "Upload successful!" when run but if I put in an invalid username and password it still is successful which I would like to change which I am unsure of how to make the request fill the input field of the form and complete the form.
I have looked at other posts on Stackoverflow but haven't found any that have worked/are the same area I need.
const express = require('express')
const app = express()
const port = 3000
app.listen(port, () => console.log(`Listening at http://localhost:${port}`))
var urlWithLoginForm = 'https://steamcommunity.com';
var loginUrl = urlWithLoginForm+'/openid/login?openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.return_to=https%3A%2F%2Fapi.entertoroll.com%2Fauth%2Fsteam%2Freturn&openid.realm=https%3A%2F%2Fapi.entertoroll.com';
var formData = {'username': 'your_username', 'password': 'your_password'};
request(urlWithLoginForm, function() { // initialising cookies by doing http get
// so now we have cookies in jar, now we can make post request
request.post({url: loginUrl, formData: formData}, function(err, res, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful!');// Server responded with:', body);
app.get('/', (req, res) => res.send(body))
});
});
The part where it puts it on localhost was just for my testing so I could see if it got the page correctly/what the request looks like live.
Related
I'm new react and nodejs and full stack development in general. I'm trying to make a login page in nodejs/react/mysql. Right now, I'm just trying to do get request for the main login page. I think I'm struggling with connecting the front and backend and the moment.
Nodejs app.js:
const express = require('express');
const bodyparser = require('body-parser');
const cors = require('cors');
const app = express();
const mysql = require('mysql');
let connection = mysql.createConnection({
//Connection is encrypted for security reasons.
host: '***********',
user: '***********t',
password: '***********',
database: '***********'
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.listen(3001, () => { console.log('running on port 3001'); });
app.use(cors());
app.use(express.json()); a
app.use(bodyparser.urlencoded({extended: true}));
app.get('/', (req, res) => { res.send('respond with a resource'); });
componentDidMount() react code/fetch request:
componentDidMount() {
// GET request using fetch with error handling
fetch('/')
.then(async response => {
const data = await response.text();
// console.log(data);
console.log('test',data);
// check for error response
if (!response.ok) {
// get error message from body or default to response statusText
const error = (data && data.message) || response.statusText;
return Promise.reject(error);
}
this.setState({ totalReactPackages: data.total })
})
.catch(error => {
this.setState({ errorMessage: error.toString() });
console.error('There was an error!', error);
});
}
My sql connection works fine, I think it's an issues connecting the front end and backend. Changing following line:.
const data = await response.text();
to:
const data = await response.json();
Returns the following error:
There was an error! SyntaxError: Unexpected token < in JSON at position 0
This is the html it returns in the following screenshot:
Once I figure out how to connect the front end and backend the rest of the project should be easyish to do. The react UI work and my SQl connection works fine. Any help would be greatly appreciated.
You're currently fetching data from the primary site, not the Node.js site you've created.
You should change the fetch to:
fetch('http://localhost:3001')
Additional information
The response you are sending from the backend isn't JSON:
res.send('respond with a resource');
To send JSON, you should use:
res.json({ message: "respond with a resource" });
Then you'll be able to use:
const data = await response.json();
And access the data via:
const message = data.message;
For me it worked just by appending "Https://" to the beginning of the API url.
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${CITY_NAME}&appid=${API_KEY}`)
It took me days and 10s of articles/SO threads to figure out that when doing dev on your local machine the fetch request gets routed to local html document.
Restify redirect does'nt work
I have login page, when user enters email and password. If data is correct, he should redirect to another page. But it's not working.
const restify = require('restify')
var server = restify.createServer()
server.listen(8080, function () {
console.log('%s listening at %s', server.name, server.url)
});
server.post('/login/:email/:password', function (request, response, next) {
const email = request.params.email
const password = request.params.password
if (authentication.credentialsIsCorrect(email, password)) {
response.redirect('https://www.google.com', next)
// response.redirect('/index.html', next)
// response.redirect('localhost:8080/index.html', next)
return
}
})
There is no errors of exceptions. It's just dont redirect
You can do it from frontend after you get a sucess status of 200.
Currently, I have run into an issue that I've been stuck on all day. In essence, I am trying to get a login session for an account through the Roblox authentication API. It works the first when I post from my server to their API so that I can get the X-CSRF-TOKEN which needs to be set in the headers for the next time I make a post to the same API so I am able to get the .ROBLOSECURITY which is used to authenticate that the account session. However, the second time I post to their API with the token in the header, I get a 400 error and I am unsure of why this is occurring.
Also, for anyone who is wondering, it is returning a valid X-CSRF-TOKEN.
var request = require('request');
var loginOptions = {
url: 'https://auth.roblox.com/v2/login',
form: {
'ctype': 'Username',
'cvalue': 'AccountUsernameHere',
'password': 'AccountPassGoesHere'
},
headers: {
'Content-Type': 'application/json'
}
};
request.post(loginOptions, function(error, response, body) {
loginOptions.headers['X-CSRF-TOKEN'] = response.headers['x-csrf-token'];
request.post(loginOptions, function(error, response, body) {
if (response.statusCode == 200) {
console.log('Success: ' + body);
} else {
console.log(response.statusCode + ' : ' + response.statusMessage);
}
});
});
You need install cors in nodejs: npm install cors, you can try the following below
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
It appears there were two issues with my code.
The first issue is that I was using form when I should have been using body. I also ended up needing to add json: true too.
I am using Mongoose and nodejs to write an API.
My users.js looks as follow:
var express = require('express');
var router = express.Router();
var user = require('../models/users.js');
router.post('/',function(req, res, next) {
console.log("made a post");
var user2 = new user(); // create a new instance of the Bear model
user2.firstName = req.body.firstName; // set the bears name (comes from the request)
user2.lastName=req.body.lastName;
user2.email=req.body.email;
user2.save(function(err) {
if (err)
res.send(err);
console.log("User created");
});
})
//The model acts as our user object...this returns all users.
.get('/', function(req, res, next) {
console.log("sending a get request");
user.find(function(err, users) {
if (err)
res.send(err);
res.json(users);
});
})
module.exports = router;
When I send a get request, it works perfectly. However, I am now trying to develop the POST request. I send a request such as the following:
http://localhost:4000/users?firstName=Han&lastName=Bo#email=haBo#yah.com
and I receive the following in my console:
sending a get request
GET /users?firstName=Han&lastName=Bo#email=haBo#yah.com
200 15.522 ms - 1365
And I receive the output of my GET request in the browser.
I'm new to node and would appreciate some help with this.
Thanks.
You are putting your parameters as URL parameters, while your POST API reads parameters from body of request.
Here is explanation of POST parameters.
Also, if you are not already using it, use postman to send requests.
I'm trying to set up a web server using express. To access this server, users have to authenticate and for that, I use the basicAuth() middleware provided by Express. It works perfectly, except that I do not know how to log out once I logged in ! I have to close my browser to disconnect, but instead I would like to have a "disconnect" page which would redirect towards the "login" page (this one with the hideous form used to log in...).
Does anyone has an idea ?
Thanks per advance
PS : I apologize for my pathetic English :)
Express' basicAuth uses HTTP Basic Authentication whose implementation doesn't need HTML pages, cookies nor session ids. Its main drawbacks are its not secure and, our concern here, there is no mechanism in the spec for the server to instruct the browser to log out.
express.basicAuth() calls require(blah-blah/connect/lib/utils).unauthorized() which sends a 401 status with header 'WWW-Authenticate: Basic realm="..."'. The browser handles the authentication window and from then on sends a header like 'Authorization: Basic YmFzaWM6YmFzaWM=' which contains the username and password.
(express.basicAuth is not secure, especially over HTTP, because you can get the username:password with
new Buffer('YmFzaWM6YmFzaWM=' , 'base64').toString()
which gives basic:basic in this case.)
Our problem is the HTTP spec does not provide a way to stop that header being sent. A workaround for HTTPS is to redirect the user to a URL on the same domain having incorrect credentials.
The HTTP workaround I use for Express V3 can be used with app.use(express.basicAuth(...)). I find this easier to use than other solutions which require a call to middleware in every secured route, e.g. app.get('/secure', checkAuth, function (req, res) {...}).
Here is a working example.
var express = require('express'),
http = require('http'),
app = express();
app.use(express.favicon()); // prevent interference during test
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'winter is coming' }));
app.use(function (req, res, next) {
if (!req.session.authStatus || 'loggedOut' === req.session.authStatus) {
req.session.authStatus = 'loggingIn';
// cause Express to issue 401 status so browser asks for authentication
req.user = false;
req.remoteUser = false;
if (req.headers && req.headers.authorization) { delete req.headers.authorization; }
}
next();
});
app.use(express.basicAuth(function(user, pass, callback) {
callback(null, user === 'basic' && pass === 'basic');
}, '***** Enter user= basic & password= basic'));
app.use(function (req, res, next) {
req.session.authStatus = 'loggedIn';
next();
});
app.use(app.router);
app.get('/secure', function (req, res) {
res.send([
'You are on a secured page.',
'<br>',
'Refresh this page without having to log in again.',
'<br/>',
'Log out.'
].join(''));
});
app.get('/logout', function (req, res) {
delete req.session.authStatus;
res.send([
'You are now logged out.',
'<br/>',
'Return to the secure page. You will have to log in again.',
].join(''));
});
http.createServer(app).listen(3000, function(){
console.log('Express server listening on port 3000. Point browser to route /secure');
});
P.S. Your English is excellent.
For express.js 4 and basicAuth, you can use this method:
app.get('/logout', function (req, res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.sendStatus(401);
});
Adding to wyllman, the 401 code is Unauthorized.
You can simply respond with res.status(401).send('Logged out')
or
app.get('/logout', function (req, res) {
res.status(401).send('Logged out')
//or res.status(401).end() if you don't want to send any message
});
I've confirmed that redirecting the user to a /logout page with an http code 401 and html with <a> element links to /login works.