Sunday, April 15, 2018

How to change password in MVC application


In this article I am going to explain how to change password in MVC application. 

Description:
I want to add change password functionality for logged in users. To change password users have to enter current password, after that new password and confirm the new password.
  

Implementations:
Please check the previous post Create login form and maintain authenticated user’s detail in MVC application.

Model

public partial class Login
    {
        public int Id { get; set; }
        [Required(ErrorMessage = "Please enter username")]
        [DisplayFormat(ConvertEmptyStringToNull = true)]
        [Display(Name = "Username")]

        public string Username { get; set; }

        [Required(ErrorMessage = "Please enter password")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Confirm password")]
        [Required(ErrorMessage = "Please enter confirm password")]

        [DataType(DataType.Password)]
        public string Confirmpwd { get; set; }

        public Nullable<bool> Is_Deleted { get; set; }
    }


Controller:
Complete code of controller:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2017.Models;
using System.Security.Cryptography;
using System.Configuration;
using System.Net.Mail;
using System.Net;
using System.IO;
using System.Web.Security;
using System.Drawing;
using System.Data;

namespace mvcapplication2017.Controllers
{
  
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        DemoEntities db = new DemoEntities();
        public ActionResult Index()
       {
            return View();
        }
        [HttpPost]
        public ActionResult Index(Login objlogin)
        {
           
                if (ModelState.IsValidField("Username") && ModelState.IsValidField("Password"))
                {
                    var login = db.Logins.Where(u => u.Is_Deleted == false && u.Username.Equals(objlogin.Username) && u.Password.Equals(objlogin.Password)).FirstOrDefault();
                    if (login != null)
                    {
                        TempData["user"] = login.Username;
                        TempData["id"] = login.Id;
                       
                        TempData.Keep("id");TempData.Keep("user");
                        return RedirectToAction("dashboard");
                    }
                    else
                    {
                        TempData["msg"] = "<script>alert('Username and Password does not match');</script>";
                    }
                }
         
            return View(objlogin);
        }
        public ActionResult dashboard()
        {
            if (TempData["user"]==null)
            {
                return RedirectToAction("index");
            }
            else { }
            return View();
        }
        [HttpPost]
        public ActionResult dashboard(string Password, string newPassword, string Confirmpwd)
        {
            Login objlogin = new Login();
            string user = TempData["user"].ToString();
            int id =int.Parse(TempData["id"].ToString());
            var login = db.Logins.Where(u => u.Is_Deleted == false && u.Username.Equals(user) && u.Id.Equals(id)).FirstOrDefault();
            if (login.Password == Password)
            {
                if (Confirmpwd == newPassword)
                    {
                        login.Confirmpwd = Confirmpwd;
                        login.Password = newPassword;
                        db.Entry(login).State = EntityState.Modified;
                        db.SaveChanges();
                        TempData["msg"] = "<script>alert('Password has been changed successfully !!!');</script>";
                    }
                else
                {
                    TempData["msg"] = "<script>alert('New password match !!! Please check');</script>";
                }
            }
            else
            {
                TempData["msg"] = "<script>alert('Old password not match !!! Please check entered old password');</script>";
            }
            return View();
        }
        public ActionResult Createuser()
        {
           
            return View();
        }
        public ActionResult About()
        {
            return View();
        }
        public ActionResult LogOut()
        {
            TempData.Remove("user");
            return RedirectToAction("index","login");
        }
    }
}




Add view
Add view for dashboard action. On this view user can see his information (name) and add form to change password.

Complete source of dashboard view:

@{
    ViewBag.Title = "dashboard";
    TempData.Keep("user");
    TempData.Keep("id");
}

<div style="width:auto;float:right">
    @if (@TempData["user"] != null)
    {
     <span>Welcome : </span> @TempData["user"] <span> | </span> @Html.ActionLink("Log Out", "Logout", "login")
    }
    else
    {
        @Html.ActionLink("Register", "Register", "User")
        <span> | </span>
        @Html.ActionLink("Log In", "Login", "User")
    }
</div>
<div style="text-align: center; padding-top: 50px;">
    <h3>Welcome to aspmantra</h3>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <fieldset>
        <legend>Change Password</legend>
       <table>
           <tr>
               <td>@Html.Label("Old Password", new { @for = "Password" }) :  </td>
               <td>@Html.Password("Password")</td>
           </tr>
           <tr>
               <td>@Html.Label("New Password", new { @for = "newPassword" }) :</td>
               <td>@Html.Password("newPassword")</td>
           </tr>
           <tr>
               <td>@Html.Label("Confirm Password", new { @for = "Confirmpwd" }) : </td>
               <td>@Html.Password("Confirmpwd")</td>
           </tr>
           <tr>
               <td></td>
               <td><input type="submit" value="Change Password" /></td>
           </tr>
       </table>      
</fieldset>
}
</div>@Html.Raw(TempData["msg"])


1 comment: