Can we store data coming in console to our database? - database

I am working with angular,Mongodb,Nodejs,express. simply a Mean stack.
my website is related to shopping where the carts loads dynamically. the products added to cart should be sent as mail to owner.
can we send directly mail? is yes please explain the process how.
if not should be stored in database then how?

So, the question is very unclear here. But I'll try my best to explain all the situations. So that, you don't have to mess with it a lot. I'll explain how you can send a mail to the user using front-end only or using your server.
To send an email to a user, we need to do it on the backend. That means you'll have to write some code in your server for sending the email to your client. As you have a MEAN Stack application, you must be familiar with Node package manager.
npm has a package called nodemailer that can be used for sending emails to the users. But make sure you write those emails in a good manner so that they don't end up in the spam box.
You can install nodemailer using
npm install nodemailer
Here's a sample code from w3schools
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'youremail#gmail.com',
pass: 'yourpassword'
}
});
var mailOptions = {
from: 'youremail#gmail.com',
to: 'myfriend#yahoo.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
You may also find other and maybe even better alternatives with a simple google search.
Also, i don't think there's any point in storing this data in the database unless you need it for future use. I don't know the flow of your ecommerce application. So, I'll leave this decision for you to take.
And if you want to send the e-mail directly from the front-end, there's a workaround. Sending emails requires a server, but you can use someone's else backend server for this. Basically a BaaS(Backend as a Service). You can check this previously answered question on stackoverflow for more information regarding sending emails directly from the frontend of an application.
How can i send emails without a server ? Only front-end Javascript

Related

"mock app" how to search through a database for matches? (react-native app)

Im working on a mock app as a project to have for my portfolio as a frontend developer.
So far i've been able to fairly accurately mock some posts requests in my app ( requests for fetching data, logging in, etc ) here is an example of my login func
export const loginUser = async ({
username,
password,
onSuccess = () => {},
onFailure = () => {},
}) =>
postReq({
endpoint: LOGIN_USER,
body: {
username,
password,
},
onSuccess,
onFailure,
});
all of my "Data" lives in a json file in my project file.
however not very familiar with the backend side of things, How would the backend normally perform a search that returns data ? and whats the closest thing i can do from the frontend? I've only recently discovered regular expression functions, is this a path in the right direction? Thank you very much, Im excited to keep learning.
I think you are using redux or useReducer kind of logic to handle your login. This seems fairly true what you did for authenticate user from frontend side.
For backend side;
1- You send your request(via axios, fetch, ajax etc) to your server(backend) like this and waiting for a response.
2- You are taking this information from your request body as you send this informations in your request body which is the preferred way.
3- You check for username in your database if there is a collasion, you will check for password correctness which i advice you to store your passwords hashed and check correctness via hash compare.
4-If there is no collasion or password is not correct you send an error with relative status code like 500 and a message "A user with
the given username and password could not be found"
5- If password is true, you send your feedback your frontend with a success status response(like 200).
6- You taking your response from your server and take the necessary actions accordingly
And keep up your passion you will have a lot of fun

How to protect/hide your userId and web token in react?

I'm developing simple CRUD app in react and express. Now, When user SignIn, I store the userId(from database) and JWT(web token) in localstorage and I use this userId and token to check isSignin() and isAuthenticated() for future API calls. Now, If I deploy or make production build of this application, the user info will be clearly visible in my localstorage and it can be threat to my security. Can anyone please tell me how to hide this information and implement these mathods in production ready app? I want deploy it on AWS. Because, I've seen on so many website, we cannot see our own userId other credentials in our own localstorage.
here my methods. The req are coming from front end in react and as soon as I am getting response to front-end my react code is storing that in localstorage.
exports.isSignedIn = expressJwt({
secret: process.env.SECRET,
userProperty: "auth"
});
exports.isAuthenticated = (req, res, next) => {
let checker = req.profile && req.auth && req.profile._id == req.auth._id;
if (!checker) {
return res.status(403).json({
error: "ACCESS DENIED"
});
}
next();
};
Randall Degges gave a very detailed explanation about why you shouldn't use localstorage to store sensitive data. I will point out the main part.
If you need to store sensitive data, you should always use a
server-side session. Sensitive data includes:
User IDs, Session IDs, JWTs, Personal information, Credit card information,
API keys, And anything else you wouldn't want to publicly share on
Facebook If you need to store sensitive data, here's how to do it:
When a user logs into your website, create a session identifier for
them and store it in a cryptographically signed cookie. If you're
using a web framework, look up “how to create a user session using
cookies” and follow that guide.
Make sure that whatever cookie library your web framework uses is
setting the httpOnly cookie flag. This flag makes it impossible for a
browser to read any cookies, which is required in order to safely use
server-side sessions with cookies. Read Jeff Atwood's article for more
information. He's the man.
Make sure that your cookie library also sets the SameSite=strict
cookie flag (to prevent CSRF attacks), as well as the secure=true flag
(to ensure cookies can only be set over an encrypted connection).
Each time a user makes a request to your site, use their session ID
(extracted from the cookie they send to you) to retrieve their account
details from either a database or a cache (depending on how large your
website is)
Once you have the user's account info pulled up and verified, feel
free to pull any associated sensitive data along with it
This pattern is simple, straightforward, and most importantly: secure.
And yes, you can most definitely scale up a large website using this
pattern. Don't tell me that JWTs are “stateless” and “fast” and you
have to use local storage to store them: you're wrong!
Source/Read more: Please Stop Using Local Storage

How to send sms messages from a React Native App programmatically ?

I want to be able to sent sms messages though my React Native app programatically in the background.
I know how to sent sms normally in the code, but the app keeps opening the default sms app, and that is not what i want.
The user should not push any buttons to sent the sms, because my goal is to notify a phonenumber every time the user is doing a particularly task in the app.
I have tried looking at Twilio, but they dont provide a api for React Native.
Does anybody know something about how I can do this ?
With the answer from kdenz, I followed a tutorial here: Seeting up a firebase function
This is my code for sending a request to Twilio, when the firebase database value 'visible' is changing.
import * as functions from 'firebase-functions';
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const twilio = require('twilio');
const accountSid = functions.config().twilio.sid;
const authToken = functions.config().twilio.token;
console.log(`Twilio account: ${accountSid}`);
const client = new twilio(accountSid, authToken);
const twilioNumber = 'xxx-xxx-xxx';
exports.textStatus = functions.database
.ref('/users/{userId}/data/visible')
.onUpdate(event => {
return admin.database()
.ref(`users/{userId}/data/`)
.once('value')
.then(snapshot => snapshot.val())
.then(user=> {
console.log(user[0]);
const longitude = user.longi;
const latitude = user.lati;
const phoneNumber = user.phone;
const textMessage = {
body: `See user position at Google: http://www.google.com/maps/place/${latitude},${longitude}`,
to: phoneNumber,
from: twilioNumber
}
return client.messages.create(textMessage);
})
.then(message => console.log(message.sid, 'success'))
.catch(err => console.log(err));
});
I think this is only possible with Android, as seen in this deprecated package https://www.npmjs.com/package/react-native-send-sms
For iOS, I don't think so, as seen in How to programmatically send a text message after the user has given permission?
To achieve what you want, you'll need a SMS service like Twilio. Then you can set up a server (Or a cloud function for minimal cost + easy maintainability) which receives API calls from your RN app, and sends the message to the desired recipient. You can then set up some security measures too, to prevent hackers from spamming the API.
Or if you don't care about security (Which I highly don't recommend), you can directly call Twilio send message API within your app, which is dangerous because hackers can easily extract your Twilio authorization token and use it to send messages for themselves.
On android, it is possible to send sms from user's number programmatically without user interaction.
But on IOS, the only way you can send an SMS without user interaction is to use an external provider such as Twilio; but the message will come from your server's number, not from the user.
I have already answered for same kind of question. Check this out
Is there anyway to send sms in background for both Android & IOS?

Nodejs and express error handling on backend and frontend

I'm currently working on a portal website with nodejs, express and angular. One issue I have come across is how error handling should be done. I have read through the express error handling guide also and have implemented their default error handling function. So, I can't seem to find the best practice for this situation.
For example, if I am trying to retrieve from a database and it cannot be found, the server would send a 404 and in https request would handle it there on the client end. The only problem is, is that it sends the error message and stack trace into the client's console. My method was, based on that error, I would handle it on the client end by displaying a message such as "Incorrect password" or "Cannot find this e-mail in the database. Would you like to sign up?".
Another example I have is when a user inputs his credit card information. On the client end, there is a http request for his billing information. If I receive a "404" for no billing information found, I would bring up a add billing form. If it is a "200", I would display that current billing information on that same page.
What would be the best practice to catching errors on the front end without sending errors to the user?
function getBillingInfo(){
$http.get('test/api/billinginfo', {
params: {
token: store.get('token')
}
}).then(function (response) {
//Retrieve billing information
$scope.billingInfo = response.data;
//Display current billing information
$scope.billingState = "display";
}, function (response) {
//Display add billing form
$scope.billingState = "add";
//Initialize form input
$scope.billingAdd = {
country:"US",
month:"month",
year:"year",
state:"AL"
};
});
}

Send SMS form AngularJS Web App

I want to send SMS from AngularJS web application. Can anyone tell me how to do this? Please suggest me some reference link or code sample.
One technique you could use is using Firebase and Zapier to help trigger sending your SMS. You can check out this blog post which details how to set something like this up.
The trick is loading data into your firebase when you want the SMS to be triggered like this:
var sendSMSText = function (recipient) {
var smsQueue = new Firebase('https://.firebaseio.com/sms/' + recipient.phone);
smsQueue.set({
name: recipient.name,
phone: recipient.phone
}, onSuccess)
};
Then setup Zapier to trigger a new action when an entry is added to your Firebase database. You can have this action trigger a Twilio SMS message.
Hope that helps.
Disclaimer: I work for Twilio.
not working in angular2

Resources