This email already exists validation - reactjs

I am making a React application where i submit the username, password and email to the mongo database.
Now I am trying to figure out how I could check inside of React whether the user or email already exists. Meaning so I could show an error-box telling the user to choose something else as an username.
I do know how to do it when I use Node.js and Handlebars. I know how to check my database with the Find() method of mongoose.
But I just don't understand how to think now that I am using React.
When I check if the user already exists in the back-end and it shows that it does exist, how could I inform my front-end (React) that it does?
When I use node.js and handlebars I use flash messages, and it works fine.
I guess my question could be summarized to, how should I do to get my React front-end to cooperate with my Node/Express back-end to share info about a username inside of the database already existing?
I have no code to show, this is more of asking for advice on what tools or methods I should use. I just can't figure it out.
Thank you in advance!

You'll need to have your back-end inform your front-end about whether or not an email has already been used since the front-end has no way of knowing without the back-end.
Basically, when a user tries to register, you should send your registration request from the front-end to the back-end without worrying about duplicate emails. The response from the server should indicate whether or not registration was successful, and if not, why not.
For example the registration component in your React code might look something like this:
class RegistrationComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
error: "",
}
}
handleSubmit = async event => {
event.preventDefault();
const { email, password } = this.state;
const response = await sendRegisterRequest(email, password);
const responseJson = await response.json();
if (response.status !== 200) {
this.setState({error: reponseJson.error});
} else {
// handle successful registration
}
}
render() {
const { error } = this.state;
return (
<form onSubmit={ this.handleSubmit }>
<span>{ error }</span>
{ /* rest of the form */ }
</form>
)
}
}
Where sendRegisterRequest is some module that handles sending registration requests to the server.
Note that this front-end logic expects the server to respond with status 200 on successful registration and with something else (status 400) if there is an error. Also if there is an error, the server should respond with a payload body that looks like: {"error": "That email is already in use"}.
You mention that you know how to check for existing email addresses on the server, so just check in that manner before creating a new account, and if the email address is already in use send the error payload with a status of 400.

You can respond with a 400 status if it occurs then send the error message to the frontend that way. e.g. return res.status(400).json(errors).

catch((err) => {
console.log(err);
if(err.status=404){
alert("email already used");
}

Related

Can URL API endpoint self-correct?

I am using fetch API inside a React application to retrieve and display some quiz questions.
This is my url endpoint: https://opentdb.com/api.php?amount=${amount}&difficulty=${difficulty}&type=multiple
I have noticed that:
-when I misspell part of the URL before "?" then the response doesn't get back.
example:https://opentdb.com/api.ph?amount=${amount}&difficulty=${difficulty}& (missing "p" of php)
-when I misspell part of the url after "?" then, sometimes I get an empty array back, sometimes I get the data back. How can I get data back with a wrong URL?
example: https://opentdb.com/api.php?amoun=${amount}&difficulty=${difficulty}&type=multiple (missing "t" in amount)
I haven't deployed the application yet, I am using vsc and run npm start to develop the application.
Is it possible that the URL auto-corrects? or maybe it gets cached?
my code:
export const fetchQuizQuestions = async (
amount: number,
difficulty: Difficulty
) => {
const endPoint = `https://opentdb.com/api.php?amount=${amount}&difficulty=${difficulty}&type=multiple`;
try {
const response = await fetch(endPoint);
console.log(response);
const data = await response.json();
console.log(data);
if (data.results.length === 0) {
throw new Error("The part after ? contains some mistake");
}
//below I create the new property "all_answers" and make sure the answers order is never the same
return data.results.map((question: Question) => ({
...question,
all_answers: shuffleArray([
...question.incorrect_answers,
question.correct_answer,
]),
}));
} catch (error: any) {
console.log(error.name);
console.log(error.message);
}
};
Before the ? It's the url. So if you make a mistake there, basically it's like sending a letter to a different adress, so you will not get any answers.
After the ? it's the query string. So you're asking for a result, with some parameters (your query)
So if you're saying like "ok, send me back answers with amount = XXX" but you misspell amount, it's just like "ok send me back answers" because you're not asking for amount anymore (but amoun which is nothing for the endpoint)

Reactjs: Show logged in or log in accordingly to session

I am trying to get better in react and I would like to do it everything correctly which is why I am asking for your opinions and help.
I am building a project in NextJS and I have a layout component which contains components which are rendered multiple times such as header, footer etc.
I this header, I have a "Sign in" and "Sign out" button. I'd like it to only show one of them accordingly to your session status.
I use a sessionid which contains some more info in the database and this sessionid is stored in a httponly cookie.
It is stored in the database with data:
id
sessionid
userid
expires
Would you add or remove anything to this?
So my question is:
How would you check for a session and then render x accordingly? Would you just send an api call each request that checks the session or? Should I maybe use useContext and create a provider which can then send the session with the provider?
I'm quite lost on how to do it the best way so the flow is smooth as f*ck.
It depends how strict you want to be with it.
One option would be to simply check the existence of the cookie and adjust according to that. You can use js-cookie for that.
The better option, in my opinion, is to verify the cookie with your backend. You should set up an endpoint that simply verifies / parses the cookie and returns something like the user_id, or ismply a boolean indicating whether the user is logged in.
Given that you are using Next, you can add this call to your App's getInitialProps() like this:
App.getInitialProps = async () => {
let loggedIn;
try {
({ data: {loggedIn} } = await axios.get('/api/v1/auth/checkCookie'));
} catch (err) {
console.log('Error checkingCookie', err.message );
}
return {
loggedIn,
}
}
Your loggedIn variable will then be available in the props of your App, like:
function App({currentUser}) {
if (currentUser) {
return <div>Logged In</div>
} else {
return <div>Logged Out</div>
}
}

setPersistence function is not working properly (Firebase + React)

I want to make a functionality where I persist the user while the window is open or to be precise in the current session. To make this I've researched the Firebase documentation, and I found out about this: Authentication State Persistence.
After researching it, I decided to put it inside my app, here's how my code looks like:
function logIn(email, password) {
setPersistence(auth, browserLocalPersistence)
.then(() => {
return signInWithEmailAndPassword(auth, email, password);
})
.catch((error) => {
console.log(error);
});
}
This function is inside my UserAuthContext file where I keep all functionalities regarding user. Now some may say that there is nothing wrong with the way this function is made, but whenever email and password are empty the user can still Login without being stopped by Firebase errors like it happens without setPersistence function.
Does anyone know why does my Login go through even though email and password are empty?

How to update the password of a Supabase user on a NextJs project?

I'm facing an issue updating a password for a supabase user on a BlitzJs (NextJs) project.
Basically, I have a reset password method that works perfectly. First I send an email with a reset link, that opens a page where the user can update his password like so:
const { error, data } = await supabase.auth.api.updateUser(token, { password: password.trim() })
the token being the one in the url, provided in the email link.
So far, so good, but when I try to update the password for a logged in user, using the exact same method supabase.auth.api.updateUser, it fails to find the user;
The difference is the token is the session.access_token
So I've tried to use the supabase.auth.api.updateUserById method, but it gives me another error: { message: 'User not allowed', status: 401 }
Any ideas? I feel the supabase docs about this is not very clear, and probably outdated as it doesn't show all the available methods :/
Update password for authenticated user.
const { user, error } = await supabase.auth.update({password: 'new password'})
For more informations check: Supabase references

Firebase failure in React Native

what's wrong with this picture ?
import firebase from 'firebase';
onButtonPress() {
const { email, password } = this.state;
firebase.auth().signInWithEmailAndPassword(email, password)
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.catch(() => {
this.setState({ error: 'Authentication Failed' });
});
});
}
And so that we're clear:
Yes it's installed in the framework when I built the app. And yes I'm calling it on the same page where this is being executed. And yes the app runs fine without this section of code. there are no coding errors, nor logic errors.
If I wanted to a.) debug this bit of code how would I do that ? and b.) where would I add the console.log statement ? I know it has to live somewhere....like here >
firebase.auth().signInWithEmailAndPassword(console.log(email, password)) ??
Shouldn't a call like these to firebase work like this ?
Thanks ahead of time.
Miles.
Oy! When I called the function to press the button I had set up. I had written onButtonPress instead of onPress....grrrrrrrrr! Sorry to bother everyone. All is well now.
You need to add firebase to your application, there are specific steps mentioned on their site. The site has information no how to call firebase for email authentication.

Resources