Dynamic routing performance in node.js with express - performance

I have to create routes of the type /:username in an express application. I can think of two ways for this and i wonder which is more performance optimized. The first is to dynamic serve the route with a call to the db and if the username exists to serve the profile needed. The second one is to create a function, so that when a user is created his profile url is hardcoded into the app and then removed when a user is deleted. This way there won't be calls to the db whenever a url of this type is requested. So the question is what would be the performance problems in the second case, if any and what are the advantages and disadvantages on each case, mainly performance-wise?

Do the first one. I cannot speak towards performance (however I feel that the first will be faster in the long-run), however what happens if your application were to (not saying this would happen) be as popular as Facebook and you then have 1 000 000 000 routes in your express application? Even trying to start your app would get ridiculous.
Databases can handle this, and if you're really worried about it you could keep a cache of the usernames that have already been checked. Add them when you first check it, and delete them if the username is deleted.
It also occurs to me now; will you not have to perform pretty much the same query to get the information to populate the profile anyways? If you are suggesting to create static pages for each profile when the account is created, don't do this. This is what databases were designed for, so it is perfectly safe to use them in this way.

I simply use /:username and i have it below my other routes, so it doesnt' supersede other pages like /login
If there is no user for that username, then I redirect them to the homepage.
Using mongoose, you can do something like this:
//app.js
app.get('/:username', routes.profile.get);
//route handler
User.findOne({ username: req.params.username}, function(err, owner){
if ( !owner ) {
req.flash('error', 'Woops, looks like that account doesn\'t exist.');
res.redirect('/');
}
//do something with owner
});

Related

VueJS SPA dynamic baseURL for axios

I've searched and searched and can't seem to find a pattern for this. I'd consider myself an intermediate Vue dev, however, the backend is my strong suit. I'm working on an app that will be white-labeled by resellers. While it's possible to have multiple builds, avoiding that would be ideal. The setup is a stand-alone vue-cli SPA connecting to a Laravel api backend and using the Sanctum auth package. So I need calls to the same domain. The issue: resellers will be on their own domain. The ask: Is there a pattern/solution for dynamically loading configs (mainly baseURL) for different domains (other items would by theme/stylesheet). Currently I have a few typical entries:
i.e. axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL
Basically, based on the domain the site is being served on, I'd like a dynamic/runtime config. I feel like this has been solved, but I can't seem to use the right search terms for some direction, so anything is helpful. I've tried a few things:
1) Parsing in js, but can't seem to get it to run early enough in the process to take effect? It seems to work, but I can't get it to "click"
2) Hit a public API endpoint with the current domain and get the config. Again, can implement, but can't seem to get it to inject into the Vue side correctly?
Any resources, pattern references or general guidance would be much appreciative to avoid maintaining multiple builds merely for a few variables. That said, I don't think there's much overhead in any of this, but also open to telling my I'm wrong and need multiple builds.
End Result
url visited is https://mydomaincom
then baseURL = https://api.mydomiancom
url visited https://resellerdomaincom
then baseURL=https://api.resellerdomaincom
I don't think there is a common pattern to solve your problem - I haven't found anything on the net.
The best software design solution could be the following:
have a single back-end
distribute only the client to your customers/resellers
Obviously the back end could see the domain of the application from which the request comes and manage the logic accordingly.
Good luck with your project.
Honestly how the question is put it's not really clear to me. Although my usual pattern is to:
Create an axios instance like so:
export const axiosInstance = axios.create({
// ...configs
baseURL: process.env.VUE_APP_URL_YOU_WOULD_LIKE_TO_HIT
})
and then whenever I make a request to some api, I would use this instance.
EDIT: According to your edit, you can either release the client to each customer, and have a .env file for each and every of them, or you can have a gateway system, where the client axios end point is always the same, hitting always the same server, and then from there the server decides what to ping, based on your own logic

Is this issue due to bots?

In our MVC website log I can see lot of errors with message "A public action method was not found". Requests are coming with junk action method name.
For example if I have action name "GetProducts" then requests are coming with actiona name as "GetProducts AND 1=1" , "GetProducts;id'" , "GetProductswhscheck".
is this because of internet bots are trying to access my website with junk values?
It may be bots, it may be script kiddies, or it may be crackers. Either way - somebody is trying to find vulnerabilities on your site.
Let's look at the first one:
GetProducts AND 1=1"
This looks like an attempt at SQL Injection. There was probably a longer query after the "1=1", trying to get information out of your database - like usernames, e-mail addresses, and so on.
To defend yourself, make sure your queries are parameterized. You may also want to add some form of rate-limiting on your system; if possible, see if you can add captchas.
You may also want to look at this answer on Information Security Stack Exchange, and the OWASP top 10 security vulnerabilities.
Do this as soon as possible, because somebody's trying to break in to your system.

Laravel Multi Domain Session

I am not a superb developer, so I guess the problem I did run into is just to big for me.
I have a project where I have different subdomains for the current language. When I login a user it is logged only for the current subdomain. So when I login at "en.Aproject.com", and then go to "de.Aproject.com", the user will not be logged in. They don't share the session. I already tried to modify the 'domain' => null, in app/sessions.php. But when I change the value here the Login doesn't work at all. Then everytime a new Session-row is created in the DB and Laravel seems not to recognize them.
Is the current domain saved somehow in the session identifier? Is it possible to use one session for different domains? I found some stuff about OAuth and Single sign-on but I can not handle it by myself.
I was thinking about (when logging in and the credentials are correct) calling a script via Ajax, which should log in the user for all needed domains. But I would have to do the same for logging out.. And I will probably have a lot of domains. The project will have one base page and several subprojects (all with the different languages). Like this
mainproject.com
en.mainproject.com
de.mainproject.com
...
Aproject.com
en.Aproject.com
de.Aproject.com
...
Bproject.com
en.Bproject.com
de.Bproject.com
...
So it would just feel wrong to log in the user to like 20 different pages and create 20 sessions... It would feel better to just use one session for all of them.
Okay, I hope you understand the problem and someone already had the same problem and found a solution. Thanks!!!!!!!! greets. gerti
Background info.. I am using Laravel 4.2
Now I just tried something, maybe it helps someone. Actually point 2 is weird to me (see below)
I display these 3 things:
Session::getId()
Auth::getName()
var_dump(Session::all())
I display them on "de.Aproject.com". Here I am logged in.
And i display them on "en.Aproject.com"... Where I am still logged out (which I want to fix :D )
The value of Session::getId() is different on both sides. Thats the problem I guess, they should share the same.
The value of Auth::getName() is the same on both sides (login_82e5d2c56bdd0811318f0cf078b78bfc). Which I don't understand. Why does the second page have this value when i am not logged in?
The value of Session::all() is ["login_82e5d2c56bdd0811318f0cf078b78bfc"] => string(17) "test#test.de" on the first site, on the second its empty. Thats correct.
Since the default Laravel authentication system uses cookies to manage the session, you actually need to login the user on each subdomain you're going to use. To avoid that, you can use another session driver like database.

Sessions in Meteor

After a research it seems that Meteor Sessions are reset after refreshing page or opening the website in new tab, i.e. they are not usual server-side sessions but something like global javascript variables on client-side. Some people advice to use AmplifyJS, but I'm not sure that it will work like usual session in other frameworks/languages and also it is a third party library, so is there any normal way to use sessions in Meteor, i.e. keep user-specific data on server?
At this moment I'm handling that by using custom Collections, but it is not an ideal way of doing that because it is needed to remove expired values from Collection manually, which makes additional troubles.
Yes this is correct. Despite the name Session is nothing like a cookie, but just a reactive form of a variable stored in a hashmap
To keep data persistent across tabs you need to use a Collections (as this is the only way to reactively share data across tabs) - Cookies can't work because they can't be made reactive as data needs to be sent to the server to notify the client when there is a change. There really wouldn't be another way at the moment as the publish/subscribe methods can only send down data from collections at the moment.
You can use your setup you have now with your custom collection. You can use a server side cron job to remove expired data (either with Meteor.setInterval or Tom Coleman's cron.
There is a package developed just for that: https://atmospherejs.com/u2622/persistent-session
After installation you can use the following functions to set sessions which are persistent:
//store a persistent session variable which is stored across templates
Session.setPersistent(key, value);
//same as above, but automatically deletes session data when user logs out
Session.setAuth(key, value);
I've tried the package and it works like charm.

Subsonic, SharedDbConnectionScope and ApplicationState

I'm looking at using Subsonic with a multi-tenant ASP.net web application. There are multiple DB's (one per client/instance). The user logs in with a domain suffix to their username (e.g. user#tenant1, user#tenant2).
The custom membership provider will then determine which database a user is using, and authenticate against it. All user-initiated calls in the webapp will be wrapped in a SharedDbConnectionScope call, however I have a question regarding caching subsonic items.
Basically each instance will have a few records that rarely change (search options/configurations). I would like to read these in the Application_Start event, and cache them into the ApplicationState.
In the Application_Start event, it would loop over each client database, use a SharedDbConnectionScope to connect to each DB, and create these cached records (e.g. Application('tenant1_search_obj') = subsonic_object
When a user loads the search page, it would then check what domain a user is in, and then retreive that search option from the cache.
Is this feasible? I'm just concerned that if I cache an object, when I retrieve it from the application cache it won't know what connection its using, and might possibly pull in the wrong data.
I'd like to avoid putting this in the session object if possible.
it's possible, but probably not a good idea since it doesn't scale at all - you're going to pop a new connection for every single client whether they show up or not.
Maybe your best bet is to "lazy load" the setting - first hit on the search page loads the config into the cache or Application settings and there it stays.
Other than that - to answer your question it is possible. If you're using SubSonic 3, just create a new provider on the fly using ProviderFactory.GetProvider(connectionString, "System.Data.SqlClient") and then execute your stuff against it.
For SubSonic 2 - SharedConnectionScope is what you want.

Resources