Friday, August 12, 2016

Building a Note-Taking Software-as-a-Service Using ASP.NET MVC 5, Stripe, and Azure_part 1

What You'll Be Creating
1. Introduction

In this tutorial, I'm going to show you how to build a Software-as-a-Service (SaaS) minimum viable product (MVP). To keep things simple, the software is going to allow our customers to save a list of notes.

I am going to offer three subscription plans: the Basic plan will have a limit of 100 notes per user, the Professional plan will allow customers to save up to 10,000 notes, and the Business plan will allow a million notes. The plans are going to cost $10, $20 and $30 per month respectively. In order to receive payment from our customers, I'm going to use Stripe as a payment gateway, and the website is going to be deployed to Azure.

2. Setup 

2.1 Stripe
In a very short time Stripe has become a very well known Payment Gateway, mainly because of their developer-friendly approach, with simple and well-documented APIs. Their pricing is also very clear: 2.9% per transaction + 30 cents. No setup fees or hidden charges.

Credit card data is also very sensitive data, and in order to be allowed to receive and store that data in my server, I need to be PCI compliant. Because that's not an easy or quick task for most small companies, the approach that many payment gateways take is: You display the order details, and when the customer agrees to purchase, you redirect the customer to a page hosted by the payment gateway (bank, PayPal, etc), and then they redirect the customer back.

Stripe has a nicer approach to this problem. They offer a JavaScript API, so we can send the credit card number directly from the front-end to Stripe's servers. They return a one-time use token that we can save to our database. Now, we only need an SSL certificate for our website that we can quickly purchase from about $5 per year.

Now, sign up for a Stripe account, as you'll need it to charge your customers.

2.2 Azure
As a developer I don't want to be dealing with dev-ops tasks and managing servers if I don't have to. Azure websites is my choice for hosting, because it's a fully managed Platform-as-a-Service. It allows me to deploy from Visual Studio or Git, I can scale it easily if my service is successful, and I can focus on improving my application. They offer $200 to spend on all Azure services in the first month to new customers. That's enough to pay for the services that I am using for this MVP. Sign up for Azure.

2.3 Mandrill and Mailchimp: Transactional Email
Sending emails from our application might not seem like a very complex task, but I would like to monitor how many emails are delivered successfully, and also design responsive templates easily. This is what Mandrill offers, and they also let us send up to 12,000 emails per month for free. Mandrill is built by MailChimp, so they know about the business of sending emails. Also, we can create our templates from MailChimp, export them to Mandrill, and send emails from our app using our templates. Sign up for Mandrill, and sign up for MailChimp.

2.4 Visual Studio 2013 Community Edition
Last but not least, we need Visual Studio to write our application. This edition, which was launched only a few months ago, is completely free and is pretty much equivalent to Visual Studio Professional. You can download it here, and this is all we need, so now we can focus on the development.

3. Creating the Website

The first thing that we need to do is open Visual Studio 2013. Create a new ASP.NET Web Application:
  • Go to File > New Project and choose ASP.NET Web Application.
  • On the ASP.NET template dialog, choose the MVC template and select Individual User Accounts.

This project creates an application where a user can login by registering an account with the website. The website is styled using Bootstrap, and I'll continue building the rest of the app with Bootstrap. If you hit F5 in Visual Studio to run the application, this is what you will see:


This is the default landing page, and this page is one of the most important steps to convert our visitors into customers. We need to explain the product, show the price for each plan, and offer them the chance to sign up for a free trial. For this application I am creating three different subscription plans:
  • Basic: $10 per month
  • Professional: $20 per month
  • Business: $30 per month
3.1 Landing Page
For some help creating a landing page, you can visit ThemeForest and purchase a template. For this sample, I am using a free template, and you can see the final result in the photo below.


3.2 Registration Page
In the website that we created in the previous step, we also get a Registration form template. From the landing page, when you navigate to Prices, and click on Free Trial, you navigate to the registration page. This is the default design:


We only need one extra field here to identify the subscription plan that the user is joining. If you can see in the navigation bar of the photo, I am passing that as a GET parameter. In order to do that, I generate the markup for the links in the landing page using this line of code:
  1. <a href="@Url.Action("Register", "Account", new { plan = "business" })">
  2.     Free Trial
  3. </a>
To bind the Subscription Plan to the back-end, I need to modify the class RegisterViewModel and add the new property.
  1. public class RegisterViewModel
  2. {
  3.     [Required]
  4.     [EmailAddress]
  5.     [Display(Name = "Email")]
  6.     public string Email { get; set; }
  7.  
  8.     [Required]
  9.     [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
  10.     [DataType(DataType.Password)]
  11.     [Display(Name = "Password")]
  12.     public string Password { get; set; }
  13.  
  14.     [DataType(DataType.Password)]
  15.     [Display(Name = "Confirm password")]
  16.     [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
  17.     public string ConfirmPassword { get; set; }
  18.  
  19.     public string SubscriptionPlan { get; set; }
  20. }
I also have to edit AccountController.cs, and modify the Action Register to receive the plan:
  1. [AllowAnonymous]
  2. public ActionResult Register(string plan)
  3. {
  4.     return View(new RegisterViewModel
  5.     {
  6.         SubscriptionPlan = plan
  7.     });
  8. }
Now, I have to render the Plan Identifier in a hidden field in the Register form:
  1. @Html.HiddenFor(m => m.SubscriptionPlan)
The last step will be to subscribe the user to the plan, but we'll get to that a bit later. I also update the design of the registration form.




3.3 Login Page

 In the template we also get a login page and action controllers implemented. The only thing I need to do is to make it look prettier.


3.4 Forgot Password
Take a second look at the previous screenshot, and you'll notice that I added a "Forgot your Password?" link. This is already implemented in the template, but it's commented out by default. I don't like the default behaviour, where the user needs to have the email address confirmed to be able to reset the password. Let's remove that restriction. In the file AccountController.cs edit the action ForgotPassword:
  1. [HttpPost]
  2. [AllowAnonymous]
  3. [ValidateAntiForgeryToken]
  4. public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
  5. {
  6.     if (ModelState.IsValid)
  7.     {
  8.         var user = await UserManager.FindByNameAsync(model.Email);
  9.         if (user == null)
  10.         {
  11.             // Don't reveal that the user does not exist or is not confirmed
  12.             return View("ForgotPasswordConfirmation");
  13.         }
  14.  
  15.         // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
  16.         // Send an email with this link
  17.         // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
  18.         // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);       
  19.         // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
  20.         // return RedirectToAction("ForgotPasswordConfirmation", "Account");
  21.     }
  22.  
  23.     // If we got this far, something failed, redisplay form
  24.     return View(model);
  25. }
The code to send the email with the link to reset the password is commented out. I'll show how to implement that part a bit later. The only thing left for now is to update the design of the pages:
  • ForgotPassword.cshtml: Form that is displayed to the user to enter his or her email.
  • ForgotPasswordConfirmation.cshtml: Confirmation message after the reset link has been emailed to the user.
  • ResetPassword.cshtml: Form to reset the password after navigating to the reset link from the email.
  • ResetPasswordConfirmation.cshtml: Confirmation message after the password has been reset.

4. ASP.NET Identity 2.0

ASP.NET Identity is a fairly new library that has been built based on the assumption that users will no longer log in by using only a username and password. OAuth integration to allow users to log in through social channels such as Facebook, Twitter, and others is very easy now. Also, this library can be used with Web API, and SignalR. 

On the other hand, the persistence layer can be replaced, and it's easy to plug in different storage mechanisms such as NoSQL databases. For the purposes of this application, I will use Entity Framework and SQL Server.

The project that we just created contains the following three NuGet packages for ASP.NET Identity:
  • Microsoft.AspNet.Identity.Core: This package contains the core interfaces for ASP.NET Identity.
  • Microsoft.AspNet.Identity.EntityFramework: This package has the Entity Framework implementation of the previous library. It will persist the data to SQL Server.
  • Microsoft.AspNet.Identity.Owin: This package plugs the middle-ware OWIN authentication with ASP.NET Identity.
The main configuration for Identity is in App_Start/IdentityConfig.cs. This is the code that initializes Identity.
  1. public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
  2. {
  3.     var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
  4.     // Configure validation logic for usernames
  5.     manager.UserValidator = new UserValidator<ApplicationUser>(manager)
  6.     {
  7.         AllowOnlyAlphanumericUserNames = false,
  8.         RequireUniqueEmail = true
  9.     }; 
  10.     // Configure validation logic for passwords
  11.     manager.PasswordValidator = new PasswordValidator
  12.     {
  13.         RequiredLength = 6,
  14.         RequireNonLetterOrDigit = true,
  15.         RequireDigit = true,
  16.         RequireLowercase = true,
  17.         RequireUppercase = true,
  18.     };
  19.     // Configure user lockout defaults
  20.     manager.UserLockoutEnabledByDefault = true;
  21.     manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
  22.     manager.MaxFailedAccessAttemptsBeforeLockout = 5; 
  23.     // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
  24.     // You can write your own provider and plug it in here.
  25.     manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
  26.     {
  27.         MessageFormat = "Your security code is {0}"
  28.     });
  29.     manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
  30.     {
  31.         Subject = "Security Code",
  32.         BodyFormat = "Your security code is {0}"
  33.     });
  34.     manager.EmailService = new EmailService();
  35.     manager.SmsService = new SmsService();
  36.     var dataProtectionProvider = options.DataProtectionProvider;
  37.     if (dataProtectionProvider != null)
  38.     {
  39.         manager.UserTokenProvider = 
  40.             new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
  41.     }
  42.     return manager;
  43. }
As you can see in the code, it's pretty easy to configure users' validators and password validators, and two factor authentication can also be enabled. For this application, I use cookie-based authentication. The cookie is generated by the framework and is encrypted. This way, we can scale horizontally, adding more servers if our application needs it.
Written by Pedro Alonso

If you found this post interesting, follow and support us.
Suggest for you:

No comments:

Post a Comment