Exemple #1
0
        public static ApplicationUser ToIdentityModel(this ApplicationUserExtended user)
        {
            var retVal = new ApplicationUser();

            user.Patch(retVal);
            return(retVal);
        }
        public static ApplicationUser ToDataModel(this ApplicationUserExtended user)
        {
            var dbUser = new ApplicationUser();
            var id     = dbUser.Id;

            dbUser.InjectFrom(user);
            dbUser.Id = id;

            if (user.Logins != null)
            {
                foreach (var login in user.Logins)
                {
                    var userLogin = dbUser.Logins.FirstOrDefault(l => l.LoginProvider == login.LoginProvider);
                    if (userLogin != null)
                    {
                        userLogin.ProviderKey = login.ProviderKey;
                    }
                    else
                    {
                        dbUser.Logins.Add(new IdentityUserLogin
                        {
                            LoginProvider = login.LoginProvider,
                            ProviderKey   = login.ProviderKey,
                            UserId        = dbUser.Id
                        });
                    }
                }
            }

            return(dbUser);
        }
Exemple #3
0
        private ApplicationUserExtended GetUserExtended(ApplicationUser applicationUser, UserDetails detailsLevel)
        {
            ApplicationUserExtended result = null;

            if (applicationUser != null)
            {
                var cacheRegion = GetUserCacheRegion(applicationUser.Id);
                result = _cacheManager.Get(cacheRegion + ":" + detailsLevel, cacheRegion, () =>
                {
                    ApplicationUserExtended retVal;
                    using (var repository = _platformRepository())
                    {
                        var user = repository.GetAccountByName(applicationUser.UserName, detailsLevel);
                        retVal   = applicationUser.ToCoreModel(user, _permissionScopeService);
                        //Populate available permission scopes
                        if (retVal.Roles != null)
                        {
                            foreach (var permission in retVal.Roles.SelectMany(x => x.Permissions).Where(x => x != null))
                            {
                                permission.AvailableScopes = _permissionScopeService.GetAvailablePermissionScopes(permission.Id).ToList();
                            }
                        }
                    }

                    if (detailsLevel != UserDetails.Export)
                    {
                        retVal.PasswordHash  = null;
                        retVal.SecurityStamp = null;
                    }

                    return(retVal);
                });
            }
            return(result);
        }
        public async Task <IHttpActionResult> CreateAsync(ApplicationUserExtended user)
        {
            //ClearSecurityProperties(user);
            var result = await _securityService.CreateAsync(user);

            return(Content(result.Succeeded ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result));
        }
        public async Task <IHttpActionResult> CreateAsync(ApplicationUserExtended user)
        {
            ClearSecurityProperties(user);
            var result = await _securityService.CreateAsync(user);

            return(ProcessSecurityResult(result));
        }
        public static void Patch(this ApplicationUserExtended user, ApplicationUser dbUser)
        {
            dbUser.Id                   = user.Id ?? dbUser.Id;
            dbUser.LockoutEnabled       = user.LockoutEnabled;
            dbUser.LockoutEndDateUtc    = user.LockoutEndDateUtc;
            dbUser.PasswordHash         = user.PasswordHash ?? dbUser.PasswordHash;
            dbUser.PhoneNumber          = user.PhoneNumber ?? dbUser.PhoneNumber;
            dbUser.PhoneNumberConfirmed = user.PhoneNumberConfirmed;
            dbUser.SecurityStamp        = user.SecurityStamp ?? dbUser.SecurityStamp;
            dbUser.TwoFactorEnabled     = user.TwoFactorEnabled;
            dbUser.UserName             = user.UserName ?? dbUser.UserName;
            dbUser.AccessFailedCount    = user.AccessFailedCount;
            dbUser.EmailConfirmed       = user.EmailConfirmed;
            dbUser.Email                = user.Email ?? dbUser.Email;

            // Copy logins
            if (user.Logins != null)
            {
                var changedLogins = user.Logins.Select(x => new IdentityUserLogin
                {
                    LoginProvider = x.LoginProvider,
                    ProviderKey   = x.ProviderKey,
                    UserId        = dbUser.Id
                }).ToList();

                var comparer = AnonymousComparer.Create((IdentityUserLogin x) => x.LoginProvider);
                changedLogins.Patch(dbUser.Logins, comparer, (sourceItem, targetItem) => { sourceItem.ProviderKey = targetItem.ProviderKey; });
            }
        }
        public static ApplicationUser ToDataModel(this ApplicationUserExtended user)
        {
            var dbUser = new ApplicationUser();

            dbUser.CopyFrom(user);
            return(dbUser);
        }
 private void ApplyAuthorizationRulesForUser(ApplicationUserExtended user)
 {
     if (user != null && !_securityService.UserHasAnyPermission(User.Identity.Name, null, new[] { PredefinedPermissions.SecurityApiAccountsRead }))
     {
         user.ApiAccounts = null;
     }
 }
Exemple #9
0
        public static string ApplyResponseGroupFiltering(ApplicationUserExtended user, Permission[] permissions, string respGroup)
        {
            var result = respGroup;

            var needRestrict = !user.IsAdministrator && permissions.Any() && !permissions.Any(x => x.Id == OrderPredefinedPermissions.ReadPrices);

            if (needRestrict && string.IsNullOrWhiteSpace(respGroup))
            {
                const CustomerOrderResponseGroup val = CustomerOrderResponseGroup.Full & ~CustomerOrderResponseGroup.WithPrices;

                result = val.ToString();
            }
            else if (needRestrict)
            {
                var items = respGroup.Split(',').Select(x => x.Trim()).ToList();

                items.Remove(CustomerOrderResponseGroup.WithPrices.ToString());

                result = string.Join(",", items);
            }

            if (needRestrict && string.IsNullOrEmpty(result))
            {
                result = CustomerOrderResponseGroup.Default.ToString();
            }

            return(result);
        }
Exemple #10
0
        public bool UserHasAnyPermission(ApplicationUserExtended user, string[] scopes, params string[] permissionIds)
        {
            if (permissionIds == null)
            {
                throw new ArgumentNullException("permissionIds");
            }

            var result = user != null && user.UserState == AccountState.Approved;

            if (result && user.IsAdministrator)
            {
                return(true);
            }

            //For managers always allow to call api
            if (result && permissionIds.Length == 1 && permissionIds.Contains(PredefinedPermissions.SecurityCallApi) &&
                (string.Equals(user.UserType, AccountType.CompanyManager.ToString(), StringComparison.InvariantCultureIgnoreCase) ||
                 string.Equals(user.UserType, AccountType.Administrator.ToString(), StringComparison.InvariantCultureIgnoreCase)))
            {
                return(true);
            }

            if (result)
            {
                var fqUserPermissions  = user.Roles.SelectMany(x => x.Permissions).SelectMany(x => x.GetPermissionWithScopeCombinationNames()).Distinct();
                var fqCheckPermissions = permissionIds.Concat(permissionIds.LeftJoin(scopes, ":"));
                result = fqUserPermissions.Intersect(fqCheckPermissions, StringComparer.OrdinalIgnoreCase).Any();
            }

            return(result);
        }
 private static void ClearSecurityProperties(ApplicationUserExtended user)
 {
     if (user != null)
     {
         user.PasswordHash  = null;
         user.SecurityStamp = null;
     }
 }
        public async Task <SecurityResult> UpdateAsync(ApplicationUserExtended user)
        {
            SecurityResult result;

            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            NormalizeUser(user);

            //Update ASP.NET indentity user
            using (var userManager = _userManagerFactory())
            {
                var dbUser = await userManager.FindByIdAsync(user.Id);

                result = ValidateUser(dbUser);
                if (result.Succeeded)
                {
                    //Update ASP.NET indentity user
                    user.Patch(dbUser);
                    var identityResult = await userManager.UpdateAsync(dbUser);

                    result = identityResult.ToCoreModel();
                }
            }

            if (result.Succeeded)
            {
                //Update platform security user
                using (var repository = _platformRepository())
                {
                    var targetDbAcount = repository.GetAccountByName(user.UserName, UserDetails.Full);

                    if (targetDbAcount == null)
                    {
                        result = new SecurityResult {
                            Errors = new[] { "Account not found." }
                        };
                    }
                    else
                    {
                        var changedDbAccount = user.ToDataModel();
                        using (var changeTracker = GetChangeTracker(repository))
                        {
                            changeTracker.Attach(targetDbAcount);

                            changedDbAccount.Patch(targetDbAcount);
                            repository.UnitOfWork.Commit();
                            //clear cache
                            _cacheManager.ClearRegion(GetUserCacheRegion(changedDbAccount.Id));
                        }
                    }
                }
            }

            return(result);
        }
        public async Task <IHttpActionResult> UpdateAsync(ApplicationUserExtended user)
        {
            EnsureUserIsEditable(user.UserName);

            //ClearSecurityProperties(user);
            var result = await _securityService.UpdateAsync(user);

            return(Content(result.Succeeded ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result));
        }
        public async Task <IHttpActionResult> UpdateAsync(ApplicationUserExtended user)
        {
            EnsureThatUsersEditable(user.UserName);

            ClearSecurityProperties(user);
            var result = await _securityService.UpdateAsync(user);

            return(ProcessSecurityResult(result));
        }
        public async Task <IHttpActionResult> Create(ApplicationUserExtended user)
        {
            var result = await _securityService.CreateAsync(user);

            if (result == null)
            {
                return(BadRequest());
            }

            return(Ok(result));
        }
Exemple #16
0
        protected virtual async Task <ApplicationUserExtended> GetUserExtendedAsync(ApplicationUser applicationUser, UserDetails detailsLevel)
        {
            ApplicationUserExtended result = null;

            if (applicationUser != null)
            {
                result = await _cacheManager.GetAsync($"GetUserByName-{applicationUser.UserName}-{detailsLevel}", SecurityConstants.CacheRegion, async() =>
                {
                    ApplicationUserExtended retVal;
                    using (var repository = _platformRepository())
                    {
                        var user = await repository.GetAccountByNameAsync(applicationUser.UserName, detailsLevel);
                        retVal   = applicationUser.ToCoreModel(user, _permissionScopeService);
                        //Populate available permission scopes
                        if (retVal.Roles != null)
                        {
                            foreach (var permission in retVal.Roles.SelectMany(x => x.Permissions).Where(x => x != null))
                            {
                                permission.AvailableScopes = _permissionScopeService.GetAvailablePermissionScopes(permission.Id).ToList();
                            }
                        }

                        //Load log entities to account
                        if (detailsLevel.HasFlag(UserDetails.Full) || detailsLevel.HasFlag(UserDetails.Export))
                        {
                            _changeLogService.LoadChangeLogs(retVal);
                        }
                    }

                    var suppressForcingCredentialsChange = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Security:SuppressForcingCredentialsChange", false);
                    if (!suppressForcingCredentialsChange)
                    {
                        //Setting the flags which indicates a necessity of security credentials change
                        retVal.PasswordExpired |= retVal.PasswordHash == Resources.Default.DefaultPasswordHash;
                        if (retVal.ApiAccounts != null)
                        {
                            foreach (var apiAccount in retVal.ApiAccounts)
                            {
                                apiAccount.SecretKeyExpired = apiAccount.SecretKey == Resources.Default.DefaultSecretKey;
                            }
                        }
                    }

                    if (detailsLevel != UserDetails.Export)
                    {
                        retVal.PasswordHash  = null;
                        retVal.SecurityStamp = null;
                    }

                    return(retVal);
                });
            }
            return(result);
        }
Exemple #17
0
        protected virtual ListDictionary <string, string> DetectAccountChanges(ApplicationUserExtended newUser, ApplicationUserExtended oldUser)
        {
            //Log changes
            var result = new ListDictionary <string, string>();

            if (newUser.UserName != oldUser.UserName)
            {
                result.Add(SecurityAccountChangesResource.AccountUpdated, $"user name: {oldUser.UserName} -> {newUser.UserName}");
            }
            if (newUser.UserType != oldUser.UserType)
            {
                result.Add(SecurityAccountChangesResource.AccountUpdated, $"user type: {oldUser.UserType} -> {newUser.UserType}");
            }
            if (newUser.UserState != oldUser.UserState)
            {
                result.Add(SecurityAccountChangesResource.AccountUpdated, $"account state: {oldUser.UserState} -> {newUser.UserState}");
            }
            if (newUser.IsAdministrator != oldUser.IsAdministrator)
            {
                result.Add(SecurityAccountChangesResource.AccountUpdated, $"root: {oldUser.IsAdministrator} -> {newUser.IsAdministrator}");
            }
            if (!newUser.ApiAccounts.IsNullOrEmpty())
            {
                var apiAccountComparer = AnonymousComparer.Create((ApiAccount x) => $"{x.ApiAccountType}-{x.SecretKey}");
                newUser.ApiAccounts.CompareTo(oldUser.ApiAccounts ?? Array.Empty <ApiAccount>(), apiAccountComparer, (state, sourceItem, targetItem) =>
                {
                    if (state == EntryState.Added)
                    {
                        result.Add(SecurityAccountChangesResource.ApiKeysActivated, $"{sourceItem.Name} ({sourceItem.ApiAccountType})");
                    }
                    else if (state == EntryState.Deleted)
                    {
                        result.Add(SecurityAccountChangesResource.ApiKeysDeactivated, $"{sourceItem.Name} ({sourceItem.ApiAccountType})");
                    }
                }
                                              );
            }
            if (!newUser.Roles.IsNullOrEmpty())
            {
                newUser.Roles.CompareTo(oldUser.Roles ?? Array.Empty <Role>(), EqualityComparer <Role> .Default, (state, sourceItem, targetItem) =>
                {
                    if (state == EntryState.Added)
                    {
                        result.Add(SecurityAccountChangesResource.RolesAdded, $"{sourceItem?.Name}");
                    }
                    else if (state == EntryState.Deleted)
                    {
                        result.Add(SecurityAccountChangesResource.RolesRemoved, $"{sourceItem?.Name}");
                    }
                });
            }

            return(result);
        }
        public void CanCheckPermissionsNoPermissions(string expected, string respGroup)
        {
            // Arrange
            var permissions = new Permission[0];
            var user        = new ApplicationUserExtended();

            // Act
            var result = OrderReadPricesPermission.ApplyResponseGroupFiltering(user, permissions, respGroup);

            // Assert
            Assert.Equal(expected, result);
        }
Exemple #19
0
        public async Task <SecurityResult> CreateAsync(ApplicationUserExtended user)
        {
            IdentityResult result;

            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            NormalizeUser(user);

            if (string.IsNullOrEmpty(user.UserName))    // PS: Если пользователь создан только для входа на кассу
            {
                result = IdentityResult.Success;
            }
            else
            {
                //Update ASP.NET indentity user
                using (var userManager = _userManagerFactory())
                {
                    var dbUser = user.ToIdentityModel();
                    user.Id = dbUser.Id;

                    if (string.IsNullOrEmpty(user.Password))
                    {
                        result = await userManager.CreateAsync(dbUser);
                    }
                    else
                    {
                        result = await userManager.CreateAsync(dbUser, user.Password);
                    }
                }
            }

            if (result.Succeeded)
            {
                using (var repository = _platformRepository())
                {
                    var dbAcount = user.ToDataModel();
                    if (string.IsNullOrEmpty(user.MemberId))
                    {
                        //Use for memberId same account id if its not set (Our current case Contact member 1 - 1 Account workaround). But client may use memberId as for any outer id.
                        dbAcount.MemberId = dbAcount.Id;
                    }
                    dbAcount.AccountState = AccountState.Approved.ToString();

                    repository.Add(dbAcount);
                    repository.UnitOfWork.Commit();
                }
            }

            return(result.ToCoreModel());
        }
Exemple #20
0
        public async Task <IHttpActionResult> CreateAsync(ApplicationUserExtended user)
        {
            var dbUser = new ApplicationUser();

            dbUser.InjectFrom(user);

            IdentityResult result;

            if (!string.IsNullOrEmpty(user.Password))
            {
                result = await UserManager.CreateAsync(dbUser, user.Password);
            }
            else
            {
                result = await UserManager.CreateAsync(dbUser);
            }

            if (result.Succeeded)
            {
                using (var repository = _platformRepository())
                {
                    var account = new AccountEntity()
                    {
                        Id           = user.Id,
                        UserName     = user.UserName,
                        MemberId     = user.MemberId,
                        AccountState = AccountState.Approved,
                        RegisterType = (RegisterType)user.UserType,
                        StoreId      = user.StoreId
                    };

                    if (user.Roles != null)
                    {
                        foreach (var role in user.Roles)
                        {
                            account.RoleAssignments.Add(new RoleAssignmentEntity {
                                RoleId = role.Id, AccountId = account.Id
                            });
                        }
                    }

                    repository.Add(account);
                    repository.UnitOfWork.Commit();
                }

                return(Ok());
            }
            else
            {
                return(BadRequest(String.Join(" ", result.Errors)));
            }
        }
Exemple #21
0
        protected virtual SecurityResult ValidateUser(ApplicationUserExtended applicationUserExtended)
        {
            if (applicationUserExtended == null)
            {
                return(new SecurityResult {
                    Errors = new[] { "User not found." }
                });
            }

            return(new SecurityResult {
                Succeeded = true
            });
        }
        public static ApplicationUserExtended ToCoreModel(this UserEntity dbEntity)
        {
            var retVal = new ApplicationUserExtended();

            retVal = new ApplicationUserExtended();
            retVal = Mapper.Map <UserEntity, ApplicationUserExtended>(dbEntity);

            retVal.UserState = EnumHelper.SafeParse <AccountState>(dbEntity.AccountState, AccountState.Approved);

            //  retVal.Roles = dbEntity.Roles.Select(x => x.Role.ToCoreModel()).ToArray();

            return(retVal);
        }
        public virtual async Task <SecurityResult> CreateAsync(ApplicationUserExtended user)
        {
            IdentityResult result;

            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            NormalizeUser(user);

            //Update ASP.NET indentity user
            using (var userManager = _userManagerFactory())
            {
                var dbUser = user.ToIdentityModel();
                user.Id = dbUser.Id;

                if (string.IsNullOrEmpty(user.Password))
                {
                    result = await userManager.CreateAsync(dbUser);
                }
                else
                {
                    result = await userManager.CreateAsync(dbUser, user.Password);
                }
            }

            if (result.Succeeded)
            {
                using (var repository = _platformRepository())
                {
                    var dbAcount = user.ToDataModel();
                    if (string.IsNullOrEmpty(user.MemberId))
                    {
                        //Use for memberId same account id if its not set (Our current case Contact member 1 - 1 Account workaround). But client may use memberId as for any outer id.
                        dbAcount.MemberId = dbAcount.Id;
                    }
                    dbAcount.AccountState = AccountState.Approved.ToString();

                    repository.Add(dbAcount);

                    var userChangedEntry = new ChangedEntry <ApplicationUserExtended>(user, EntryState.Added);
                    await _eventPublisher.Publish(new UserChangingEvent(userChangedEntry));

                    repository.UnitOfWork.Commit();
                    await _eventPublisher.Publish(new UserChangedEvent(userChangedEntry));
                }
            }

            return(result.ToCoreModel());
        }
Exemple #24
0
        public async Task <SecurityResult> CreateAsync(ApplicationUserExtended user)
        {
            IdentityResult result = null;

            if (user != null)
            {
                var dbUser = user.ToDataModel();

                using (var userManager = _userManagerFactory())
                {
                    if (string.IsNullOrEmpty(user.Password))
                    {
                        result = await userManager.CreateAsync(dbUser);
                    }
                    else
                    {
                        result = await userManager.CreateAsync(dbUser, user.Password);
                    }
                }
                if (result.Succeeded)
                {
                    using (var repository = _platformRepository())
                    {
                        var account = new AccountEntity
                        {
                            Id           = dbUser.Id,
                            UserName     = user.UserName,
                            MemberId     = user.MemberId,
                            AccountState = AccountState.Approved,
                            RegisterType = (RegisterType)user.UserType,
                            StoreId      = user.StoreId
                        };

                        if (user.Roles != null)
                        {
                            foreach (var role in user.Roles)
                            {
                                account.RoleAssignments.Add(new RoleAssignmentEntity {
                                    RoleId = role.Id, AccountId = account.Id
                                });
                            }
                        }

                        repository.Add(account);
                        repository.UnitOfWork.Commit();
                    }
                }
            }

            return(result == null ? null : result.ToCoreModel());
        }
Exemple #25
0
        public static ApplicationUserExtended ToCoreModel(this ApplicationUser applicationUser, AccountEntity dbEntity, IPermissionScopeService scopeService)
        {
            var retVal = new ApplicationUserExtended();

            retVal.InjectFrom(applicationUser);
            retVal.InjectFrom(dbEntity);
            retVal.UserState = EnumUtility.SafeParse(dbEntity.AccountState, AccountState.Approved);

            retVal.Roles       = dbEntity.RoleAssignments.Select(x => x.Role.ToCoreModel(scopeService)).ToArray();
            retVal.Permissions = retVal.Roles.SelectMany(x => x.Permissions).SelectMany(x => x.GetPermissionWithScopeCombinationNames()).Distinct().ToArray();
            retVal.ApiAccounts = dbEntity.ApiAccounts.Select(x => x.ToCoreModel()).ToArray();

            return(retVal);
        }
Exemple #26
0
        public static webModel.StorefrontUser ToWebModel(this ApplicationUserExtended user)
        {
            var retVal = new webModel.StorefrontUser();

            retVal.InjectFrom(user);
            retVal.Password      = null;
            retVal.PasswordHash  = null;
            retVal.SecurityStamp = null;
            retVal.UserState     = user.UserState;
            retVal.Logins        = user.Logins;
            retVal.Permissions   = user.Permissions;
            retVal.Roles         = user.Roles;
            return(retVal);
        }
 /// <summary>
 /// Authorizes current user for given permission or permissions,
 /// throws <see cref="AbpAuthorizationException"/> if not authorized.
 /// </summary>
 /// <param name="permissionChecker">Permission checker</param>
 /// <param name="requireAll">
 /// If this is set to true, all of the <see cref="permissionNames"/> must be granted.
 /// If it's false, at least one of the <see cref="permissionNames"/> must be granted.
 /// </param>
 /// <param name="permissionNames">Name of the permissions to authorize</param>
 /// <exception cref="AbpAuthorizationException">Throws authorization exception if</exception>
 public static void Authorize(this ApplicationUserExtended permissionChecker, bool requireAll, params string[] permissionNames)
 {
     if (IsGranted(permissionChecker, requireAll, permissionNames))
     {
         return;
     }
     if (requireAll)
     {
         throw new UnauthorizedAccessException("没有权限访问,必须所有这些权限都被授权。");
     }
     else
     {
         throw new UnauthorizedAccessException("没有权限访问,至少有一个必须被授予这些权限。");
     }
 }
        public void ApplyResponseGroupFiltering_AdminWithOrderPermissionNoReadPrices_NoChangesInResponseGroup(string expected, string respGroup)
        {
            // Arrange
            var permissions = PreparePermissions(false);
            var user        = new ApplicationUserExtended()
            {
                IsAdministrator = true,
            };

            // Act
            var result = OrderReadPricesPermission.ApplyResponseGroupFiltering(user, permissions, respGroup);

            // Assert
            Assert.Equal(expected, result);
        }
        public static ApplicationUserExtended ToCoreModel(this UserEntity applicationUser, UserEntity dbEntity, IPermissionScopeService scopeService)
        {
            var retVal = new ApplicationUserExtended();

            retVal = new ApplicationUserExtended();
            retVal = Mapper.Map <UserEntity, ApplicationUserExtended>(applicationUser);
            retVal = Mapper.Map <UserEntity, ApplicationUserExtended>(dbEntity);

            retVal.UserState = EnumHelper.SafeParse <AccountState>(dbEntity.AccountState, AccountState.Approved);

            retVal.Roles       = dbEntity.Roles.Select(x => x.Role.ToCoreModel(scopeService)).ToArray();
            retVal.Permissions = retVal.Roles.SelectMany(x => x.Permissions).SelectMany(x => x.GetPermissionWithScopeCombinationNames()).Distinct().ToArray();
            retVal.ApiAccounts = dbEntity.ApiAccounts.Select(x => x.ToCoreModel()).ToArray();

            return(retVal);
        }
        public static void CopyFrom(this ApplicationUser dbUser, ApplicationUserExtended user)
        {
            // Backup old values
            var id            = dbUser.Id;
            var passwordHash  = dbUser.PasswordHash;
            var securityStamp = dbUser.SecurityStamp;

            dbUser.InjectFrom(user);

            // Restore old values
            if (user.Id == null)
            {
                dbUser.Id = id;
            }

            if (user.PasswordHash == null)
            {
                dbUser.PasswordHash = passwordHash;
            }

            if (user.SecurityStamp == null)
            {
                dbUser.SecurityStamp = securityStamp;
            }

            // Copy logins
            if (user.Logins != null)
            {
                foreach (var login in user.Logins)
                {
                    var userLogin = dbUser.Logins.FirstOrDefault(l => l.LoginProvider == login.LoginProvider);
                    if (userLogin != null)
                    {
                        userLogin.ProviderKey = login.ProviderKey;
                    }
                    else
                    {
                        dbUser.Logins.Add(new IdentityUserLogin
                        {
                            LoginProvider = login.LoginProvider,
                            ProviderKey   = login.ProviderKey,
                            UserId        = dbUser.Id
                        });
                    }
                }
            }
        }
        /// <summary>
        /// Create new user 
        /// </summary>
        /// <exception cref="VirtoCommerce.Platform.Client.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="user">User details.</param>
        /// <returns>Task of SecurityResult</returns>
        public async System.Threading.Tasks.Task<SecurityResult> SecurityCreateAsyncAsync(ApplicationUserExtended user)
        {
             ApiResponse<SecurityResult> localVarResponse = await SecurityCreateAsyncAsyncWithHttpInfo(user);
             return localVarResponse.Data;

        }
        public async Task<IHttpActionResult> UpdateAsync(ApplicationUserExtended user)
        {
            var dbUser = await UserManager.FindByIdAsync(user.Id);

            dbUser.InjectFrom(user);

            foreach (var login in user.Logins)
            {
                var userLogin = dbUser.Logins.FirstOrDefault(l => l.LoginProvider == login.LoginProvider);
                if (userLogin != null)
                {
                    userLogin.ProviderKey = login.ProviderKey;
                }
                else
                {
                    dbUser.Logins.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin
                    {
                        LoginProvider = login.LoginProvider,
                        ProviderKey = login.ProviderKey,
                        UserId = dbUser.Id
                    });
                }
            }

            var result = await UserManager.UpdateAsync(dbUser);

            if (result.Succeeded)
            {
                using (var repository = _platformRepository())
                {
                    var acount = repository.GetAccountByName(user.UserName, UserDetails.Full);
                    if (acount == null)
                    {
                        return BadRequest("Acount not found");
                    }
                    acount.RegisterType = (RegisterType)user.UserType;
                    acount.AccountState = (AccountState)user.UserState;
                    acount.MemberId = user.MemberId;
                    acount.StoreId = user.StoreId;

                    if (user.ApiAcounts != null)
                    {
                        var source = new ObservableCollection<ApiAccountEntity>(user.ApiAcounts.Select(x => x.ToFoundation()));
                        var inventoryComparer = AnonymousComparer.Create((ApiAccountEntity x) => x.Id);
                        acount.ApiAccounts.ObserveCollection(x => repository.Add(x), x => repository.Remove(x));
                        source.Patch(acount.ApiAccounts, inventoryComparer, (sourceAccount, targetAccount) => sourceAccount.Patch(targetAccount));
                    }

                    if (user.Roles != null)
                    {
                        var sourceCollection = new ObservableCollection<RoleAssignmentEntity>(user.Roles.Select(r => new RoleAssignmentEntity { RoleId = r.Id }));
                        var comparer = AnonymousComparer.Create((RoleAssignmentEntity x) => x.RoleId);
                        acount.RoleAssignments.ObserveCollection(ra => repository.Add(ra), ra => repository.Remove(ra));
                        sourceCollection.Patch(acount.RoleAssignments, comparer, (source, target) => source.Patch(target));
                    }

                    repository.UnitOfWork.Commit();
                }

                return Ok();
            }

            return BadRequest(String.Join(" ", result.Errors));
        }
        public async Task<IHttpActionResult> CreateAsync(ApplicationUserExtended user)
        {
            var dbUser = new ApplicationUser();

            dbUser.InjectFrom(user);

            IdentityResult result;
            if (!string.IsNullOrEmpty(user.Password))
            {
                result = await UserManager.CreateAsync(dbUser, user.Password);
            }
            else
            {
                result = await UserManager.CreateAsync(dbUser);
            }

            if (result.Succeeded)
            {
                using (var repository = _platformRepository())
                {
                    var account = new AccountEntity()
                    {
                        Id = user.Id,
                        UserName = user.UserName,
                        MemberId = user.MemberId,
                        AccountState = AccountState.Approved,
                        RegisterType = (RegisterType)user.UserType,
                        StoreId = user.StoreId
                    };

                    if (user.Roles != null)
                    {
                        foreach (var role in user.Roles)
                        {
                            account.RoleAssignments.Add(new RoleAssignmentEntity { RoleId = role.Id, AccountId = account.Id });
                        }
                    }

                    repository.Add(account);
                    repository.UnitOfWork.Commit();
                }

                return Ok();
            }
            else
            {
                return BadRequest(String.Join(" ", result.Errors));
            }
        }
        private ApplicationUserExtended GetUserExtended(ApplicationUser applicationUser, UserDetails detailsLevel)
        {
            ApplicationUserExtended result = null;

            if (applicationUser != null)
            {
                result = new ApplicationUserExtended();
                result.InjectFrom(applicationUser);

                using (var repository = _platformRepository())
                {
                    var user = repository.GetAccountByName(applicationUser.UserName, detailsLevel);

                    if (user != null)
                    {
                        result.InjectFrom(user);

                        result.UserState = (UserState)user.AccountState;
                        result.UserType = (UserType)user.RegisterType;

                        if (detailsLevel == UserDetails.Full)
                        {
                            var roles = user.RoleAssignments.Select(x => x.Role).ToArray();
                            result.Roles = roles.Select(r => r.ToCoreModel(false)).ToArray();

                            var permissionIds = roles
                                    .SelectMany(x => x.RolePermissions)
                                    .Select(x => x.PermissionId)
                                    .Distinct()
                                    .ToArray();

                            result.Permissions = permissionIds;
                            result.ApiAcounts = user.ApiAccounts.Select(x => x.ToWebModel()).ToList();
                        }
                    }
                }
            }

            return result;
        }
 public async Task<IHttpActionResult> UpdateAsync(ApplicationUserExtended user)
 {
     var result = await _securityService.UpdateAsync(user);
     return ProcessSecurityResult(result);
 }
 /// <summary>
 /// Create new user 
 /// </summary>
 /// <exception cref="VirtoCommerce.Platform.Client.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="user">User details.</param>
 /// <returns>SecurityResult</returns>
 public SecurityResult SecurityCreateAsync(ApplicationUserExtended user)
 {
      ApiResponse<SecurityResult> localVarResponse = SecurityCreateAsyncWithHttpInfo(user);
      return localVarResponse.Data;
 }
        /// <summary>
        /// Create new user 
        /// </summary>
        /// <exception cref="VirtoCommerce.Platform.Client.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="user">User details.</param>
        /// <returns>Task of ApiResponse (SecurityResult)</returns>
        public async System.Threading.Tasks.Task<ApiResponse<SecurityResult>> SecurityCreateAsyncAsyncWithHttpInfo(ApplicationUserExtended user)
        {
            // verify the required parameter 'user' is set
            if (user == null)
                throw new ApiException(400, "Missing required parameter 'user' when calling VirtoCommercePlatformApi->SecurityCreateAsync");

            var localVarPath = "/api/platform/security/users/create";
            var localVarPathParams = new Dictionary<string, string>();
            var localVarQueryParams = new Dictionary<string, string>();
            var localVarHeaderParams = new Dictionary<string, string>(Configuration.DefaultHeader);
            var localVarFormParams = new Dictionary<string, string>();
            var localVarFileParams = new Dictionary<string, FileParameter>();
            object localVarPostBody = null;

            // to determine the Content-Type header
            string[] localVarHttpContentTypes = new string[] {
                "application/json", 
                "text/json", 
                "application/xml", 
                "text/xml", 
                "application/x-www-form-urlencoded"
            };
            string localVarHttpContentType = ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            string[] localVarHttpHeaderAccepts = new string[] {
                "application/json", 
                "text/json", 
                "application/xml", 
                "text/xml"
            };
            string localVarHttpHeaderAccept = ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
            if (localVarHttpHeaderAccept != null)
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            localVarPathParams.Add("format", "json");
            if (user.GetType() != typeof(byte[]))
            {
                localVarPostBody = ApiClient.Serialize(user); // http body (model) parameter
            }
            else
            {
                localVarPostBody = user; // byte array
            }


            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await ApiClient.CallApiAsync(localVarPath,
                Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (localVarStatusCode >= 400 && (localVarStatusCode != 404 || Configuration.ThrowExceptionWhenStatusCodeIs404))
                throw new ApiException(localVarStatusCode, "Error calling SecurityCreateAsync: " + localVarResponse.Content, localVarResponse.Content);
            else if (localVarStatusCode == 0)
                throw new ApiException(localVarStatusCode, "Error calling SecurityCreateAsync: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);

            return new ApiResponse<SecurityResult>(localVarStatusCode,
                localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                (SecurityResult)ApiClient.Deserialize(localVarResponse, typeof(SecurityResult)));
            
        }
 private void ClearSecurityProperties(ApplicationUserExtended user)
 {
     if (user != null)
     {
         user.PasswordHash = null;
         user.SecurityStamp = null;
     }
 }
        public async Task<IHttpActionResult> UpdateAsync(ApplicationUserExtended user)
        {
            EnsureThatUsersEditable(user.UserName);

            ClearSecurityProperties(user);
            var result = await _securityService.UpdateAsync(user);
            return ProcessSecurityResult(result);
        }
 public async Task<IHttpActionResult> CreateAsync(ApplicationUserExtended user)
 {
     ClearSecurityProperties(user);
     var result = await _securityService.CreateAsync(user);
     return ProcessSecurityResult(result);
 }