Business logic structure in mongoose and restify - node.js

I'm having a lot of trouble figuring out how to organize my business logic in mongoose. I'm pretty new to MongoDB and still trying to figure out everything.
So, I'm trying to achieve what socialite from Laravel does, I need to login with Facebook, check if the user is already registered, if it is, just login, if it's not, then register with the info from facebook.
I created a providerAccount and a user model. The providerAccount is the schema with the Facebook ID and userId relation, the user is the user's schema with all the fields I need.
I tried to create a createOrGetUser() static in the user's schema, which should do exactly what I said earlier, the problem is I just don't know how to properly write this function nor if this is the correct place to write it.
Should I require() the providerAccount inside my user model and keep chaining the queries and ifs or there is a better way to do this kind of logic?
Thanks!

Related

Clean Architecture: how to properly authenticate users

I am making a project using Express and Nodejs.
I am learning how to implement learning how to implement clean Architecture properly.
I've made so far a Entity whose is a Balance (income/outcome).
But, in order for a particular user to be able to insert a new Balance, it's needed to be logged in.
So, in the Controller, I am receiving a Request which has a body with the income data and headers with the authorization token.
This controller makes the validations and forward the body as a DTO to the CreateBalanceUseCase.
My problem is that when i reach the CreateBalanceUseCase, I should call the data-access in order to save the data on the Database. But, the authorization token should be validated calling the AuthorizationDataAcess in order to find a user with same authorization token. But doing so, I violate the Clean Architecture I guess, right? Because I am trying to access the data-acces of the Authorization(aka User) inside the BalanceUseCase.
Also, on my database, I have a 1-n relation of the UserId with the Balance. So I can know what balance belongs to what user. So, also in order to save a Balance, I need to get the userId.
My second approach was create a Express Middleware that authorize the client and returns a userId, so whatever I must do through the app that needs authorization, It must use this middleware.
The problem is that I must access the data-access layer on the presentation layer
Whats the best practice in this situation? Or am I getting the Clean Code Architecture all wrong?
If there is any code or something else I could do to clarify more my question, feel free to comment it out.
Best regards.

I need to use a function to check if a uid already exists in the database before the user is created

I'm building an application, and I have everything set up and working properly. I did some modifications, using rand-token, to have shorter ID's for user profiles, comments, and posts.
I am able to put the randomly generated token into the new ID field (uid for users), but I'm stuck trying to figure out where to put a function to check whether or not the uid already exists in the database before passport writes to the database. I haven't tried to test it by putting a static string in where the random token is generated to see if mongo or passport automatically error out if two ID's exist.
So I guess this is a multi part question.
1) Where exactly could i put a function to check to see if a uid exists before writing to the db?
and
2) Does mongo or even passport do this automatically? I couldn't find documentation for this scenario.
I'm sorry if this is a duplicate post, I've looked at other similar posts but couldn't find anything that is similar to what I need.
Also its worth noting that I'm not talking about a username. I'm talking about uid, separate from username and _id.
its solved. mongo errors out if multiple ids' exist

Different user schemas in mongo db with mongoose js

I have different types of users(admin, employe, user) in my mongo db and I wanted to ask what the best strategy is to handle this scenario.
1)Should I use mongoose schema extend so I can query on just one schema type(for example at registration) ?
2)Should I handle every user type for it self?
3)Is there a better solution you would recommend ?
4)Would you save permissions for each user type in the db or in a config file?
I guess the question is basic, but since I dont have any kind of experience on this field I am glad to get some good advise from you guys :)
It kind of depends what you want to do.
If users can have different sets of properties, I would suggest using a separate model per user type, and splitting your database into different collections per user type. I don't have experience with mongoose schema extend so I couldn't really comment on that, but it seems to be made for this scenario.
If you have roles that you also need to account for, and that you want to store in the database (e.g. for easy configuration and changes later on), perhaps you should look into a relational database because in this case you're talking about relations (between the user and the roles) and MongoDB isn't really the best choice for that.
If you don't need to store the user roles in your database (e.g. if they're hardcoded in your application) and your users don't have different properties, you could simply add a usertype property to your user model, and just check which value it has wherever you need it in your application.
Disclaimer: I'm no MongoDB expert, this is just from my own experience :)

PassportJS authentication and mongodb database collection best practices?

I am working in a project and actually the first time using nodejs, express and mongodb. For the authentication i am using passport.js which look pretty flexible and easy to integrate it.
I really like the idea of Serializing and Deserializing but my concern is about the user object which is always ON and can be used on every request.
My project involve subscriptions, user profile and maybe a small ticked system.
So my user schema it contains user credentials, user info like address, phone, email and also information about the subscription. Some of this information is embedded documents with in same schema. It seems weird that all this info is always ready even i do not needed, even the bcrypt password is always on the request call.
My question is, do you think is best practice to separate the user credentials from the user object and play with relationships soi can call the user info when i need it with normal controller model way?
Thanks in advance
if you are referring to sessions you should really only be sending a small piece of data with the request such as a user id. The entire user document should not be going across with every request.
It's common practice to separate user credentials from the rest of the user data, because the credentials need to be stored in a very secure manner - so much so that it dictates different infrastructure.
I work at Stormpath and we provide this as a service. We store the password for you, with very high levels of encryption. We have a great integration for Express, you check it out here:
https://github.com/stormpath/stormpath-express

Express.js and Mongoose model relationships - in model or router?

Building a REST API with Express.js and Mongoose on node - I have stumbled upon a code design issue - where should I handle relationships - in models or routers?
First, I am pretty new to the MVC and such, and even though express.js is not a full MVC, I would like to follow best design practices.
The issue is rather easy - the app has users, each user can have multiple documents (projects, orders, etc). Obviously I have to at least store the user ID for every document that is created. The question is - where should I do that?
I can get the user ID from the session in each router and attach it to a document, or I can just set the current user ID to a global variable, for example app.currentUserID and use that in my model to attach the ID to the document.
There are actually more interesting cases, where a user can have multiple organizations, and I have to set the organization ID for each document that the user creates when operating with a specific organization.
So the question is: should I handle this kind of logic in my router (express does not have 'controllers' as such) or model?
Do it in the model. Even if you're not creating an enforced relation, storing the actual ID of a related object still changes the model, so there's no reason to leave the logic in the router.
MongoDB (and Mongoose) doesn't have referential integrity like relational databases do. This means that the database will not give you an error if you insert a relation to an object which doesn't exist. It lets the application code handle those relations.
Mongoose is an attempt to bring structure to an otherwise pretty liberal nosql DB. As such, it offers an ability to create such relations with the ObjectId schema type.
Read the following SO answer for more info: https://stackoverflow.com/a/7813331/1801

Resources