How to do Firebase OTP verification using react-dom-router - reactjs

I am doing a project in react based no Firebase OTP authentication.
I get the OTP part right but the trouble comes in the OTP verification part, because it's done in another page. But when i run the verification code on the other page i get an error as Cannot read properties of undefined (reading 'confirm').
OTP_SEND.JS
onsignInSubmit =(event)=>{
event.preventDefault();
this.setupRecaptcha()
var phoneNumber = "+91"+this.state.mobile
console.log(phoneNumber)
var appVerifier = window.recaptchaVerifier;
authentication
.auth()
.signInWithPhoneNumber(phoneNumber,appVerifier)
.then(function(confirmationResult){
window.confirmationResult = confirmationResult;
console.log("otp sent")
}).catch(function(error){
console.log("OTP not send")
})
}
OTP-VERIFICATION.JS
otpSubmit=(e)=>{
e.preventDefault();
const code = this.state.otp;
console.log( code);
window.confirmationResult.confirm(code).then((result)=>{
const user = result.user;
console.log(JSON.stringify(user))
alert("user verified")
}).catch((error)=>{
console.log(error)
})
}

Install the react-dom-router package.
Create a new React application and add the react-dom-router package to it.
Create a new page in your application and add a form to it. This form should include fields for the user's phone number and a button to send the OTP.
Use the Firebase Authentication API to generate an OTP and send it to the user's phone number.
Create a new page in your application and add a form to it. This form should include fields for the user's OTP and a button to verify the OTP.
Use the Firebase Authentication API to verify the OTP entered by the user.
If the OTP is verified, redirect the user to the page you want them to see.

Related

Linking Twitter account to user account (twitter-passport)

Currently, a user is able to login in and sign up for my application no problem. I've then added a "Link your twitter user to account" button which when clicked takes the user to '/auth/twitter'. This then kicks off passport-twitter and the oAuth process begins.
Right now, I'm using passport-twitter as the package for twitter oAuth. This process works. I'm able to get the user successfully authenticated. Here is the code.
However two problems: I don't see a way to 1) keep the user signed into Twitter so they don't have to keep doing this flow of reconnecting their twitter every time they want to push content to it from my app. and 2) associate the Twitter user and the signed in user to my application. Long term, I plan to add other social media accounts, so the user will have multiple social media linked. Twitter will be just one.
Problem #2: I wasn't able to do an axios.get call from my redux store or from the front end to '/auth/twitter/' otherwise I could then just get the information back from the call and then post it to the user's table (right?). So, instead I'm accessing '/auth/twitter' from an tag in the front end to kick off the flow.
passport.use(
new TwitterStrategy(
{
consumerKey: "XXX",
consumerSecret: "XXX",
callbackURL: "http://localhost:8080/auth/twitter/callback",
// callbackURL: "http://www.localhost:8080/home",
includeEmail: true,
},
async(accessToken, refreshToken, profile, cb) => {
console.log('got the prodile')
const twitterIDforOAuth = profile.id
const { id, username } = profile;
let theuser = await User.findOne({
where: {
twitterID: id
}
})
if(theuser){
console.log('FOUND USER', '\n', theuser)
} else {
try {
console.log('NO USER FOUND')
var passwordUser = (Math.random() + 1).toString(36).substring(7);
console.log('CREATING USER')
theuser = await Promise.all([
User.create({
twitterID: id,
username : username,
password: passwordUser
})
])
console.log('USER CREATED');
} catch (error) {
console.log(error);
}
}
//this callback calls the auth/callback url to kick off the redirect process
// need to send username and password to /auth/signup
return cb(null, {username: username, password: passwordUser})
//Line below sends too much data that is irrelevant for the user... lets review it?
// return cb(null, {username: twitterIDforOAuth})
}
)
);
app.get('/auth/twitter', passport.authenticate("twitter"));
app.get(
"/auth/twitter/callback",
passport.authenticate("twitter", {
failureRedirect: "/login",
failureMessage: true,
session: false
}),
async (req, res) => {
var user = req.user;
console.log(user.username, user.password);
//GET USERNAME AND PASSWORD
var username = user.username;
var password = user.password;
///they need to login the app
//auth/login
res.redirect('/AccountSettings')
}
);
The user is being redirected to /AccountSettings while they go through this flow, so I know that the user is 100% authenticated and signed in with Twitter (otherwise they'd be pushed to /login, which isn't happen).
Most people in this flow create a user in their database using the information returned from Twitter.
However, I'm trying to link this information to the signed in user, and keep them signed into Twitter so the user doesn't need to keep reconnecting their Twitter account (at least not often). (With access to their Twitter account, my plan is to allow them to push content to it)
Currently I'm hitting the '/auth/twitter' route with an tag which's href takes it to '/auth/twitter'. Is this the right way about it or is this approach causing my linkage issue?
What are people's recommendation for this issue? Whats the right way to approach linking social media accounts to a signed in user's account?
I'm using Express, Redux, React, Postgres, and passport-twitter
SOLUTION: How to passing data in TwitterStrategy, PassportJS?
had to create a state object outside the /auth/twitter route and then added a id param to the /auth/twitter route so the full route was /auth/twitter/:id
once I got the id I saved it to a state route outside the route in the server file that was accessible to the callback function later in the proces.

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

send email from the email entered by the user

If a user sends an email from my application it should show the user's email Id in the "from" field of the email. I am working in react native. please name any technology or service which can do so and how.
Assume that the app needs to open up the client email app on the user device (android & ios).
At the core, React native provides a Linking library for deep linking with external apps.
const sendMail = async () => {
try {
const recipient = "bill#microsoft.com"
const title = "Acquire Unicorn metaverse start-up";
const body = "Don't lie behind Zuck back. Metaverse is the future..."
const url = `mailto:${recipient}?cc=&subject=${title}&body=${body}`;
await Linking.openURL(url);
} catch (error) {
console.log(error);
}
};
The function will open the email client app and pass email, title, and body parameters to the email client.
Explore more at https://reactnative.dev/docs/linking

How to validate current password in firebase

So I am building a react native expo app and I wanted to reset the password. For now I am just sending the current signed in user an email for reset but I want to do it within the app.
function={() => {
firebase
.auth()
.sendPasswordResetEmail(firebase.auth().currentUser.email)
.then(alert("Please check your email..."))
.then(auth.signOut())
.catch(function (e) {
console.log(e);
});
}}
With the firebase documentation I know how to reset the password but I think to make it a bit more secure I want to validate the current password. But sadly no idea from the documentation. Any help?

After how many days should I reset my JWT cookie for Android local database?

I'm currently doing forgot password functionality for the first time and here's the code so far.
sends the email for the user that has the URL with the JWT token
router.post('/change-password', verifyAuth, resetPassword);
receives and confirms JWT then changes password
router.post('/change-password/:token/:password', confirmResetPassword);
the process I'm currently thinking about is in the email I send the user to
http://localhost:3000/change-passowrd?token=TOKEN_VALUE
but I'm not sure if this is a smart idea or not? I can also use cookies if it's better, any idea?
It's okay to store the JWT token store in the URL for reset password functionality. You have to send this link using Email or any other secure communication service.
I implemented this feature
https://yourapp.com/home/reset/${token}
const data = {
from: "yourcompanymail#outlook.com",
to: user.email,
subject: "Please reset your password",
text: `Hello ${user.name},\n\nI heard that you lost your Teeny password. You can use the following link to reset your password: https://yourapp.com/home/reset/${token}
};
transporter.sendMail(data, function (error, info) {
if (error) {
console.log(error);
} else {
console.log("Email sent: " + info.response);
}
});
Now if the user hits this URL, validate the token and redirect or render the change password page. But don't send the password through the URL.

Resources