How to made Signup and Login Post Request on same Webpage - node.js

I am new in Nodejs and developing a login and signup page. But the thing which is different is I want my login and signup on same post request
and Login Page is
What I next do is in both form I add my action to home page but inside
app.post("/",function(req,res){
});
How will I differentiate between request is sign in or signup.. I want to do on same page and also I did not want to change my Url on browser while doing that

Id recommend separate paths for both, but if still you want to achieve this with single request path. Then you need to add an identifier to differentiate between signup / signin requests.
you can pass it in body of POST request :
{
username: xyz,
password: abc,
reqType: 'login'
}
Once you receive this body at you server, you can just simply check the value of req.body.reqType variable and perform the logic.
You can also pass the unique identifier to differentiate between signup / signin requests as a request header. At server side you can just check for req.headere.reqType and perform the desired actions,

Related

firebase onAuthStateChanged infinite loop node js

I'm using firebase to sign in my users on my node js app. I would like to see if the user is authentificated or not and after it redirect to the page I want (login if it not logged or dashboard).
But when I redirect user (if it not logged previously or session expires) it's looping on the same page (send redirect of the login page everytime when I'm on login page).
My function that I use actually :
function authenficated (req, res, next) {
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
console.log("connected" + " " + user.uid);
next()
} else {
console.log("disconnected")
res.redirect('/') //loop on / page
next()
}
});
}
I would like a function that provides if my user is logged or not, if it logged my node backend return to /dashboard or other pages that I want and if not it cannot access to dashboard and it return automatically to / or /login
I specify I don't use React or Vue, I use simply EJS to display my pages
Thanks for all
This function/sdk is meant for frontend applications and not backend apps. You need to the admin sdk for that. You can use cookies and the admin sdk provides a function to create cookies. After a signin you attach the cookie to the headers and it will be send by the browser on every request. If the cookie header is empty than you know the user isn't signed in. To logout a user you can add a head method to clear the cookie.
To use backend function you need to use the admin sdk. This function is a front end function (web sdk ).
You can use onAuthStateChanged on the front end and redirect them from the front end. Remember onAuthStateChanged will fire on every page load.
OR implement cookies like the previous comments.
OR
Send the id token from the client via http request (fetch or axios) and verify server side using the admin sdk. Here is the specific link. This solution would require you to load something on the front end though and then send a http request to the backend, verify, then send protected resources after.
Cookies on the other hand are sent to the backend with every request, so if no cookie is present on the page load request then obviously there is no user. Or if the below function fails then server wont send protected resources. (this is explained in the link above for cookies)
getAuth().verifySessionCookie(sessionCookie, true /** checkRevoked */)

Express js - how to redirect to new page with new data

Im on the home page and i see a list of names. When I click a name, a post request is sent to the backend. From here, I want to one: load the respective profile data from the database, and two: redirect to the profile page and display that data.
From the research i've done, it seems like I have to create an http session variable and decorate that with my profile data before redirecting to the profile page. Is that the best way to go about this?
my html:
<div class="result" onclick="loadProfile(this)" onmouseover="showActions(this)" onmouseleave="removeActions(this)">
<p id="user-id" style="display:none;"> 123456 </p>
<div class="person-info">
</div>
</div>
my front-end js:
function loadProfile() {
}
how would i write the get request? and send the id as a param?
Querying data should be a GET request, not a POST request. A POST would typically be for adding a new record or in some cases, modifying a record. A GET is for querying existing data. As such, you should be constructing a URL such as:
/profile?id=someName
And doing a GET request. Then you create a route handler for /profile on your server (or whatever you want the URL to be named) and that route handler parses the id value out of the query string in the URL. If you're using request, it would be in req.query.id.
Then, that route handler can use the id value to query the data store and show the appropriate profile page.
No session is needed. No redirect is needed. This is stateless (which is desirable from an http server point of view). Note, this also creates a URL structure where a user can bookmark the profile page or you can link to it directly in HTML.
If you show the client-side HTML/code that is creating your current request, we could advise more specifically on how to create the GET request from it. If you're using an HTML <form>, you can configure the form to create a GET request instead of the POST and to put the data into the query string.
In loadProfile(), you can just construct the URL by fetching the current ID based on the value of this and then just do in loadProfile():
let id = <code to get id from the current HTML, based on the click>
let newURL = `/profile?id=${id}`;
window.location = newURL; // will cause browser to go to that page
Then, construct the appropriate route on the server to handle this URL.

JSON Web Token (JWT) is too long to pass through client URL? Node.js and Express authentication

I am trying to use JWT to authenticate a user's email address. I cannot use OAuth because a user will be signing up with their work email and will need to verify using that.
I have added a field to my User model called isVerified. I have used mailgun to send an email to the user when they go to sign up that includes a link to a verification page in the form of http://{client_url}/verification/{userToken} where the userToken is a generated token using JSON web token.... the token is created using only the user's id so there is not a lot of information in the payload.
When the user clicks on this link, they are getting a 404 Not Found error. When I manually shorten the userToken in the url, then it properly connects to the correct React Component...
How do I solve this issue?
UPDATE: I just got rid of all the periods from the JWT token and it is loading like that.... so it seems to not be an issue with the length but with the periods... My react router Route path is "/verification/:userToken" ... how do I get it to not be affected by the periods?
Since this does not trigger your component to be rendered
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIyLCJpYXQiOjE2MTEwMDY5OTUsImV4cCI6MTYxMTAwODE5NX0.D_-RI_YvE6lyHZFtkMizuHxPs3huIE87D6UKFEywYdg
and this does
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
I would suspect that it somehow worked because you got rid of the dots.
Make sure the "." in the token prevent the url from matching your "verification/token" route ? I mean react is assuming that
"verification/eyxxxx.eyzzzz"
is not a valid route.
Try calling for example "verification/test.test.test" and see if it renders your component.

MongoDB Stitch double encodes redirect URI during Facebook login attempt breaking the login process?

I am trying to use the MongoDB Stitch examples tutorial for the Web based Todo App. I am using Node.JS v10.14.2 on a Ubuntu 18.04 Bionic Beaver Linux station.
When I try to log in with Facebook, the login process fails with Facebook complaining that the redirect URL generated by the Stitch server is not whitelisted, and therefore has been rejected during the attempt to login into Facebook with OAuth. The URL is generated during this code block found in this Node module:
node_modules/mongodb-stitch-browser-core/dist/cjs/core/auth/internal/StitchAuthImpl.js
Here is the code that generates the URL that starts the login process. It calls the Stitch server and the Stitch server generates the correct URL to ask Facebook to login the user. Note, I did modify the code but only to show me the value the getAuthProviderRedirectRoute() call was generating. No other changes were made.
StitchAuthImpl.prototype.loginWithRedirect = function (credential) {
var _this = this;
var _a = this.prepareRedirect(credential), redirectUrl = _a.redirectUrl, state = _a.state;
this.requestClient.getBaseURL().then(function (baseUrl) {
// ROS: We want to see the URL being created - ESM.
let replaceUrl = baseUrl +
_this.browserAuthRoutes.getAuthProviderRedirectRoute(credential, redirectUrl, state, _this.deviceInfo);
_this.jsdomWindow.location.replace(replaceUrl);
});
};
Here is the value of replaceUrl that shows the URL that was generated at this initial stage of the Facebook login process:
replaceUrl = https://stitch.mongodb.com/api/client/v2.0/app/my_stitch_app/auth/providers/oauth2-facebook/login?redirect=http://localhost:8001/&state=<<redacted>>&device=<<redacted>>
Stitch generates this URL for the start of the OAuth Facebook login handshake. As you can see from the code this URL is loaded into the browser's location. The stitch server then generates the URL for the next leg of the OAuth handshake. I have excerpted the redirect_uri query argument from the URL it generates and transfers control to, shown here:
redirect_uri%3Dhttps%253A%252F%252Fstitch.mongodb.com%252Fapi%252Fclient%252Fv2.0%252Fauth%252Fcallback
I then manually decoded the redirect URI because it looked wrong. If you look at the redirect_uri query argument shown above, you will see that the OAuth callback URI has been double encoded with the encodeUri() method. This causes the Facebook OAuth server to reject the callback URI because after being decoded, it looks like the URL shown next to the DECODED ONCE label shown below.
This causes the OAuth handshake to fail because it does not match the URL that you see below marked with the label "DECODED AGAIN".
That value is what I put in the Facebook OAuth "Client OAuth Settings" page in the "Valid OAuth Redirect URIs" section as instructed to by the MongoDB Stitch tutorial. Since the URL has been double encoded, the redirect URI when decoded once, doesn't match the "DECODED AGAIN" value and the login process fails. Obviously I could add the "DECODED ONCE" value to the whitelisted URLs list, but that would just kick the problem down the road because it should look like the completely decoded value in "DECODED AGAIN".
DECODED ONCE:
redirect_uri=https%3A%2F%2Fstitch.mongodb.com%2Fapi%2Fclient%2Fv2.0%2Fauth%2Fcallback
DECODED AGAIN:
redirect_uri=https://stitch.mongodb.com/api/client/v2.0/auth/callback
To recapitulate, when Facebook is asked to login in the user with the URL generated by Stitch, shown below, Facebook fails the process with the error message also shown below:
https://www.facebook.com/login.php?skip_api_login=1&api_key=<<redacted>>&kid_directed_site=0&app_id=<<redacted>>%26redirect_uri%3Dhttps%253A%252F%252Fstitch.mongodb.com%252Fapi%252Fclient%252Fv2.0%252Fauth%252Fcallback
Facebook Error:
URL Blocked
This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.
I have scoured the MongoDB Stitch control panel and I don't see anywhere I may have entered something that would lead to the callback URL being passed to Facebook by Stitch, to be double-encoded. Can anyone tell me what could cause this unwanted behavior and how to fix this?
Thanks for the detailed explanation. I tried reproducing your issue but I was able to login with Facebook successfully.
I also checked the URL that the Stitch server generates when redirecting to Facebook, and it was the exact same double-encoded URI you have in your post. This means that this behavior is expected and should not affect the login flow.
If you look at the full URL, you'll see that the main url (starting at "https://www.facebook.com/login.php") has a query parameter called "next". The "next" parameter is a URL, so it needs to be URL-encoded. This URL passed to "next" has the "redirect_uri" parameter, which is also a URL, so it needs to be URL-encoded as well. Since this is a URL in a URL in a URL, this is why you see the double-encoding.
I formatted the URL with each parameter on a new line, and each sub-URL intended to help demonstrate this:
https://www.facebook.com/login.php
?skip_api_login=1
&api_key=<redacted>
&kid_directed_site=0
&app_id=<redacted>
&signed_next=1
&next=https%3A%2F%2Fwww.facebook.com%2Fdialog%2Foauth
%3Faccess_type%3Doffline
%26client_id%<redacted>
// this is the double encoded URL
%26redirect_uri%3Dhttps%253A%252F%252Fstitch.mongodb.com%252Fapi%252Fclient%252Fv2.0%252Fauth%252Fcallback
%26response_type%3Dcode
%26scope%3Demail%2Bpublic_profile
%26state%3D<redacted>
%26ret%3Dlogin
%26fallback_redirect_uri%<redacted>
&cancel_url=https%3A%2F%2Fstitch.mongodb.com%2Fapi%2Fclient%2Fv2.0%2Fauth%2Fcallback
%3Ferror%3Daccess_denied
%26error_code%3D200
%26error_description%3DPermissions%2Berror
%26error_reason%3Duser_denied
%26state%3D<redacted>
&display=page&locale=en_US
To get Facebook login working, I would ensure the following:
In the Facebook console, make sure this URL is added to the list of "Valid OAuth Redirect URIs":
https://stitch.mongodb.com/api/client/v2.0/auth/callback
In the Stitch console, make sure that your application URL is included in the list of "Redirect URIs" for the Facebook Provider. This should include any trailing slashes.
In your application code, make sure you are calling the following JS code when your redirect URL is hit. This allows the the Stitch client SDK to get the result of the OAuth2 flow performed by the Stitch server:
if (yourStitchClient.auth.hasRedirectResult()) {
return yourStitchClient.auth.handleRedirectResult().then(user => {
console.log("Authenticated as user: " + user);
});
}
Check out https://docs.mongodb.com/stitch/authentication/facebook/ for more explanation on these steps.
If you're still having trouble getting this to work after the above steps, let me know and I'll try to help you debug the issue.

Handling redirect code with OAuth2

I am using Instagram's API which requires OAuth2 have some questions regarding best practice for setup. For more details here: https://www.instagram.com/developer/authentication/
So a user clicks on a login button and I give a redirect href.
Log In
They then receive a popup sign in, and they have the option of signing in or not. They are then redirected and '?code=zzzzzzz'is appended to the url: "http://localhost:8080?code=zzzzzzz"
Then the instructions read:
Now you need to exchange the code you have received in the previous step for an access token. In order to make this exchange, you simply have to POST this code, along with some app identification parameters, to our access_token endpoint.
But how should I do this? I'm using Express on the backend. To serve the frontend I use this line:
var static_path = path.join(__dirname, './../build');
It isn't an API route, so I can't use the normal
app.get('/?code=zzzzzzz', function(req, res) {...}).
So how can I use the code that I received in the params?
You must change your redirect_uri on isntagram to something like:
/auth/instagram/callback
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=http://localhost:8080/auth/instagram/callback&response_type=code
Then you can get your code with req.query.code from inside the controller.
For posting the code to isntagrams API use "request" library for nodejs

Resources