Forms authentication in Lightswitch using MVC Part 4

Rama Sagar
Posted by in LightSwitch category on for Beginner level | Points: 250 | Views : 9204 red flag

Forms authentication is managed by the application itself, and a user must supply a username and a password to access the application

Introduction


In this article we will see how to add controller and perform login ,Registration and change password to the project which we have created in part3..

Before we proceed please check previous articles on Light switch Part 1,Part 2 and Part 3


Add The Controller


  •  Step 1:Add a class called AccountController.cs to the Controllers folder and use the following Implementation




using System;
using System.Web.Mvc;
using System.Web.Security;
using Microsoft.LightSwitch.Security.ServerGenerated.Implementation;
using LightSwitchApplication.Models;
namespace LightSwitchApplication.Controllers
{
    public class AccountController : Controller
    {
   
        // Register - Create a new user
      
        public ActionResult Register()
        {
            return View(new Users());
        }
        [HttpPost]
        public ActionResult Register(FormCollection collection)
        {
            try
            {
                var UserName = collection["UserName"];
                var Password = collection["Password"];
                var Email = collection["Email"];
                if (UserName == "")
                {
                    throw new Exception("No UserName");
                }
                if (Password == "")
                {
                    throw new Exception("No Password");
                }
                // Keep our UserName as LowerCase
                UserName = UserName.ToLower();
                // Create LightSwitch user
                MembershipUser objMembershipUser = Membership.CreateUser(UserName, Password, Email);
                // Log User in
                // Create a new instance of the LightSwitch Authentication Service
                using (var authService = new AuthenticationService())
                {
                    var LoggedInUser = authService.Login(
                        UserName,
                        Password,
                        false,
                        null);
                    // Successful login?  If so, return the user
                    if (LoggedInUser != null)
                    {
                        return Redirect("~/Home");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "Login failed.");
                        return View();
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(
                    string.Empty, "Error: " + ex);
                return View();
            }
        }
       
        // ChangePassword - Change the password of an existing user
       
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View(new ChangePassword());
        }
        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(FormCollection collection)
        {
            try
            {
                using (var authService = new AuthenticationService())
                {
                    //checks whether new passowrd and confirm passowrd matches

                    if (collection["NewPassword"] != collection["ConfirmPassword"])
                    {
                        throw new Exception("New Password and Confirm Password must match");
                    }
                    if (!Membership.GetUser()
                        .ChangePassword(collection["OldPassword"], collection["NewPassword"]))
                    {
                        throw new Exception("Password change failed.");
                    }
                    return Redirect("~/Home");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Error: " + ex);
                return View();
            }
        }
      
        // Login - Log a user in, return authentication cookie
       
        public ActionResult Login()
        {
            return View(new Users());
        }
        [HttpPost]
        public ActionResult Login(FormCollection collection)
        {
            try
            {
                // Create a new instance of the LightSwitch Authentication Service
                using (var authService = new AuthenticationService())
                {
                    // Log User in
                    var user = authService.Login(
                        collection["UserName"].ToLower(),
                        collection["Password"],
                        Convert.ToBoolean(collection["Persistent"]),
                        null);
                    // Successful login?  If so, return the user
                    if (user != null)
                    {
                        return Redirect("~/Home");
                    }
                    else
                    {
                        //Throws an error

                        ModelState.AddModelError(string.Empty,
                            "Login failed.  Check User Name and/or Password.");
                        return View();
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Error: " + ex.Message);
                return View();
            }
        }
      
        // LogOff - Clears the cookie, logging a user out of the system
       
        public ActionResult LogOff()
        {
            // Create a new instance of the LightSwitch Authentication Service
            using (var authService = new AuthenticationService())
            {
                var user = authService.Logout();
                return Redirect("~/Home");
            }
        }
    }
}
  • Step 2:Now Lets modify Index.cshtml with the following




@{
    Layout = null;
}
@using Microsoft.AspNet.Identity
<!DOCTYPE html>
<html>
<head>
    <meta name="HandheldFriendly" content="true" />
    <meta name="viewport" content="width=device-width,
          initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no" />
    <title>Log In</title>
</head>
<body>
    <div>
        @if (Request.IsAuthenticated)
        {
            using (Html.BeginForm("LogOut", "Account",
                FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
            {
                @Html.AntiForgeryToken()
                <p>
                    Hello @User.Identity.GetUserName() |
                    @Html.ActionLink("Change Password",
                    "ChangePassword", "Account",
                    routeValues: null, htmlAttributes: new { id = "changepassword" }) |
                    <a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>
                </p>
                <a href="HTMLClient">LightSwitch Application</a>
            }
        }
        else
        {
            <p>
                @Html.ActionLink("Register", "Register", "Account",
                routeValues: null, htmlAttributes: new { id = "registerLink" }) |
                @Html.ActionLink("Log in", "Login", "Account",
                routeValues: null, htmlAttributes: new { id = "loginLink" })
            </p>
        }
    </div>
</body>
</html>

Debug the Application and check 


Conclusion

In this article we have seen  how to add controller and perform login ,Registration and change password

Reference

http://msdn.microsoft.com/en-us/library/ff851957.aspx
Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Posted by: Sheonarayan on: 12/12/2013 | Points: 25
Thanks Rama Sagar, you are going great !

Just a suggestion that may make it more easily understandable - It would be nice to explain methods and codes written in the code snippets block even if they are looking self understood as it might be self understood for all.

Thanks and keep it up!

Login to post response

Comment using Facebook(Author doesn't get notification)