ASP.NET MVC Security Guard Membership using Profile for Additional User Data

Kita dapat menambahkan data user yang secara default disediakan oleh Security Guard / Membership. Misalnya kita mau menambahkan data nama lengkap user. Untuk menambahkan data tersebut, kita dapat menggunakan fitur Profile yang disediakan Membership.

1. Buat kelas profile yang berisi data-data tambahan user

[code language=”csharp”]

namespace WebUI.Models
{
public class UserProfile : ProfileBase
{
[SettingsAllowAnonymous(false)]
public string FullName
{
get { return base["FullName"] as string; }
set { base["FullName"] = value; }
}

[SettingsAllowAnonymous(false)]
public string GroupId
{
get { return base["GroupId"] as string; }
set { base["GroupId"] = value; }
}

[SettingsAllowAnonymous(false)]
public string DepartmentId
{
get { return base["DepartmentId"] as string; }
set { base["DepartmentId"] = value; }
}

public static UserProfile GetUserProfile(string username)
{
return Create(username) as UserProfile;
}

public static UserProfile GetUserProfile()
{
return Create(Membership.GetUser().UserName) as UserProfile;
}
}
}

[/code]

2. Mengubah web.config -> property inherits disesuaikan dengan class UserProfile

[code language=”xml”]

<profile defaultProvider="DefaultProfileProvider" inherits="WebUI.Models.UserProfile">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="UserManagement" applicationName="Mandiri" />
</providers>
</profile>

[/code]

3. Penambahan di fungsi Create user

[code language=”csharp”]
[HttpPost]
public virtual ActionResult CreateUser(viewModels.RegisterViewModel model)
{
MembershipUser user;
MembershipCreateStatus status;
user = membershipService.CreateUser(model.UserName, model.Password, model.Email, model.SecretQuestion, model.SecretAnswer, model.Approve, out status);
JsonResponse response = new JsonResponse();

if (user == null)
{
response.Success = false;
response.Message = status.ToString();
if (status == MembershipCreateStatus.InvalidPassword)
{
ModelState.AddModelError("", "Password must be at least 6 characters.");
}
else if (status == MembershipCreateStatus.InvalidEmail)
{
ModelState.AddModelError("", "The provided email is wrong.");
}
return RedirectToAction("CreateUser");
}
else
{
UserProfile profile = UserProfile.GetUserProfile(user.UserName);
profile.FullName = model.FullName;
profile.GroupId = model.GroupId.ToString();
profile.DepartmentId = model.DepartmentId.ToString();
profile.Save();
}

return routeHelpers.Actions.GrantRolesToUser(user.UserName);
}

[/code]

5. Penambahan atribut di model untuk update user

[code language=”csharp”]
public class UserViewModel
{
//…

[Required]
[Display(Name = "Nama Lengkap")]
public string FullName { get; set; }
}
[/code]

6. Perubahan di Controller & View update

[code language=”csharp”]
[HttpGet]
public ActionResult Update(string userName)
{
//…

UserProfile profile = UserProfile.GetUserProfile(user.UserName);
viewModel.FullName = profile.FullName;

return View(viewModel);
}
[/code]

[code language=”html”]
<div class="form-group">
@Html.LabelFor(model => model.FullName, new { @class = "col-xs-2 control-label" })
<div class="col-xs-4">
@Html.EditorFor(model => model.FullName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FullName)
</div>
</div>
[/code]

7. Penambahan di fungsi post Update user

[code language=”csharp”]
[HttpPost]
[MultiButtonFormSubmit(ActionName = "UpdateDeleteCancel", SubmitButton = "UpdateUser")]
public ActionResult UpdateUser(string UserName)
{
if (string.IsNullOrEmpty(UserName))
{
throw new ArgumentNullException("userName");
}

MembershipUser user = membershipService.GetUser(UserName);

try
{
user.Comment = Request["User.Comment"];
user.Email = Request["User.Email"];

membershipService.UpdateUser(user);

UserProfile profile = UserProfile.GetUserProfile(user.UserName);
profile.FullName = Request["FullName"];
profile.GroupId = Request["GroupId"];
profile.DepartmentId = Request["DepartmentId"];
profile.Save();

TempData["SuccessMessage"] = "The user was updated successfully!";

}
catch (Exception)
{
TempData["ErrorMessage"] = "There was an error updating this user.";
}

return RedirectToAction("Update", new { userName = user.UserName });
}

[/code]

http://www.codeproject.com/Articles/667595/Profile-Provider-in-Asp-Net-MVC

Chandra Oemaryadi has written 244 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>