Node/Express Email + Token Authentication - javascript

I'm wondering if any Node/Express gurus could give me a little advice on if the following scenario that I'm trying to achieve is possible. I think it is, I'm just a little unsure on the best-practise way to tackle the problem.
I'm currently in the process of building a small client that will be protected. To gain access to the following the following steps must occur:
Input name + email address in a form that then sends this data in an email to an admin.
The email will containing a prebuilt link containing query params of the data that was input into the field. The link will have an API URL prior to the query params.
When the link is clicked an API request will be performed that takes the query params (mainly the email address) and grants this email address access to the client for a specific period of time such as 2 hours.
The client will go to subdomain.domain.com, enter their email address (which gets validated to check that an admin has approved the email address) and have access to the client for 2 hours. There will also be a timer with the remainding session length.
The majority of this I can take care of but I thought I'd give you an insight in to the full picture of what it is I'm trying to achieve. The part that I have queries about is section 3 and giving an email address access to the client for a specific period of time. I don't want any passwords to be involved so what is the most-secure, more-advisable solution to this? Would I have to use tokens?
I will be building the server-side using Express unless I strictly have to use Node for whatever reason.
Thanks in advance!

When the admin approves the request, the api inserts a row into a db (mongo would be easy) which expires in 2 hours (or however long). Next, when the user goes to the subdomain, they enter their email address. Your express app checks if the email is in mongo. If it is, they have access. You can stick their email in a cookie and check it that way on future requests.

Related

How to check the existence of an email address

I am in charge of developing an application that needs to upload a lot of user data in a batch way. One of the users' data is an email address and we need to make sure that this email address really exists so that we can send a welcome message.
So, how could I check if an email address really exists?
You can check the format of an email address for RFC5322 compliance using npm email-validator:
const validator = require('email-validator')
...
if (validator.validate('test#email.com')) {
/* email format is correct */
}
But you're asking if there's a general and reliable way to ask the intertoobz if there's a real mailbox behind any given email address.
The answer is no, except by sending a message to the mailbox and asking the recipient to respond. There are unreliable ways to check for a mailbox's existence, but many mail transfer agents do not implement them. Why not? Spam.
Commercial mail services (Constant Contact, MailChimp, SendGrid) offer features to send a message to a mailbox requesting permission to give it a subscription to an email service. The person behind the mailbox usually responds by clicking a hyperlink. The hyperlink contains a nonce -- a hard-to-guess random value -- that identifies the mailbox. Only after the URL click can you be sure the address exists. Sometimes end-users are asked to "confirm your email address" using this technique.
Those same services are good about tracking email bounces and failures, so they can have a temporary idea about what mailboxes don't exist. They go to a lot of trouble to avoid sending junk, because the big email providers (gmail, outlook.com, comcast, charter, and the rest) routinely blacklist servers sending email, to lower their spam load. When you use a service, you're paying for a lot of network-engineering work to prevent blacklisting.
You can implement a similar "permission to subscribe" service in your own application, but explaining how to do that is beyond the scope of a StackOverflow answer. Keeping it from being blacklisted? Probably very difficult unless your volume is very low.
See this for more discussion.
Can I check if an email address exists using .net?
I've used SendGrid.com 's free service tier, and it works well. I've also used MailChimp successfully.
You can use a service like EmailChecker (I just did a quick google search) to check if the email really exists.
To use the API you need to pay for premium but you can see how it works here: https://email-checker.net
Validating that an email address is a legal (e.g., mailable) format is one thing, but it doesn't tell you that there's a mailbox at that address. The only way to know if an email address "exists" is to mail something to it. If it [eventually] bounces, you can be pretty sure that it doesn't exist. Otherwise, all you know is that somebody's SMTP server accepted the message.
See https://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/
and this:
How to check if an email address exists without sending an email?

How do i only allow specific email to login into my page

There are two sides, Admin and Users. I am using the same database in firebase for both Users and Admin. It means that Users that are registered in my firebase authentication, can login to Admin webpage. How do i allow only specific admin's email to login into the Admin page.
For example:
Admin has an email of admin#admin.com
User has various email like 123#gmail.com, 222#gmail.com and etc.
What i want is only to allow admin#admin.com to be able to login into the Admin page but restrict login for User emails to login to the Admin page.
Using a Javascript, a simple solution would be to split the email String on the #, which will return you an Array of substrings and compare the second part which is the domain. Then, you could condition the rest of your code to work only if the criteria is true.
An example would be:
const allowedEmailDomain = 'admin.com';
const email = 'test#admin.com';
if (email.split('#')[1] === allowedEmailDomain) {
// do something, we accept this email
} else {
// return an error or do nothing
}
I make the assumption that, on the back-end side, your application is correctly secured, i.e. you have security rules in your database that only allow the users with an "admin" profile/role to read or write "admin" data in the database.
If this is not the case you MUST set correct security rules, since securing your Firebase instance only from a front-end perspective is not sufficient, as it is not very difficult to reverse engineer your app code and write some JavaScript code that will interact with your back-end. For that you could use Custom Claims.
So, with this assumption, it means that you need to adapt your front end in such a way the admin screens are only seen by the admin users.
One of the best answer is again to use Custom Claims, as explained here https://firebase.google.com/docs/auth/admin/custom-claims#access_custom_claims_on_the_client (Section "Access custom claims on the client") and in this official Firebase video: https://firebase.google.com/docs/auth/admin/custom-claims#access_custom_claims_on_the_client
Note that trying to block a user based on his email domain may not be a good solution as it is easy, in few lines of JavaScript code, to register to your Firebase project as a user with a mail like whatever#admin.com or with any other email (using createUserWithEmailAndPassword)
Just block every other domain as #admin.com.
$allowed_domains = array("admin.com");
$email_domain = array_pop(explode("#", $email));
if(!in_array($email_domain, $allowed_domains)) {
// Not an authorised email
}
It's simply. Make an array for allowed domains, explode by #, get the last element of the array and check if it exists in the allowed domains array.

Is it possible to post to chat.postMessage as any user in a Slack team?

I'm building a Slack integration that is intended to modify some text and then post it to a Slack channel as though the user who triggered the command had said it.
e.g. /makeFace disapproval
#Ben 3:45pm
ಠ_ಠ
I ask for the client permission scope, which adds the chat:write:user permission. But when I hit the chat.postMessage endpoint, it only seems to allow you to post as the user who added the integration because the token it returns seems to be individuated for that user.
I know that giphy, for instance, sends its gif messages as though you are the originator, but I can't find out how they manage it. Is there any documentation for sending messages as other members of the team?
There are 2 ways to achieve this:
A. Overwriting username and icon
When you send a message with chat.postMessage it is possible to set a user name with the property username. The message will then appear as being send by that user (same for icon with icon_url).
However, this is not meant to impersonate real users, so even if you use the same username and icon as the real user the message will have the app tag, so that they can be distinguished from a real user.
Here is an example how it looks like (from a gamer Slack about flying and killing space ships):
But depending on what your requirements are that might work for you.
If you want to use it make sure to also set the as_user property to false (yes, really) and it will not work with a bot token, only with a user token.
See here for more details on how it works.
This also works for the legacy version of Incoming Webhooks, not with the current version of incoming webhooks though. (You can still get the legacy version, see this answer)
B. Having the user's token
Another approach is to always use the token from the respective user for sending the message. In combination with as_user = true messages sent by your app will look exactly as if they would come from the respective user (no APP tag).
To make that happen your app would need to collect tokens from all users on your workspace and store them for later use. This can be done by asking every user to install your app (called adding a "configuration") through the Oauth process (same you use to install your app to a workspace), which allows your app to collect and store those tokens for later use.
Update: This doesn't work. It impersonates the user who installed the app, so it merely seems to work... until another user tries to use it (and they end up impersonating you).
Go to your App's management page. Select "OAuth & Permissions".
Add the chat.write OAuth Scope to your app as a User Token Scope, not a Bot Token scope.
Take note of your User OAuth Token at the top of this page (not your But User OAuth Token).
Call chat.postMessage with
username = user id of the user you'd like to post on behalf of
token = the token from step 3. above
The resulting post will be 100% impersonated. Not just the name and icon as mentioned in other answers, but it'll 100% function as if it came from the user.
I hope this will help those who are still facing this issue.
First give the chat:write and chat:write.customize scope to your bot. The scope chat:write.customize Send messages as #your_slack_app with a customized username and avatar
From "OAuth & Permissions" settings get the bot OAuth token or even bot access token (both will work).
Then set the arguments like the following.
username to specify the username for the published message.
icon_url to specify a URL to an image to use as the profile photo alongside the message.
icon_emoji to specify an emoji (using colon shortcodes, eg. :white_check_mark:) to use as the profile photo alongside the message.
You can visit the docs from here

PHP mail with AJAX causing the mail to end up in SPAM folder [duplicate]

This is a tricky one and I've always relied on techniques, such as permission-based emails (i.e. only sending to people you have permission to send to) and not using blatantly spamish terminology.
Of late, some of the emails I send out programmatically have started being shuffled into people's spam folder automatically and I'm wondering what I can do about it.
This is despite the fact that these particular emails are not ones that humans would mark as spam, specifically, they are emails that contain license keys that people have paid good money for, so I don't think they're going to consider them spam
I figure this is a big topic in which I am essentially an ignorant simpleton.
Use email authentication methods, such as SPF, and DKIM to prove that your emails and your domain name belong together, and to prevent spoofing of your domain name. The SPF website includes a wizard to generate the DNS information for your site.
Check your reverse DNS to make sure the IP address of your mail server points to the domain name that you use for sending mail.
Make sure that the IP-address that you're using is not on a blacklist
Make sure that the reply-to address is a valid, existing address.
Use the full, real name of the addressee in the To field, not just the email-address (e.g. "John Smith" <john#blacksmiths-international.com> ).
Monitor your abuse accounts, such as abuse#yourdomain.example and postmaster#yourdomain.example. That means - make sure that these accounts exist, read what's sent to them, and act on complaints.
Finally, make it really easy to unsubscribe. Otherwise, your users will unsubscribe by pressing the spam button, and that will affect your reputation.
That said, getting Hotmail to accept your emails remains a black art.
Sign up for an account on as many major email providers as possible (gmail/yahoo/hotmail/aol/etc). If you make changes to your emails, either major rewording, changes to the code that sends the emails, changes to your email servers, etc, make sure to send test messages to all your accounts and verify that they are not being marked as spam.
A few bullet points from a previous answer:
Most important: Does the sender address ("From") belong to a domain that runs on the server you send the E-Mail from? If not, make it so. Never use sender addresses like xxx#gmail.com. User reply-to if you need replies to arrive at a different address.
Is your server on a blacklist (e.g. check IP on spamhaus.org)? This is a possibility when you're on shared hosting when neighbours behave badly.
Are mails filtered by a spam filter? Open an account with a freemailer that has a spam folder and find out. Also, try sending mail to an address without any spam filtering at all.
Do you possibly need the fifth parameter "-f" of mail() to add a sender address? (See mail() command in the PHP manual)
If you have access to log files, check those, of course.
Do you check the "from:" address for possible bounce mails ("Returned to sender")? You can also set up a separate "errors-to" address.
You can tell your users to add your From address to their contacts when they complete their order, which, if they do so, will help a lot.
Otherwise, I would try to get a log from some of your users. Sometimes they have details about why it was flagged as spam in the headers of the message, which you could use to tweak the text.
Other things you can try:
Put your site name or address in the subject
Keep all links in the message pointing to your domain (and not email.com)
Put an address or other contact information in the email
Confirm that you have the correct email address before sending out emails. If someone gives the wrong email address on sign-up, beat them over the head about it ASAP.
Always include clear "how to unsubscribe" information in EVERY email. Do not require the user to login to unsubscribe, it should be a unique url for 1-click unsubscribe.
This will prevent people from marking your mails as spam because "unsubscribing" is too hard.
In addition to all of the other answers, if you are sending HTML emails that contain URLs as linking text, make sure that the URL matches the linking text. I know that Thunderbird automatically flags them as being a scam if not.
The wrong way:
Go to your account now: http://www.paypal.com
The right way:
Go to your account now: http://www.yourdomain.org
Or use an unrelated linking text instead of a URL:
Click here to go to your account
You may consider a third party email service who handles delivery issues:
Exact Target
Vertical Response
Constant Contact
Campaign Monitor
Emma
Return Path
IntelliContact
SilverPop
Delivering email can be like black magic sometimes. The reverse DNS is really important.
I have found it to be very helpful to carefully track NDRs. I direct all of my NDRs to a single address and I have a windows service parsing them out (Google ListNanny). I put as much information from the NDR as I can into a database, and then I run reports on it to see if I have suddenly started getting blocked by a certain domain. Also, you should avoid sending emails to addresses that were previously marked as NDR, because that's generally a good indication of spam.
If you need to send out a bunch of customer service emails at once, it's best to put a delay in between each one, because if you send too many nearly identical emails to one domain at a time, you are sure to wind up on their blacklist.
Some domains are just impossible to deliver to sometimes. Comcast.net is the worst.
Make sure your IPs aren't listed on sites like http://www.mxtoolbox.com/blacklists.aspx.
I hate to tell you, but I and others may be using white-list defaults to control our filtering of spam.
This means that all e-mail from an unknown source is automatically spam and diverted into a spam folder. (I don't let my e-mail service delete spam, because I want to always review the arrivals for false positives, something that is pretty easy to do by a quick scan of the folder.)
I even have e-mail from myself go to the spam bucket because (1) I usually don't send e-mail to myself and (2) there are spammers that fake my return address in spam sent to me.
So to get out of the spam designation, I have to consider that your mail might be legitimate (from sender and subject information) and open it first in plaintext (my default for all incoming mail, spam or not) to see if it is legitimate. My spam folder will not use any links in e-mails so I am protected against tricky image links and other misbehavior.
If I want future arrivals from the same source to go to my in box and not be diverted for spam review, I will specify that to my e-mail client. For those organizations that use bulk-mail forwarders and unique sender addresses per mail piece, that's too bad. They never get my approval and always show up in my spam folder, and if I'm busy I will never look at them.
Finally, if an e-mail is not legible in plaintext, even when sent as HTML, I am likely to just delete it unless it is something that I know is of interest to me by virtue of the source and previous valuable experiences.
As you can see, it is ultimately under an users control and there is no automated act that will convince such a system that your mail is legitimate from its structure alone. In this case, you need to play nice, don't do anything that is similar to phishing, and make it easy for users willing to trust your mail to add you to their white list.
one of my application's emails was constantly being tagged as spam. it was html with a single link, which i sent as html in the body with a text/html content type.
my most successful resolution to this problem was to compose the email so it looked like it was generated by an email client.
i changed the email to be a multipart/alternative mime document and i now generate both text/plain and text/html parts.
the email no longer is detected as junk by outlook.
Yahoo uses a method called Sender ID, which can be configured at The SPF Setup Wizard and entered in to your DNS. Also one of the important ones for Exchange, Hotmail, AOL, Yahoo, and others is to have a Reverse DNS for your domain. Those will knock out most of the issues. However you can never prevent a person intentionally blocking your or custom rules.
You need a reverse DNS entry. You need to not send the same content to the same user twice. You need to test it with some common webmail and email clients.
Personally I ran mine through a freshly installed spam assassin, a trained spam assassin, and multiple hotmail, gmail, and aol accounts.
But have you seen that spam that doesn't seem to link to or advertise anything? That's a spammer trying to affect your Bayesian filter. If he can get a high rating and then include some words that would be in his future emails it might be automatically learned as good. So you can't really guess what a user's filter is going to be set as at the time of your mailing.
Lastly, I did not sort my list by the domains, but randomized it.
I've found that using the recipients real first and last name in the body is a sure fire way of getting through a spam filter.
In the UK it's also best practice to include a real physical address for your company and its registered number.
That way it's all open and honest and they're less likely to manually mark it as spam.
I would add :
Provide real unsubscription upon click on "Unsubscribe". I've seen real newsletters providing a dummy unsubscription link that upon click shows " has been unsubscribed successfully" but I will still receive further newsletters.
The most important thing you can do is to make sure that the people you are sending email to are not likely going to hit the "Spam" button when they receive your email. So, stick to the following rules of thumb:
Make sure you have permission from the people you are sending email to. Don't ever send email to someone who did not request it from you.
Clearly identify who you are right at the top of each message, and why the person is receiving the email.
At least once a month, send out a reminder email to people on your list (if you are running a list), forcing them to opt back in to the list in order to keep receiving communications from you. Yes, this will mean your list gets shorter over time, but the up-side is that the people on your list are "bought in" and will be less likely to flag your email.
Keep your content highly relevant and useful.
Give people an easy way to opt out of further communications.
Use an email sending service like SendGrid that works hard to maintain a good IP reputation.
Avoid using short links - these are often blacklisted.
Following these rules of thumb will go a long way.
I have had the same problem in the past on many sites I have done here at work. The only guaranteed method of making sure the user gets the email is to advise the user to add you to there safe list. Any other method is really only going to be something that can help with it and isn't guaranteed.
It could very well be the case that people who sign up for your service are entering emails with typing mistakes that you do not correct. For example: chris#gmial.com -or- james#hotnail.com.
And such domains are configured to be used as spamtraps which will automatically flag your email server's IP and/or domain and hurt its reputation.
To avoid this, do a double-check for the email address that is entered upon your product subscription. Also, send a confirmation email to really ensure that this email address is 100% validated by a human being that is entering the confirmation email, before you send them the product key or accept their subscription. The verification email should require the recipient to click a link or reply in order to really confirm that the owner of the mailbox is the person who signed up.
It sounds like you are depending on some feedback to determine what is getting stuck on the receiving end. You should be checking the outbound mail yourself for obvious "spaminess".
Buy any decent spam control system, and send your outbound mail through it. If you send any decent volume of mail, you should be doing this anyhow, because of the risk of sending outbound viruses, especially if you have desktop windows users.
Proofpoint had spam + anti-virus + some reputation services in a single deployment, for example. (I used to work there, so I happen to know this off the top of my head. I'm sure other vendors in this space have similar features.) But you get the idea. If you send your mail through a basic commerical spam control setup, and it doesn't pass, it shouldn't be going out of your network.
Also, there are some companies that can assist you with increasing delivery rates of non-spam, outbound email, like Habeas.
Google has a tool and guidelines for this. You can find them on: https://postmaster.google.com/ Register and verify your domain name and Google provides an individual scoring of that IP-address and domain.
From the bulk senders guidelines:
Authentication ensures that your messages can be correctly classified. Emails that lack authentication are likely to be rejected or placed in the spam folder, given the high likelihood that they are forged messages used for phishing scams. In addition, unauthenticated emails with attachments may be outrightly rejected, for security reasons.
To ensure that Gmail can identify you:
Use a consistent IP address to send bulk mail.
Keep valid reverse DNS records for the IP address(es) from which you send mail, pointing to your domain.
Use the same address in the 'From:' header on every bulk mail you send.
We also recommend the following:
Sign messages with DKIM. We do not authenticate messages signed with keys using fewer than 1024 bits.
Publish an SPF record.
Publish a DMARC policy.
I always use:
https://www.mail-tester.com/
It gives me feedback on the technical part of sending an e-mail. Like SPF-records, DKIM, Spamassassin score and so on. Even though I know what is required, I continuously make errors and mail-tester.com makes it easy to figure out what could be wrong.
First of all, you need to ensure the required email authentication mechanisms like SPF and DKIM are in place. These two are prominent ways of proving that you were the actual sender of an email and it's not really spoofed. This reduces the chances of emails getting filtered as spam.
Second thing is, you can check the reverse DNS output of your domain name against different DNSBLs. Use below simple command on terminal:
**dig a +short (domain-name).(blacklist-domain-name)**
ie. dig a +short example.com.dsn.rfc-clueless.org
> 127.0.0.2
In the above examples, this means your domain "example.com" is listed in blacklist but due to Domain Setting Compliance(rfc-clueless.org list domain which has compliance issue )
note: I prefer multivalley and pepipost tool for checking the domain listings.
The from address/reply-to-id should be proper, always use visible unsubscribe button within your email body (this will help your users to sign out from your email-list without killing your domain reputation)
The intend of most of the programmatically generated emails is generally transactional, triggered or alert n nature- which means these are important emails which should never land into spam.
Having said that there are multiple parameters which are been considered before flagging an email as spam. While Quality of email list is the most important parameter to be considered, but I am skipping that here from the discussion because here we are talking about important emails which are sent to either ourself or to known email addresses.
Apart from list quality, the other 3 important parameters are;
Sender Reputation
Compliance with Email Standards and Authentication (SPF, DKIM, DMARC, rDNS)
Email content
Sender Reputation = Reputation of Sending IP address + Reputation of Return Path/Envelope domain + Reputation of From Domain.
There is no straight answer to what is your Sender Reputation. This is because there are multiple authorities like SenderScore, Reputation Authority and so on who maintains the reputation score for your domain. Apart from that ISPs like Gmail, Yahoo, Outlook also maintains the reputation of each domain at their end.
But, you can use free tools like GradeMyEmail to get a 360-degree view of your reputation and potential problems with your email settings or any other compliance-related issue too.
Sometimes, if you're using a new domain for sending an email, then those are also found to land in spam. You should be checking whether your domain is listed on any of the global blocklists or not. Again GradeMyEmail and MultiRBL are useful tools to identify the list of blocklists.
Once you're pretty sure with the sender reputation score, you should check whether your email sending domain complies with all email authentications and standards.
SPF
DKIM
DMARC
Reverse DNS
For this, you can again use GradeMyEmail or MXToolbox to know the potential problems with your authentication.
Your SPF, DKIM and DMARC should always PASS to ensure, your emails are complying with the standard email authentications.
Here's an example of how these authentications should look like in Gmail:
Similarly, you can use tools like Mail-Tester which scans the complete email content and tells the potential keywords which can trigger spam filters.
To allow DMARC checks for SPF to pass and also be aligned when using sendmail, make sure you are setting the envelope sender address (-f or -r parameter) to something that matches the domain in the From: header address.
With PHP:
Using PHP's built-in mail() function without setting the 5th paramater will cause DMARC SPF checks to be unaligned if not done correctly. By default, sendmail will send the email with the webserver's user as the RFC5321.MailFrom / Return Path header.
For example, say you are hosting your website domain.com on the host.com web server. If you do not set the additional parameters parameter:
mail($to,$subject,$message,$headers); // Wrong way
The email recipient will receive an email with the following mail headers:
Return-Path: <your-website-user#server.host.com>
From: <your-website-user#domain.com>
Even though this passes SPF checks, it will be unaligned (since domain.com and host.com do not match), which means that DMARC SPF check will fail as unaligned.
Instead, you must pass the envelope sender address to sendmail by including the 5th parameter in the PHP mail() function, for example:
mail($to,$subject,$message,$headers, '-r bounce_email#domain.com'); // Right way
In this case, the email recipient will receive an email with the following mail headers:
Return-Path: <bounce_email#domain.com>
From: <your-website-user#domain.com>
Since both of these headers contain addresses from domain.com, SPF will pass and also be aligned, which means that DMARC will also pass the SPF check.

Facebook Graph not returning email

UPDATE It seems that my personnal email address had not been used for years. Facebook marked it as inactive and did not return it as part of the JSON.
I am authenticating a user with Facebook on the client side using this url :
https://www.facebook.com/dialog/oauth?
client_id=xxx&
redirect_uri=https://www.facebook.com/connect/login_success.html&
scope=email
I receive a code I then exchange for a token :
https://graph.facebook.com/oauth/access_token?
code=xxx&
client_id=xxx&
client_secret=xxx&
redirect_uri=xxx
I then send the token to my server and I fetch the Fb Graph in order to get some user info, including the email.
https://graph.facebook.com/me?access_token=xxx
For some reason, I get all the user 'about' info, but not his/her email!
What did I do wrong?
According to the Facebook Documentation:
By default, not all the fields in a node or edge are returned when you
make a query. You can choose the fields (or edges) you want returned
with the "fields" query parameter. This is really useful for making
your API calls more efficient and fast.
This is valid from v2.4, (previous versions retrieved some default fields).
When you register a new app you are entitled automatically (without manual review) to three permissions: email, public_profile and user_friends. In your code "email" is in scope (which is good) so just change your query to:
https://graph.facebook.com/me?access_token=xxx&fields=email
You probably wanted the public_profile fields that you automatically got in previous versions of the API. Do so so, add "public_profile" to your scope:
https://www.facebook.com/dialog/oauth?
client_id=xxx&
redirect_uri=https://www.facebook.com/connect/login_success.html&
scope=email,public_profile
And now add the user name fields to your query:
https://graph.facebook.com/me?access_token=xxx&fields=first_name,last_name,gender,email,timezone,age_range,verified
Good luck

Categories

Resources