Skip to content
This repository has been archived by the owner on Jul 6, 2020. It is now read-only.

Commit

Permalink
Added GetCurrentUserAsync
Browse files Browse the repository at this point in the history
  • Loading branch information
VahidN committed Aug 13, 2015
1 parent 2fb9b12 commit ce71219
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 27 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Data.Entity;
using System.Security.Principal;
using System.Threading;
using System.Web;
using AspNetIdentityDependencyInjectionSample.DataLayer.Context;
Expand Down Expand Up @@ -28,6 +29,8 @@ private static Container defaultContainer()
{
return new Container(ioc =>
{
ioc.For<IIdentity>().Use(() => HttpContext.Current.User != null ? (HttpContext.Current != null ? HttpContext.Current.User.Identity : null) : null);
ioc.For<IUnitOfWork>()
.HybridHttpOrThreadLocalScoped()
.Use<ApplicationDbContext>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
using System.Collections.Generic;
using System.Data.Entity;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using AspNetIdentityDependencyInjectionSample.DataLayer.Context;
using AspNetIdentityDependencyInjectionSample.DomainClasses;
using AspNetIdentityDependencyInjectionSample.ServiceLayer.Contracts;
using Microsoft.AspNet.Identity;
Expand All @@ -16,17 +18,27 @@ public class ApplicationUserManager
: UserManager<ApplicationUser, int>, IApplicationUserManager
{
private readonly IDataProtectionProvider _dataProtectionProvider;
private readonly IIdentity _identity;
private readonly IApplicationRoleManager _roleManager;
private readonly IUserStore<ApplicationUser, int> _store;
private readonly IUnitOfWork _uow;
private readonly IDbSet<ApplicationUser> _users;

private ApplicationUser _user;

public ApplicationUserManager(IUserStore<ApplicationUser, int> store,
IUnitOfWork uow,
IIdentity identity,
IApplicationRoleManager roleManager,
IDataProtectionProvider dataProtectionProvider,
IIdentityMessageService smsService,
IIdentityMessageService emailService)
: base(store)
{
_store = store;
_uow = uow;
_identity = identity;
_users = _uow.Set<ApplicationUser>();
_roleManager = roleManager;
_dataProtectionProvider = dataProtectionProvider;
this.SmsService = smsService;
Expand All @@ -35,6 +47,11 @@ public class ApplicationUserManager
createApplicationUserManager();
}

public ApplicationUser FindById(int userId)
{
return _users.Find(userId);
}

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUser applicationUser)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
Expand All @@ -43,6 +60,26 @@ public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUser appl
return userIdentity;
}

public Task<List<ApplicationUser>> GetAllUsersAsync()
{
return this.Users.ToListAsync();
}

public ApplicationUser GetCurrentUser()
{
return _user ?? (_user = this.FindById(GetCurrentUserId()));
}

public async Task<ApplicationUser> GetCurrentUserAsync()
{
return _user ?? (_user = await this.FindByIdAsync(GetCurrentUserId()));
}

public int GetCurrentUserId()
{
return _identity.GetUserId<int>();
}

public async Task<bool> HasPassword(int userId)
{
var user = await FindByIdAsync(userId);
Expand Down Expand Up @@ -143,10 +180,5 @@ private async Task<ClaimsIdentity> generateUserIdentityAsync(ApplicationUserMana
// Add custom user claims here
return userIdentity;
}

public Task<List<ApplicationUser>> GetAllUsersAsync()
{
return this.Users.ToListAsync();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -552,5 +552,9 @@ public interface IApplicationUserManager : IDisposable
Task<bool> HasPhoneNumber(int userId);
void SeedDatabase();
Task<List<ApplicationUser>> GetAllUsersAsync();
ApplicationUser FindById(int userId);
ApplicationUser GetCurrentUser();
Task<ApplicationUser> GetCurrentUserAsync();
int GetCurrentUserId();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ public class ManageController : Controller

private readonly IAuthenticationManager _authenticationManager;
private readonly IApplicationUserManager _userManager;
public ManageController(IApplicationUserManager userManager, IAuthenticationManager authenticationManager)
public ManageController(
IApplicationUserManager userManager,
IAuthenticationManager authenticationManager)
{
_userManager = userManager;
_authenticationManager = authenticationManager;
Expand All @@ -42,7 +44,7 @@ public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
return View(model);
}
// Generate the token and send it
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId<int>(), model.Number);
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(_userManager.GetCurrentUserId(), model.Number);
if (_userManager.SmsService != null)
{
var message = new IdentityMessage
Expand Down Expand Up @@ -72,10 +74,10 @@ public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
return View(model);
}
var result = await _userManager.ChangePasswordAsync(User.Identity.GetUserId<int>(), model.OldPassword, model.NewPassword);
var result = await _userManager.ChangePasswordAsync(_userManager.GetCurrentUserId(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
var user = await _userManager.FindByIdAsync(User.Identity.GetUserId<int>());
var user = await _userManager.GetCurrentUserAsync();
if (user != null)
{
await signInAsync(user, isPersistent: false);
Expand All @@ -91,8 +93,8 @@ public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
[HttpPost]
public async Task<ActionResult> DisableTFA()
{
await _userManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId<int>(), false);
var user = await _userManager.FindByIdAsync(User.Identity.GetUserId<int>());
await _userManager.SetTwoFactorEnabledAsync(_userManager.GetCurrentUserId(), false);
var user = await _userManager.GetCurrentUserAsync();
if (user != null)
{
await signInAsync(user, isPersistent: false);
Expand All @@ -105,8 +107,8 @@ public async Task<ActionResult> DisableTFA()
[HttpPost]
public async Task<ActionResult> EnableTFA()
{
await _userManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId<int>(), true);
var user = await _userManager.FindByIdAsync(User.Identity.GetUserId<int>());
await _userManager.SetTwoFactorEnabledAsync(_userManager.GetCurrentUserId(), true);
var user = await _userManager.GetCurrentUserAsync();
if (user != null)
{
await signInAsync(user, isPersistent: false);
Expand Down Expand Up @@ -136,7 +138,7 @@ public async Task<ActionResult> Index(ManageMessageId? message)
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";

var userId = User.Identity.GetUserId<int>();
var userId = _userManager.GetCurrentUserId();
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPassword(userId),
Expand Down Expand Up @@ -167,7 +169,7 @@ public async Task<ActionResult> LinkLoginCallback()
{
return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(User.Identity.GetUserId<int>(), loginInfo.Login);
var result = await _userManager.AddLoginAsync(_userManager.GetCurrentUserId(), loginInfo.Login);
return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}

Expand All @@ -179,12 +181,12 @@ public async Task<ActionResult> ManageLogins(ManageMessageId? message)
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await _userManager.FindByIdAsync(User.Identity.GetUserId<int>());
var user = await _userManager.GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(User.Identity.GetUserId<int>());
var userLogins = await _userManager.GetLoginsAsync(_userManager.GetCurrentUserId());
var otherLogins = _authenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList();
ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
Expand All @@ -208,7 +210,7 @@ public ActionResult RememberBrowser()
// GET: /Account/RemoveLogin
public async Task<ActionResult> RemoveLogin()
{
var userId = User.Identity.GetUserId<int>();
var userId = _userManager.GetCurrentUserId();
var linkedAccounts = await _userManager.GetLoginsAsync(userId);
ViewBag.ShowRemoveButton = await _userManager.HasPassword(userId) || linkedAccounts.Count > 1;
return View(linkedAccounts);
Expand All @@ -221,10 +223,10 @@ public async Task<ActionResult> RemoveLogin()
public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey)
{
ManageMessageId? message;
var result = await _userManager.RemoveLoginAsync(User.Identity.GetUserId<int>(), new UserLoginInfo(loginProvider, providerKey));
var result = await _userManager.RemoveLoginAsync(_userManager.GetCurrentUserId(), new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
var user = await _userManager.FindByIdAsync(User.Identity.GetUserId<int>());
var user = await _userManager.GetCurrentUserAsync();
if (user != null)
{
await signInAsync(user, isPersistent: false);
Expand All @@ -241,12 +243,12 @@ public async Task<ActionResult> RemoveLogin(string loginProvider, string provide
// GET: /Account/RemovePhoneNumber
public async Task<ActionResult> RemovePhoneNumber()
{
var result = await _userManager.SetPhoneNumberAsync(User.Identity.GetUserId<int>(), null);
var result = await _userManager.SetPhoneNumberAsync(_userManager.GetCurrentUserId(), null);
if (!result.Succeeded)
{
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
var user = await _userManager.FindByIdAsync(User.Identity.GetUserId<int>());
var user = await _userManager.GetCurrentUserAsync();
if (user != null)
{
await signInAsync(user, isPersistent: false);
Expand All @@ -269,10 +271,10 @@ public async Task<ActionResult> SetPassword(SetPasswordViewModel model)
{
if (ModelState.IsValid)
{
var result = await _userManager.AddPasswordAsync(User.Identity.GetUserId<int>(), model.NewPassword);
var result = await _userManager.AddPasswordAsync(_userManager.GetCurrentUserId(), model.NewPassword);
if (result.Succeeded)
{
var user = await _userManager.FindByIdAsync(User.Identity.GetUserId<int>());
var user = await _userManager.GetCurrentUserAsync();
if (user != null)
{
await signInAsync(user, isPersistent: false);
Expand All @@ -292,7 +294,7 @@ public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber)
{
// This code allows you exercise the flow without actually sending codes
// For production use please register a SMS provider in IdentityConfig and generate a code here.
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId<int>(), phoneNumber);
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(_userManager.GetCurrentUserId(), phoneNumber);
ViewBag.Status = "For DEMO purposes only, the current code is " + code;
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
Expand All @@ -307,10 +309,10 @@ public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel mod
{
return View(model);
}
var result = await _userManager.ChangePhoneNumberAsync(User.Identity.GetUserId<int>(), model.PhoneNumber, model.Code);
var result = await _userManager.ChangePhoneNumberAsync(_userManager.GetCurrentUserId(), model.PhoneNumber, model.Code);
if (result.Succeeded)
{
var user = await _userManager.FindByIdAsync(User.Identity.GetUserId<int>());
var user = await _userManager.GetCurrentUserAsync();
if (user != null)
{
await signInAsync(user, isPersistent: false);
Expand Down

0 comments on commit ce71219

Please sign in to comment.