this is a authentication sequence question. I currently have a website that is hosted with an Express back-end, which manages the routing for both my main website and the API points. For any of my routes, the request has to come with a posted OAuth token for the website, which corresponds to a specific GMail account.
I have a function which checks this token/corresponding email to be authorized to access my website (although auth function is not done, this is not the problem).
function validateUser(token) {
return new Promise(
(resolve, reject) => {
if (!token)
reject("Empty token");
request(
'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' + token,
(error, response, body) => {
console.log(body);
if (error) {
return reject("Error");
} else if (JSON.parse(body)['error_description']) {
return reject(JSON.parse(body)['error_description']);
} else if (body) {
let theDict = JSON.parse(body);
theDict['oauth_token'] = token;
return resolve(theDict);
}
return reject("some other error");
}
);
}
);
}
Then I have a route that manages get requests at any location (which then redirects to the login page, and once user is logged in it posts to the route with the token to get the content).
router.post(
'/*',
(req, res, next) => {
var token = req.body['token'];
validateUser(token).then(
(data) => {
request(
'http://localhost:4200',
(err, remoteResponse, remoteBody) => {
if (err) {
return res.status(500).end('Error');
}
res.send(remoteBody);
}
);
},
(err) => {
res.redirect('/login');
}
);
}
);
Now, the problem here is, whenever I go to the main page of my site (which reverse proxies back to the dev server), loading the index.html file works fine, but obviously loading everything else like "/assets/js" or default Angular 2 files does not work because they are not similarly authenticated.
Is there a way in Angular 2 to send these requests using the same authentication method? I have the oauth token being stored in my Angular 2 application once the index.html is loaded, so maybe I can use that somehow?
Alternatively, I can also setup another API route in Express to load the files from there, but when Angular 2 generates my index.html with the extra script tag for loading vendor.js or other files, can I tell it this new location instead?
Appreciate the help.
In express, you can use serve-static to serve static files, which would take precedence over your /* route. See https://expressjs.com/en/starter/static-files.html for more details.
Note: this assumes your static assets don't require authentication (which they usually don't).
app.use(express.static('public'))
Note: this should be above the block declaring the /* route in order for it to take precendence.
If you script.js file lives in the /public folder, it will be served at the root of the express server.
Related
In the server script I try to deliver different html files. When app.post('/login'...) comes in, res.sendFile() is working and the html gets rendered. On the second call, whenn app.get('/go') comes in, the file gets served, but not displayed. I cannot explain why the second HTML file is not displayed. What am I doing wrong?
the second request comes from a fetch request in a javascript
socket.on('gameStarted', (data) => {
console.log("Game started");
fetch('/go', {method: 'GET'});
})
served but not displayed
app.post('/login', async (req, res, next) => {
var roomNR = req.body.player.gameCode;
var playerName = req.body.player.nickname;
var codeValid = await checkCode(activeRoomsCollection, gameCodes, roomNR);
var playerExists = await playerCollection.findOne({ playerName: playerName })
if (codeValid) {
if ((playerExists === null) || !playerExists) {
playerCollection.insertOne({ room: roomNR, playerName: playerName, state: false });
console.log(`Added player '${playerName}' with roomnumber '${roomNR}'`);
res.sendFile(path.join(__dirname + '/../../public/lobby.html'), function (err) {
if (err) {
console.log(err);
res.status(err.status).end();
}
else {
console.log('Sent Lobby');
}
});
} else {
// updateDomElement(player, elementId, data)
//res.send('Benutzername existiert bereits');
}
} else {
res.send('Code ungültig');
}
});
app.get('/go', (req, res, next ) => {
res.sendFile(path.join(__dirname + '/../../public/raetsel1.html'), function (err) {
if (err) {
console.log(err);
res.status(err.status).end();
}
else {
console.log('Sent Raetsel1');
}
});
});
fetch() never displays anything on its own. It's a way for your Javsascript to issue http requests to remote servers and those servers then return content back to your Javascript. The result from those http requests ONLY goes to your Javascript. Nothing in the view of the page is affected at all by a fetch() call.
If you want the result of a fetch() call to display something in your page, you would need to write Javascript to do that (to insert content into the current page).
If, instead, you just want the browser to go to a new page, then change from this:
fetch('/go', {method: 'GET'});
to this:
window.location = "/go";
This will cause the browser to go to the URL, retrieve the content and display it. This will shut-down the current page and load and display a new page and the URL in the URL-bar in the browser will show the updated location.
Note that if you have socket.io code in both pages, it will disconnect the current socket.io connection and then run the Javascript in the new page - causing it to create a new socket.io connection (if you have code in the new page to do that) as that is what happens to socket.io connections when you load and display a new web page in the browser.
I was learning to build a weather app using Node (Express) + React. I successfully fetched weather data from open weather API.
However I was directly using the open weather API key in my React app like this const weatherURL = 'http://api.openweathermap.org/data/2.5/weather?q=london,uk&APPID=1234567qwerty';. Obviously this is not safe as it exposed the API key to the client. I thought about storing the API key in .env file, but according to [this answer][1], I should never store API key in .env file or .gitignore. The right way is to make a request to backend API and make an API call to backend and send the data back. I could not find out how to do it. Can anyone help?
Following is my node js code:
const express = require('express');
const cors = require('cors');
const app = express();
const SELECT_ALL_QUERY = 'SELECT * FROM `mySchema`.`myTable`;';
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /myTable to see content')
});
const pool = require('./awsPool');
pool.getConnection((err, connection) => {
if (err) {
return console.log('ERROR! ', err);
}
if(!connection) {
return console.log('No connection was found');
}
app.get('/myTable', (req, res) => {
console.log(connection);
connection.query(SELECT_ALL_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
};
});
});
});
let port=process.env.PORT||4000;
app.listen(port, () => {
console.log(`App running on port ${port} `);
});```
[1]: https://stackoverflow.com/a/57103663/8720421
What the linked answer was suggesting is to create a route in your Node/Express backend API that will make the call to the weather API for you, instead of the front end. This way the request and your API key are not public-facing whenever your front end makes a call.
The method for doing this would essentially be the same as what you have done in React, making an HTTP request using a built-in or 3rd party library. This resource I just found has some information on how to do both.
The simplest pure http-request in node looks like this:
const http = require('http')
const url = 'http://api.openweathermap.org/data/'
http.request(url, callback).end()
function callback (weatherResponse) {
let jsonString = ''
weatherResponse.on('data', chunk => {
jsonString += chunk
})
weatherResponse.on('end', () => {
// Now you have the complete response and can do whatever you want with it
// like return it to your user `res.send(jsonString)`
console.log(jsonString)
})
}
Many people find it bulky to having to handle chunks and the whole asynchronous thing, so there are many popular npm modules, like: https://www.npmjs.com/package/axios. (And here's a list of other contenders https://github.com/request/request/issues/3143).
Also, it is normal to store API-keys in environment variables on the backend. It makes things easy if you ever try to dockerize your app, or just scale up to using two backend servers instead of one.
I found a solution based on #ippi answer, add the following part to the original code:
const request = require('request');
const url = 'http://api.openweathermap.org/data/2.5/weather?q=london,uk&APPID=1234567';
app.get('/weather', (req, res) => {
request(url, (error, response, body) => {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body)
res.send(info);
}
})
})
The url can be stored in .env file and passed into the above code. The returned weather data can be viewed in JSON format at http://localhost:4000/weather. In React the weather data can be fetched via this localhost url.
EDIT: request is deprecated, so here is a solution using axios
app.get('/weather', (req, res) => {
axios.get(url)
.then(response => {res.json(response.data)})
.catch(error => {
console.log(error);
});
})
User Passport middleware for nodeJs/Express. They provide passport-headerapikey strategy using which you can create and authorize apiKeys. http://www.passportjs.org/packages/passport-headerapikey/
I am running a Express application with Node in the backend. I have 2 functions in a component in NodeJS which I am trying to access from my service. The link for both are the same in the service. It is able to connect one of the functions from the service.
However, it is showing 404 not found for accessing the second function in the same component. It is strange that the 2 functions from the same service is are giving 2 different responses (1 success and 1 failure).
Has anyone faced any such issue and if so how can it be rectified?
Some code for reference :
component1.component.ts
getallprojectcat()
{
this.authenticationService.getprojectcat()
.pipe(first())
.subscribe(
data => {
this.data = data;
},
error => {
this.loading = false;
});
}
}
component2.component.ts
showprojects(moid)
{
this.authenticationService.getprojectslist(moid)
.pipe(first())
.subscribe(
data => {
this.silver = data;
},
error => {
console.log('some error');
this.alertService.error(error);
this.loading = false;
});
}
the .service file
getprojectcat()
{
return this.http.get<any>(this.studenturl+'/getprojectcata/')
.pipe(map(allprojectcat => {
console.log(JSON.stringify(allprojectcat));
return allprojectcat;
}));
}
getprojectslist(moid)
{
return this.http.get(this.studenturl+'/getprojects/'+moid)
.pipe(map(projectslist => {
console.log("Projects List:"+JSON.stringify(projectslist));
return projectslist;
})).catch(this.handleError);
}
Backend .js file
exports.getprojectcata = function(req, res){
console.log("First Function");
};
exports.getprojects = function(req, res){
console.log("Second Function");
};
The function getprojectcata is working in the first component. However, it shows an 404 not found on the getprojects function in the second component. I have checked the following things -
Routing does not seem to be the problem as it is moving to the next component without any issues.
We have also tried calling the getprojectscata through the same service in component and it worked.
For sencond function use .post in service and backend route also.
As GET requests is only used to request data. And you are passing moid in http.get which gives 404.
In post you can send moid data in params and in backend fetch data as req.params.
I hope it wil help you .
Share your code for better understanding.
I have set up an application with a registration homepage and a few internal pages requiring a login.
I used Node with Express.js to set up the server and controlling the routes and authentication works fine: if I try to access localhost:port/clientPage I get the desired page if I previously logged in and an error message otherwise.
The problem is that if I try to access localhost:port/clientPage.html I get the clientPage even when I have no active session. How can I ensure the same - desired - behaviour previously described also in this case? I attach the code of my GET route to clientPage:
router.get('/clientPage', function (req, res, next) {
User.findById(req.session.userId)
.exec(function (error, user) {
if (error) {
return next(error);
} else {
if (user === null) {
var err = new Error('Not authorized! Go back!');
err.status = 400;
return next(err);
} else {
return res.sendFile(path.join(__dirname + '/../views/clientPage.html'));
}
}
});
});
Since the problem is caused by adding .html to the end of the route that somehow bypassed the authentication route. I think it is highly possible that you have
express.static(path.join(__dirname, "views") at the beginning of your application publicly serving your folder.
Why is it overriding your route?
Express is running middleware sequentially through app.use(...). The statement app.use(express.static...) is placed before app.use(// your router) and the response was resolved to client early.
Using this knowledge you can easily restrict other route by placing an authentication middleware before your route instead of embedding your database call inside each specific route.
app.use(require("./middleware/auth"));
app.use("/homepage", require("./routes/homepage"));
app.use("/clientPage", require("./routes/clientPage"));
When this code hits the redirect line it throws the 'Can't set headers after they are sent error' and doesn't redirect. I'm guilty of not fully understanding headers and how express works with them. This link about this error is confusing me a bit, probably because I don't have a basic enough understanding of what's going on. Also, I know this is a bit of a naive approach to authenticating, but I'm just trying to get basic things to work.
app.post('/api/login', function(req, res) {
if (req.body.password === auth.password) {
auth.date = new Date()
res.redirect('/admin')
} else {
console.log("wrong pw")
}
})
UPDATE : thank you to #Brendan Ashworth I missed an obvious else, which I've added now and no longer get the error.
However this line doesn't change the contents of my page
res.sendfile('./public/admin/views/tunes.html')
It worked before I wrapped it with the auth check
var auth = require('../config/auth')
module.exports = function(app) {
/*
* CONTENT API
*/
//...
/*
* Admin Routes
*/
app.get('/admin/login', function(req, res) {
res.sendfile('./public/admin/views/login.html')
})
app.post('/api/login', function(req, res) {
if (req.body.password === auth.password) {
auth.date = new Date()
res.redirect('/admin')
} else {
res.json({message: 'Wrong password!'})
}
})
app.get('/admin', function(req, res) {
if (auth.date) {
res.sendfile('./public/admin/views/tunes.html')
console.log("test") //
} else { //added else
res.redirect('/admin/login')
}
})
app.get('/admin/:url', function(req, res) {
if (auth.date) {
res.sendfile('./public/admin/views/' + req.params.url + '.html')
} else { //added else
res.redirect('/admin/login')
}
})
// frontend routes
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('./public/views/index.html')
})
}
FINAL UPDATE!! The last thing I needed was to handle the redirect client side after sending the file. Simple authentication works perfectly now!
$http.post('/api/login', $scope.auth).success(function() {
window.location.href = '/admin'
})
An explanation of the error Can't set headers after they are sent error:
All HTTP responses follow this basic structure:
.. Response Line ..
.. Headers ..
.. Body ..
If you want to redirect a user, first the Response Line will be sent with a redirect code (lets say 300), then the Headers will be sent with a Location: xxx header.
Then, we can finally send a body (not in the case of a redirect, but in general). However - in the case with your code - you are sending a Body response then trying to redirect the user. Since the headers (and response line) have both already been sent (because you sent the body), it can't send more headers after the body.
An example of this in your code would be:
app.get('/admin', function(req, res) {
if (auth.date) {
res.sendfile('./public/admin/views/tunes.html')
}
res.redirect('/admin/login')
})
If I'm assuming right, you actually want to return after the res.sendfile() call. If auth.date is truthy, then you'll be sending a file (i.e. body response) and then giving a redirect code - that doesn't work.
after redirect just call res.stop();