public static ApplicationUserDTO ApplicationUserDTOMapper(IdentityModels.ApplicationUser applicationUser) { var applicationUserDto = new ApplicationUserDTO { UserId = applicationUser.Id, CreateDate = applicationUser.CreateDate, AccessFailedCount = applicationUser.AccessFailedCount, DisplayName = applicationUser.DisplayName, Email = applicationUser.Email, EmailConfirmed = applicationUser.EmailConfirmed, Status = applicationUser.Status, LockoutEnabled = applicationUser.LockoutEnabled, LockoutEndDateUtc = applicationUser.LockoutEndDateUtc, PasswordHash = applicationUser.PasswordHash, PhoneNumber = applicationUser.PhoneNumber, PhoneNumberConfirmed = applicationUser.PhoneNumberConfirmed, SecurityStamp = applicationUser.SecurityStamp, TwoFactorEnabled = applicationUser.TwoFactorEnabled, UserName = applicationUser.UserName, IsAdmin = applicationUser.IsAdmin, IsCustomizedAccess = applicationUser.IsCustomizedAccess, }; return(applicationUserDto); }
public AuthenticationResponse Login(string userName, string password, string clientId, string clientPassword, string identityServerAddress) { try { var client = new TokenClient( identityServerAddress, clientId, clientPassword); var token = client.RequestResourceOwnerPasswordAsync(userName, password, "email profile openid iranMarketerMail").Result; var application = clientId.ParseEnum(Applications.UnKnown); IdentityModels.ApplicationUser user = null; Party party = null; if (!token.AccessToken.IsNullOrEmpty()) { user = AuthenticationManager.AuthenticationProvider.GetUserByName(userName); } var result = new AuthenticationResponse { AccessToken = token.AccessToken, LifeTime = (int)token.ExpiresIn, ApplicationUser = user == null ? null : new ApplicationUserDTO { Email = user?.Email, Status = user?.Status ?? 0, IsCustomizedAccess = user.IsCustomizedAccess, CreateDate = user?.CreateDate ?? DateTime.MinValue, // PhoneNumber = party?., UserName = user?.UserName, IsAdmin = user?.IsAdmin ?? false, DisplayNameFa = party != null ? (!Regex.IsMatch(user.UserName, "^demo\\d$") ? party?.FullName : "علی احمدی") : user.DisplayName, DisplayNameEn = party != null ? (!Regex.IsMatch(user.UserName, "^demo\\d$") ? party?.FullName : "Joan Smith") : user.DisplayName, }, HasAccess = token.AccessToken != null, ClientId = clientId, // Pages = AccessService.GetAccessiblePagesByUsername(userName, application).Select(x => x.ToString()).ToList() }; BRule.Assert(result.AccessToken != null, RuleExceptionCodeUserManagement.LoginFaild.GetEnumDescription(), (int)RuleExceptionCodeUserManagement.LoginFaild); BRule.Assert(result.ApplicationUser.Status == (int)UserStatus.Active, RuleExceptionCodeUserManagement.UserIsNotActive.GetEnumDescription(), (int)RuleExceptionCodeUserManagement.UserIsNotActive); return(result); } catch (Exception ex) { Logger.ErrorException(ex.Message, ex); throw; } }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new IdentityModels.ApplicationUser { UserName = model.Email, Email = model.Email, UserData = new UserData() }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToAction("UserData", "Admin")); } AddErrors(result); } return(View(model)); }
protected virtual bool IsAuthorized(AuthorizationContext actionContext) { try { var principal = (ClaimsIdentity)actionContext.HttpContext.User.Identity; var email = principal?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value; var userName = principal?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value; var userId = principal?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value; var partyId = principal?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.UserData)?.Value; var client = principal?.Claims.FirstOrDefault(x => x.Type == "Clinet")?.Value; var application = client.ParseEnum(Applications.UnKnown); if (!userName.IsNullOrEmpty()) { user = AuthenticationManager.AuthenticationProvider.GetUserByName(userName); } var isActive = user?.Status ?? 0; //var session = new AccessTokenSession //{ // ClientId = client?.ToLower(), // userId = userName?.ToLower() //}; if (principal != null && principal.IsAuthenticated && !email.IsNullOrEmpty() && !userName.IsNullOrEmpty() && isActive == (int)UserStatus.Active) { //if (StaticData.AccessToken.ContainsKey(session) && // StaticData.AccessToken[session] == // actionContext.Request.Headers.Authorization.Parameter) return(true); } return(false); } catch (Exception ex) { Logger.ErrorException(ex.Message, ex); return(false); } }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Dashboard", "Account")); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new IdentityModels.ApplicationUser { UserName = model.Email, Email = model.Email, UserData = new UserData() }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public static IdentityModels.ApplicationUser ApplicationUserMapper(ApplicationUserDTO applicationUserDto) { var applicationUser = new IdentityModels.ApplicationUser { CreateDate = applicationUserDto.CreateDate, AccessFailedCount = applicationUserDto.AccessFailedCount, DisplayName = applicationUserDto.DisplayName, Email = applicationUserDto.Email, EmailConfirmed = applicationUserDto.EmailConfirmed, Status = applicationUserDto.Status, LockoutEnabled = applicationUserDto.LockoutEnabled, LockoutEndDateUtc = applicationUserDto.LockoutEndDateUtc, PasswordHash = applicationUserDto.PasswordHash, PhoneNumber = applicationUserDto.PhoneNumber, PhoneNumberConfirmed = applicationUserDto.PhoneNumberConfirmed, SecurityStamp = applicationUserDto.SecurityStamp, TwoFactorEnabled = applicationUserDto.TwoFactorEnabled, UserName = applicationUserDto.UserName, IsAdmin = applicationUserDto.IsAdmin, IsCustomizedAccess = applicationUserDto.IsCustomizedAccess, }; return(applicationUser); }
public void AddUser(UserManagementAddFilter model) { var addedUser = new IdentityModels.ApplicationUser(); try { BRule.Assert(model != null, RuleExceptionCodeCommon.FilterIsNull.GetEnumDescription(), (int)RuleExceptionCodeCommon.FilterIsNull); BRule.Assert(model.UserName != null, RuleExceptionCodeUserManagement.InvalidUserName.GetEnumDescription(), (int)RuleExceptionCodeUserManagement.InvalidUserName); BRule.Assert(model.DisplayName != null, RuleExceptionCodeUserManagement.DisplayNameIsNull.GetEnumDescription(), (int)RuleExceptionCodeUserManagement.DisplayNameIsNull); var user = AuthenticationManager.AuthenticationProvider.UserManager.FindByName(model.UserName); BRule.Assert(user == null, RuleExceptionCodeUserManagement.UserNameExists.GetEnumDescription(), (int)RuleExceptionCodeUserManagement.UserNameExists); var ifExistEmail = AuthenticationManager.AuthenticationProvider.UserManager.FindByEmail(model.Email); BRule.Assert(ifExistEmail == null, RuleExceptionCodeUserManagement.EmailExits.GetEnumDescription(), (int)RuleExceptionCodeUserManagement.EmailExits); AuthenticationManager.AuthenticationProvider.UserManager.PasswordValidator = new PasswordValidator { RequireDigit = false, RequireLowercase = false, RequireNonLetterOrDigit = false, RequireUppercase = false, RequiredLength = 5 }; BRule.Assert(model.Password.Equals(model.ConfirmPassword), RuleExceptionCodeUserManagement.ConfirmPasswordDontMatch.GetEnumDescription(), (int)RuleExceptionCodeUserManagement.ConfirmPasswordDontMatch); BRule.Assert( AuthenticationManager.AuthenticationProvider.UserManager.PasswordValidator.ValidateAsync( model.Password).Result.Succeeded, RuleExceptionCodeUserManagement.PasswordisInvalid.GetEnumDescription(), (int)RuleExceptionCodeUserManagement.PasswordisInvalid); Mapper.CreateMap <UserManagementAddFilter, IdentityModels.ApplicationUser>() .ForMember(dest => dest.CreateDate, opt => opt.MapFrom(src => DateTime.Now)) .ForMember(dest => dest.Id, opt => opt.Ignore()) .ForMember(dest => dest.PasswordHash, opt => opt.Ignore()) .ForMember(x => x.EmailConfirmed, y => y.UseValue(true)) .ForMember(x => x.PhoneNumberConfirmed, y => y.UseValue(true)) .ForMember(x => x.Status, y => y.UseValue(1)) .ForMember(x => x.LockoutEnabled, y => y.UseValue(false)); var result = Mapper.Map <UserManagementAddFilter, IdentityModels.ApplicationUser>(model); result.LockoutEnabled = false; AuthenticationManager.AuthenticationProvider.UserManager.Create(result, model.Password); addedUser = AuthenticationManager.AuthenticationProvider.UserManager.FindByName(model.UserName); var dbFactory = CoreContainer.Container.Resolve <IDbFactory>(); using (var uow = dbFactory.Create <IUnitOfWork, ISession>(IsolationLevel.Serializable)) { try { switch (model.PartyType) { case PartyType.Retail: { PartyProvider.Save(new RetailParty() { Created = DateTime.Now, Modified = DateTime.Now, CreatedBy = model.AuthenticatedUserName, ModifiedBy = model.AuthenticatedUserName, FullName = model.DisplayName, UserName = addedUser.UserName, UserId = addedUser.Id, }, uow); break; } case PartyType.Institutional: { LegalPartyProvider.Save(new LegalParty() { Created = DateTime.Now, Modified = DateTime.Now, CreatedBy = model.AuthenticatedUserName, ModifiedBy = model.AuthenticatedUserName, UserName = addedUser.UserName, UserId = addedUser.Id, CompanyName = model.DisplayName }, uow); break; } default: break; } } catch (Exception) { uow.Rollback(); } } } catch (Exception ex) { AuthenticationManager.AuthenticationProvider.UserManager.Delete(addedUser); Logger.ErrorException(ex.Message, ex); throw ex; } }