send email from the email entered by the user - reactjs

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

Related

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

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.

Is there a way to send a Twilio SMS with React on the Client Side?

Is there a way to send a Twilio SMS with React on the Client Side? If not, how can I send a Twilio SMS with JS?
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const twilio = require("twilio");
// Find your account sid and auth token in your Twilio account Console.
const client = new twilio(accountSid, authToken);
export const sendSMS = (to, body) => {
// Send the text message.
client.messages.create({
to: to,
from: process.env.TWILIO_NUMBER,
body: body,
});
};
No, because it would mean exposing your auth token on the client side where everybody could read it.
But there's an alternative if you say you don't want/need a backend. You can use Twilio Functions to implement the code to send the SMS and protect the Function either with a JWT token or (for testing) basic auth.

Trying to use React-google-login just for accessing Google OAuth2 calendar API but giving errors - why?

I'm really new to OAuth2 so could really use some help. I have a site where users register and login via standard means. However, once they register, I want to connect their Google account so they can view/edit/modify their Google calendars. To this end, I installed react-google-login and have a component on the front-end that logs them into their account. That works fine (here's the code). Please note that the jsx is in styled components, which is why it has odd labels.
return (
<GoogleContainer>
<Logo src={GoogleLogo} />
<GoogleLogin
clientId = {process.env.REACT_APP_CLIENT_ID}
render={(renderProps) => (
<GoogleBtn
onClick={renderProps.onClick}
disabled={renderProps.disabled}
style={styleObj}
>
Connect to Google
</GoogleBtn>
)}
// buttonText='Sign in to Google Calendar'
onSuccess={responseGoogle}
isSignedIn={true}
onFailure={responseError}
cookiePolicy={"single_host_origin"}
responseType='code'
accessType='offline'
scope='openid email profile https://www.googleapis.com/auth/calendar '
/>{" "}
</GoogleContainer>
);
On the backend, I have code that grabs the refresh_token, stores it in a database and then I make a token object that I can send back to the frontend. Here is the code for that -
//This next fx will be used in the CreateTokens fx called by Google Login to identify user by the email captured in scope
const fetchInfo = async (accessToken) => {
const request = await axios.get(
`https://www.googleapis.com/oauth2/v2/userinfo?access_token=${accessToken}`
);
let response = await request;
let email = "";
if (response) {
email = response.data.email;
}
return email;
};
//Get authorization tokens from google calendar when signing into Google
const createTokens = async (req, res, next) => {
try {
const { code } = req.body;
const { tokens } = await oauth2Client.getToken(code);
accessToken = await tokens.access_token;
expiryDate = await tokens.expiry_date;
id_token = await tokens.id_token;
//Make an object with accessToken and expiry data and send to front end
const tokenObj = {
accessToken,
expiryDate,
id_token,
};
//Refresh Token goes to the database
const refreshToken = await tokens.refresh_token;
//We find user by using the scope variable from Google Login (frontend) - fx above
let email = await fetchInfo(accessToken);
if (refreshToken) {
//Parameters to update record by putting refreshToken in database
const filter = { email: email };
const update = { refreshToken: refreshToken };
let user = await User.findOneAndUpdate(filter, update, {
new: true,
});
}
res.send({ tokenObj });
} catch (error) {
next(error);
}
};
That also works fine as I get the refresh_token and store it in the database by user and the tokenObject with the access token gets sent back to the frontend. Here's where I'm confused and can use some help - first of all, I thought I needed to send the token to the frontend to store it but pretty much every time I refresh my page now, the frontend is sending a boatload of information to the console (with tons of information from Google - like the profile, tokens, etc). I don't know what code I wrote that is causing this or if it's a good thing or not. If it's automatically generated, do I even need to have backend code to get the token? Also, I'm getting another message that says " react_devtools_backend.js:3973 Your client application uses libraries for user authentication or authorization that will soon be deprecated. See the Migration Guide for more information." I thought this was up-to-date and not sure what part is deprecated. Ugh - sorry I'm so new to this and very confused. Any help would be much, much appreciated!!
Blockquote

This email already exists validation

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");
}

Implementation of Paypal in single page application

I am currently working on a game, which will consist out of an API-based backend, along with a web frontend (which is a single page app, in AngularJS) and on several mobile devices (using Cordova). I am planning on serving the SPA over the main domain name, along with a CDN. The SPA (and homepage) will all be static HTML/Javascript/CSS files, so the only part which is dynamic is the api. The domain name for the "main server" hosting the static sites will be in the style of example.com, the one for the api will be api.example.com
I am wondering how I can integrate Paypal into this scenario though. The internet doesn't seem to offer much advice on how to integrate it into S.P.A's like this...or my google-fu could be off. Thanks for the replies.
Below is how I am handling the situation,
I have a button to say pay with paypal and onClick I open a new window -> window.open("/paypalCreate", width = "20px", height = "20px");
and I capture this get request "/paypalCreate" in my node.js server and call create method which looks liek below
exports.create = function (req, res) {
//Payment object
var payment = {
//fill details from DB
};
//Passing the payment over to PayPal
paypal.payment.create(payment, function (error, payment) {
if (error) {
console.log(error);
} else {
if (payment.payer.payment_method === 'paypal') {
req.session.paymentId = payment.id;
var redirectUrl;
for (var i = 0; i < payment.links.length; i++) {
var link = payment.links[i];
if (link.method === 'REDIRECT') {
redirectUrl = link.href;
}
}
res.redirect(redirectUrl);
}
}
});
};
This redirects user to paypal and once user confirms or cancels payment, the redirect urls are called. And in the success redirect url I capture the payment details into the databse and render a html in this opened window with the confirmation.
exports.execute = function (req, res) {
var paymentId = req.session.paymentId;
var payerId = req.param('PayerID');
// 1. if this is executed, then that means the payment was successful, now store the paymentId, payerId and token into the database
// 2. At the close of the popup window open a confirmation for the reserved listing
var details = {"payer_id": payerId};
paypal.payment.execute(paymentId, details, function (error, payment) {
if (error) {
console.log(error);
} else {
//res.send("Hell yeah!");
res.render('paypalSuccess', {payerId: payerId, paymentId: paymentId});
}
});
};
Once the user closes the opened window in which paypal was being handled the orginal SPA window will be refreshed and thus getting the payment details from the DB and here you can handle the SPA in whatever way you want.
I know that this is a dirty hack, but like you I couldnt find a better way. Please let me know if this works for you or if you have a found a better way to do tihs.
cheers,
Chidan

Resources