Swift2 Firebase: Is the email check done on the backend server? [duplicate] - swift

Question says it all. In Firebase, how do I confirm email when a user creates an account, or, for that matter, do password reset via email.
I could ask more broadly: is there any way to send emails out from Firebase? E.g. notifications, etc. This isn't the kind of thing you would usually do client-side.

Update
Note that this was never a very secure way of handling email verification, and since Firebase now supports email verification, it should probably be used instead.
Original answer
I solved the email verification using the password reset feature.
On account creation I give the user a temporary (randomly generated) password. I then trigger a password reset which will send an email to the user with a link. The link will allow the user to set a new password.
To generate a random password you can use code similar to this:
function () {
var possibleChars = ['abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!?_-'];
var password = '';
for(var i = 0; i < 16; i += 1) {
password += possibleChars[Math.floor(Math.random() * possibleChars.length)];
}
return password;
}
Note that this is happening on the client, so a malicious user could tamper with your logic.

This would need to be done outside of firebase. I store users at /users/ and keep a status on them (PENDING, ACTIVE, DELETED). I have a small service that monitors users of a PENDING status and sends out a confirmation email. Which has a link to a webservice I've created to update the user status to ACTIVE.

[Engineer at Firebase - Update 2014-01-27]
Firebase Simple Login now supports password resets for email / password authentication.
Each of the Simple Login client libraries has been given a new method for generating password reset emails for the specified email address - sendPasswordResetEmail() on the Web and Android, and sendPasswordResetForEmail() on iOS.
This e-mail will contain a temporary token that the user may use to log into their account and update their credentials. This token will expire after 24 hours or when the user changes their password, whichever occurs first.
Also note that Firebase Simple Login enables full configuration of the email template as well as the sending address (including whitelabel email from your domain for paid accounts).
To get access to this feature, you'll need to update your client library to a version of v1.2.0 or greater. To grab the latest version, check out https://www.firebase.com/docs/downloads.html.
Also, check out https://www.firebase.com/docs/security/simple-login-email-password.html for the latest Firebase Simple Login - Web Client docs.

As at 2016 July, you might not have to use the reset link etc. Just use the sendEmailVerification() and applyActionCode functions:
In short, below is basically how you'll approach this, in AngularJS:
// thecontroller.js
$scope.sendVerifyEmail = function() {
console.log('Email sent, whaaaaam!');
currentAuth.sendEmailVerification();
}
// where currentAuth came from something like this:
// routerconfig
....
templateUrl: 'bla.html',
resolve: {
currentAuth:['Auth', function(Auth) {
return Auth.$requireSignIn() // this throws an AUTH_REQUIRED broadcast
}]
}
...
// intercept the broadcast like so if you want:
....
$rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
if (error === "AUTH_REQUIRED") {
$state.go('login', { toWhere: toState });
}
});
....
// So user receives the email. How do you process the `oobCode` that returns?
// You may do something like this:
// catch the url with its mode and oobCode
.state('emailVerify', {
url: '/verify-email?mode&oobCode',
templateUrl: 'auth/verify-email.html',
controller: 'emailVerifyController',
resolve: {
currentAuth:['Auth', function(Auth) {
return Auth.$requireSignIn()
}]
}
})
// Then digest like so where each term is what they sound like:
.controller('emailVerifyController', ['$scope', '$stateParams', 'currentAuth', 'DatabaseRef',
function($scope, $stateParams, currentAuth, DatabaseRef) {
console.log(currentAuth);
$scope.doVerify = function() {
firebase.auth()
.applyActionCode($stateParams.oobCode)
.then(function(data) {
// change emailVerified for logged in User
console.log('Verification happened');
})
.catch(function(error) {
$scope.error = error.message;
console.log(error.message, error.reason)
})
};
}
])
And ooh, with the above approach, I do not think there's any need keeping the verification of your user's email in your user data area. The applyActionCode changes the emailVerified to true from false.
Email verification is important when users sign in with the local account. However, for many social authentications, the incoming emailVerified will be true already.
Explained more in the article Email Verification with Firebase 3.0 SDK

What I did to work around this was use Zapier which has a built in API for firebase. It checks a location for added child elements. Then it takes the mail address and a verification url from the data of new nodes and sends them forwards. The url points back to my angular app, which sets the user email as verified.
As I host my app files in firebase, I don't need have to take care of any servers or processes doing polling in the background.
There is a delay, but as I don't block users before verifying mails it's ok. Zapier has a free tier and since I don't have much traffic it's a decent workaround for time being.

The new Firebase SDK v3 appears to support email address verification, see here (put your own project id in the link) but it doesn't appear to be documented yet.
I have asked the question on SO here
See #SamQuayle's answer there with this link to the official docs.

As noted by various others Firebase does now support account related emails but even better, as of 10 days ago or so it also supports sending any kind of email via Firebase Functions. Lots of details in the docs and example code here.

I used following code to check the email verification after creating new account.
let firAuth = FIRAuth.auth()
firAuth?.addAuthStateDidChangeListener { auth, user in
if let loggedUser = user {
if loggedUser.emailVerified == false {
loggedUser.sendEmailVerificationWithCompletion({ (error) in
print("error:\(error)")
})
}
else {
print(loggedUser.email)
}
} else {
// No user is signed in.
print("No user is signed in.")
}
}

I used MandrillApp. You can create an API key that only allows sending of a template. This way even thought your key is exposed it can't really be abused unless someone wants to fire off tonnes of welcome emails for you.
That was a hack to get myself off the ground. I'm now enabling CORS from a EC2 that uses the token to verify that the user exists before extending them a welcome via SES.

Related

Perform extra validation after a Student signs into Moodle

I am hoping someone can point me in the right direction. We host a University Moodle site and we are looking for a way in which we can perform extra validation on a Student whenever they login. I will give a scenario.
We have an endpoint with a list of email addresses of students allowed to use the system, for example a list of Students who are fully paid up on tuition. Therefore, we are looking for a way to hook into the login process, perform this check and the allow the student to continue or redirect back to the login page with an error.
I would appreciate any advice on how we can achieve this. Thank you.
I found a solution to my problem. I ended up creating a custom Authentication plugin using the guidelines from https://docs.moodle.org/dev/Authentication_plugins. With that knowledge, I used the copied the folder in the Moodle installation path auth/none and used that as a shell for my new plugin. I went ahead and customized the plugin names to what I needed. Once that was done and once the plugin was installed and enabled from the Administrator Dashboard, I had something like this in my auth.php file:
// Required for all auth plugins
public function user_login($username, $password)
{
return false;
}
// Hooks in immediately after the User submits the login form
public function loginpage_hook()
{
$username = $_REQUEST['username'] ?? '';
/** CODE CHECKING IF USERNAME IS ALLOWED TO ACCESS MOODLE **/
/** FOR EXAMPLE CHECK IF USER PAID FEES **/
$userHasPaidFees = api_checks_if_user_paid_fees($username);
if ($userHasPaidFees ) {
// Returning true here proceeds with the
// normal Username/Password login combination
return true;
}
// If not, redirect them back to Login
// Or any other page and notify
redirect(
new moodle_url('/login/index.php'),
'Message telling user why they were not able to sign in',
null,
\core\output\notification::NOTIFY_ERROR
);
}
Thanks and I hope someone finds this useful.

I am using NSSharingService in my macOS Swift app. Is there any way to make sure the default mail client is configured with a valid account?

I am using NSSharingService to prepare an email with attachment for the user of my macOS app. My code is:
let emailService = NSSharingService.init(named: NSSharingService.Name.composeEmail)
if emailService.canPerform(withItems: [emailBody, zipFileURL]) {
// email can be sent
DispatchQueue.main.async {
emailService.perform(withItems: [emailBody, zipFileURL])
}
} else {
// email cannot be sent
// Show alert with email address and instructions
self.showErrorAlert(with: 2803)
}
This works correctly, but if the code is executed on a fresh system, Apple Mail will be opened asking the user to configure an email account. Some users may not understand what is going on in this situation. Is there a way to ascertain if the default Email Client is configured, so that I can inform the user if it is not ? Thanks for your help.

Checking if a user already signed up

I built a custom authentication system using FirebaseAuthentication tokens.
My signup / login flow should work like this:
User presses login button
My server generates the authentication token and sends it to the client
Check if the user already exists (in the 'Auth' table or in my database?)
If true: sign in using FIRAuth.auth()?.signIn(withCustomToken:...
If false: Show a form to to enter custom information (name, etc..)
sign using FIRAuth.auth()?.signIn(withCustomToken:...
save the custom information to my database
My question is: How can I find out if the user has already signed up?
Would a publicly accessible database with only uid's be the way to go?
This is fairly opinion based, but yes, I would use a standalone DB that stores each user's username who has signed up. Then all that is required is a quick web request through a PHP file querying for any rows returned with that username.
The firebase sign in method will feedback in asynchronous callback.
FIRAuth.auth()?.signInWithEmail(email, password: password, completion: { (user , error) in
if let error = error {
print(error.localizedDescription)
return
}
self.signedIn(user)
})
If you haven't sign up yet. The error will print out
There is no user record corresponding to this identifier. The user may have been deleted.

Google Sign-In with Passportjs not getting authenticated

I'm using Sails with Passport for authentication. I'm using passport-google-oauth(OAuth2Strategy) and passport-facebook for enabling Google Sign-in.
I'm not too well-versed with Passport, so pardon me if this is a rookie question. I've set up login via Facebook and it works just fine. With Google, I do receive an authorization code after allowing access to the app, but the I'm eventually not authenticated. I'm guessing the same code should work for both Facebook and Google since the strategies are both based on oauth2.
I'm not even sure what code to share, since I'm using the auto-generated code from sails-generate-auth, but do let me know if there's anything else I can share.
Any ideas on why this might be happening? The app is locally hosted but that's unlikely to be the problem since I am getting to the authorization stage anyway.
I faced the same problem and it was located here in in api/services/passport.js:
// If the profile object contains a list of emails, grab the first one and
// add it to the user.
if (profile.hasOwnProperty('emails')) {
user.email = profile.emails[0].value;
}
// If the profile object contains a username, add it to the user.
if (profile.hasOwnProperty('username')) {
user.username = profile.username;
}
// If neither an email or a username was available in the profile, we don't
// have a way of identifying the user in the future. Throw an error and let
// whoever's next in the line take care of it.
if (!user.username && !user.email) {
return next(new Error('Neither a username nor email was available'));
}
The Google service was not returning a profile.username property.
Because of it, the user is not saved in the database and cannot be authenticated. Then the passport callback receives an empty user, so the function that handles errors is fired and the user is redirected to the login page.
This change allows to use the displayName property as the username:
// If the profile object contains a list of emails, grab the first one and
// add it to the user.
if (profile.hasOwnProperty('emails')) {
user.email = profile.emails[0].value;
}
// If the profile object contains a username, add it to the user.
if (profile.hasOwnProperty('username')) {
user.username = profile.username;
}
/** Content not generated BEGIN */
// If the username property was empty and the profile object
// contains a property "displayName", add it to the user.
if (!user.username && profile.hasOwnProperty('displayName')) {
console.log(profile); // <= Use it to check the content given by Google about the user
user.username = profile.displayName;
}
/** Content not generated END */
// If neither an email or a username was available in the profile, we don't
// have a way of identifying the user in the future. Throw an error and let
// whoever's next in the line take care of it.
if (!user.username && !user.email) {
return next(new Error('Neither a username nor email was available'));
}
You could also use the profile.id property because profile.displayName is not necessarily unique (ie: two Google accounts can have an identical displayName). But it is also true accross different services: a Twitter account could also have the same username than a Facebook account. If both register on your application, you will have a bug. This is a problem from the code generated by sails-generate-auth and you should adapt it with the behavior that you want.
I will propose a PR if this solution works for you too.
Alright, so this ultimately turned out to be a known issue with the API.
TL;DR: Enable the Google+ API and the Contacts API as mentioned here. (The Contacts API isn't required, as #AlexisN-o pointed out in the comments. My setup worked as desired with Contacts API disabled. This obviously depends on what scope you're using.)
I believe it's not a nice way of failing since this was an API error that was prevented from bubbling up. Anyway, I dug into passport.authenticate to figure out what was going wrong. This eventually calls the authenticate method defined in the package corresponding to the strategy (oauth2 in this case). In here (passport-google-oauth/lib/passport-google-oauth/oauth2.js) I found that the accessToken was indeed being fetched from Google, so things should be working. This indicated that there was a problem with the requests being made to the token urls. So I ventured a little further into passport-oauth2/lib/strategy.js and finally managed to log this error:
{ [InternalOAuthError: failed to fetch user profile]
name: 'InternalOAuthError',
message: 'failed to fetch user profile',
oauthError:
{ statusCode: 403,
data: '{
"error": {
"errors": [{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured. The API (Google+ API) is not enabled for your project. Please use the Google Developers Console to update your configuration.",
"extendedHelp": "https://console.developers.google.com"
}],
"code": 403,
"message": "Access Not Configured. The API (Google+ API) is not enabled for your project. Please use the Google Developers Console to update your configuration."
}
}'
} }
This was the end of the hunt for me and the first result for the error search led to the correct answer. Weird fix though.

Generating a verification token in Meteor without sending an email?

In my meteor app, I'm setting up the registration process.
Meteor has a Account.sendVerificationEmail method to send emails out to new users with a token to verify their email address
My app does need this functionality but I don't really want to use the sendVerificationEmail to send the emails because I already have my own email helper which has got a bunch of logic and I want all the emails in my system to pass to flow out of that function.
So my question is that I do want to create my verification token for the user on registration, but I don't want sendVerificationEmail to send an email out because I want to do it manually.
Is this possible?
First add the core "random" package for random code generation
$ meteor add random
Then intercept the account creation process
Accounts.onCreateUser(function(options, user) {
// create a verified flag and set it false
user.customVerified = false;
//20 character random lowercase hex string. You can use a hash of some user info if you like. I just put this here for demonstration of the concept :)
user.customVerificationCode = Random.hexString(20).toLowerCase();
//pass the new user's email and the verification code to your custom email function so that you can craft and send the mail. Please double check the option.profile.emails[0], the email should be available somewhere within the options object
myCustomEmailFunction(options.profile.emails[0], user.customVerificationCode);
// continue with account creation
return user;
});
At this point, if you don't want to show pieces of ui elements to unverified users, you can create a template helper for that. Or you can check if user is verified in your publications. Etc... whatever you want to restrict.
Now you can define a route in your app with iron router so that when the user clicks on the link, the route takes the verification code and set's the user's verified flag to true.
You can fake the verification record for the user in the MongoDB document and then send your own email:
//Fake the verificationToken by creating our own token
var token = Random.secret();
var tokenRecord = {
token: token,
address: Meteor.user().emails[0].address,
when: new Date(),
};
//Save the user
Meteor.users.update(
{_id: Meteor.userId()},
{$push: {'services.email.verificationTokens': tokenRecord}}
, function(err){
//Send an email containing this URL
var confirmUrl = Meteor.absoluteUrl() + '#/verify-email/' + token;
//Send using SendGrid, Mandrill, MailGun etc
});
Code taken from GitHub:
https://github.com/meteor/meteor/blob/5931bcdae362e1026ceb8a08e5a4b053ce5340b7/packages/accounts-password/password_server.js