Пример #1
0
 private async Task ReturnError(HttpContextBase context, SecurityResult error)
 {
     LogError(context, error);
     context.Response.Headers.Set("Content-Type", "application/json;charset=UTF-8");
     context.Response.StatusCode = (int)error.Code;
     await context.Response.Output.WriteAsync(_base.Serialize(error)).ConfigureAwait(false);
 }
Пример #2
0
 //Método utilizado en Web para añadir los errores producidos al modelo
 private void AddErrors(SecurityResult result)
 {
     foreach (var error in result.Errors)
     {
         ModelState.AddModelError("", error);
     }
 }
        public async Task <SecurityResult> RegisterAsync(string userName, string email, string password)
        {
            var securityResult = new SecurityResult();

            var user = new User
            {
                UserName   = userName,
                Email      = email,
                IsApproved = false
            };

            var createUserResult = await _userManager.CreateAsync(user, password);

            if (!createUserResult.Succeeded)
            {
                securityResult.AddErrorMessages(createUserResult.Errors.Select(e => e.Description));
                return(securityResult);
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id)
            };

            var addClaimsResult = await _userManager.AddClaimsAsync(user, claims);

            if (!addClaimsResult.Succeeded)
            {
                securityResult.AddErrorMessages(addClaimsResult.Errors.Select(e => e.Description));
            }

            return(securityResult);
        }
Пример #4
0
        public static string SecurityResultToString(SecurityResult status)
        {
            switch (status)
            {
                case SecurityResult.Success:

                    //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de-DE");

                    Localization.Culture = new System.Globalization.CultureInfo("de-DE");

                    return Localization.Success;
                    //return "No error.";
                case SecurityResult.Unimplemented:
                    return "Function or operation not implemented.";
                case SecurityResult.Parameter:
                    return "One or more parameters passed to a function where not valid.";
                case SecurityResult.Allocate:
                    return "Failed to allocate memory.";
                case SecurityResult.Deprecated:
                    return "Deprecated password encryption error found.";
                case SecurityResult.NotAvailable:
                    return "No keychain is available. You may need to restart your computer.";
                case SecurityResult.DuplicateItem:
                    return "The specified item already exists in the keychain.";
                case SecurityResult.ItemNotFound:
                    return "The specified item could not be found in the keychain.";
                case SecurityResult.InteractionNotAllowed:
                    return "User interaction is not allowed.";
                case SecurityResult.Decode:
                    return "Unable to decode the provided data.";
                default:
                    return "Unknown security result error.";
            }
        }
        public async Task <SecurityResult <TokenBatch> > LoginAsync(string userName, string password)
        {
            var result = new SecurityResult <TokenBatch>();

            var user = await _userManager.FindByNameAsync(userName);

            if (user == null)
            {
                result.AddErrorMessage($"{userName} does not exists.");
                return(result);
            }

            var verified = _userManager.PasswordHasher.VerifyHashedPassword(user, user.PasswordHash, password);

            if (verified == PasswordVerificationResult.Failed)
            {
                result.AddErrorMessage("Invalid password.");
                return(result);
            }

            var usersClaims = await _userManager.GetClaimsAsync(user);

            var accessToken = _tokenService.GenerateAccessToken(usersClaims);

            result.Data = new TokenBatch
            {
                AccessToken = accessToken
            };

            return(result);
        }
Пример #6
0
        private SecurityResult ValidateUser(ApplicationUser dbUser)
        {
            SecurityResult result;

            if (dbUser == null)
            {
                result = new SecurityResult {
                    Errors = new[] { "User not found." }
                };
            }
            else
            {
                if (!IsEditableUser(dbUser.UserName))
                {
                    result = new SecurityResult {
                        Errors = new[] { "It is forbidden to edit this user." }
                    };
                }
                else
                {
                    result = new SecurityResult {
                        Succeeded = true
                    };
                }
            }

            return(result);
        }
Пример #7
0
 public SingleResultDto(SecurityResult erroSecurity)
 {
     Codigo   = erroSecurity.Code;
     Sucesso  = false;
     Mensagem = erroSecurity.ErrorMessage;
     Data     = null;
 }
Пример #8
0
        public async Task <IHttpActionResult> RequestPasswordReset(string loginOrEmail)
        {
            var retVal = new SecurityResult
            {
                // Return success by default for security reason
                Succeeded = true
            };

            try
            {
                var user = await _securityService.FindByNameAsync(loginOrEmail, UserDetails.Full)
                           ?? await _securityService.FindByEmailAsync(loginOrEmail, UserDetails.Full);

                // Do not permit rejected users and customers
                if (string.IsNullOrEmpty(user?.Email) || user.UserState == AccountState.Rejected || user.UserType.EqualsInvariant(AccountType.Customer.ToString()))
                {
                    if (ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:ForgotPassword:RevealAccountState", false))
                    {
                        retVal.Errors    = new[] { "User with this name or email does not exist" };
                        retVal.Succeeded = false;
                    }
                }
                else
                {
                    EnsureUserIsEditable(user.UserName);

                    var uri = Request.RequestUri.AbsoluteUri;
                    uri = uri.Substring(0, uri.IndexOf("/api/platform/security/", StringComparison.OrdinalIgnoreCase));

                    var token = await _securityService.GeneratePasswordResetTokenAsync(user.Id);

                    var sender = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:Sender:Email")
                                 ?? "noreply@" + Request.RequestUri.Host;

                    var notification = _notificationManager.GetNewNotification <ResetPasswordEmailNotification>("Platform", typeof(ResetPasswordEmailNotification).Name, "en-US");
                    notification.Url       = $"{uri}/#/resetpassword/{user.Id}/{token}";
                    notification.Recipient = user.Email;
                    notification.Sender    = sender;

                    try
                    {
                        _notificationManager.ScheduleSendNotification(notification);
                    }
                    catch (Exception ex)
                    {
                        // Display errors only when sending notifications fails
                        retVal.Errors    = new[] { ex.Message };
                        retVal.Succeeded = false;
                    }
                }
            }
            catch
            {
                // No details for security reasons
            }

            return(Ok(retVal));
        }
        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 Task Authorize(GetUserProfileQuery request, IUserContext userContext, CancellationToken cancellationToken)
        {
            if (userContext.IsAuthenticated)
            {
                return(SecurityResult.Ok());
            }

            return(SecurityResult.AnonymousUser(request));
        }
Пример #11
0
 private void LogError(HttpContextBase context, SecurityResult error)
 {
     _logger?.LogError("Actuator Security Error: {ErrorCode} - {ErrorMessage}", error.Code, error.Message);
     if (_logger?.IsEnabled(LogLevel.Trace) == true)
     {
         foreach (var header in context.Request.Headers.AllKeys)
         {
             _logger?.LogTrace("Header: {HeaderKey} - {HeaderValue}", header, context.Request.Headers[header]);
         }
     }
 }
Пример #12
0
        public static int DeleteCustomerService(int serviceId)
        {
            SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();

            //
            if (!result.Success)
            {
                return(result.ResultCode);
            }
            //
            return(EcommerceProvider.DeleteCustomerService(ES.SecurityContext.User.UserId, serviceId));
        }
        public static SecurityResult ToCoreModel(this IdentityResult dataModel)
        {
            var result = new SecurityResult();

            result = Mapper.Map <IdentityResult, SecurityResult>(dataModel);
            if (dataModel.Errors != null)
            {
                result.Errors = dataModel.Errors.Select(x => x.Description).ToArray();
            }

            return(result);
        }
Пример #14
0
        public static int SetPluginProperties(int userId, int pluginId, KeyValueBunch props)
        {
            string xmlText = String.Empty;

            string[][]     pluginProps = null;
            SecurityResult result      = StorehouseController.CheckAccountNotDemoAndActive();

            //
            if (!result.Success)
            {
                return(result.ResultCode);
            }
            if (props != null)
            {
                // create system plugin
                SystemPluginBase pluginObj = GetSystemPluginInstance(userId, pluginId, false);
                // crypt sensitive data
                foreach (string keyName in props.GetAllKeys())
                {
                    //
                    string keyValue = props[keyName];
                    //
                    if (pluginObj.SecureSettings != null)
                    {
                        int indexOf = Array.IndexOf(pluginObj.SecureSettings, keyName);
                        // crypt sensitive data
                        if (indexOf > -1)
                        {
                            keyValue = CryptoUtils.Encrypt(keyValue);
                        }
                    }
                    //
                    props[keyName] = keyValue;
                }

                // load old properties
                KeyValueBunch oldProps = GetPluginPropertiesInternal(userId, pluginId,
                                                                     false, pluginObj.SecureSettings);
                // merge old props with new props
                foreach (string keyName in props.GetAllKeys())
                {
                    // copy
                    oldProps[keyName] = props[keyName];
                }
                //
                pluginProps = oldProps.KeyValueArray;
            }
            // build update xml
            xmlText = SettingsHelper.ConvertObjectSettings(pluginProps, "properties", "property");
            //
            return(EcommerceProvider.SetPluginProperties(SecurityContext.User.UserId, userId, pluginId, xmlText));
        }
Пример #15
0
        public static SecurityResult ToCoreModel(this IdentityResult dataModel)
        {
            var result = new SecurityResult();

            result.InjectFrom(dataModel);

            if (dataModel.Errors != null)
            {
                result.Errors = dataModel.Errors.ToArray();
            }

            return(result);
        }
Пример #16
0
        public static int VoidCustomerInvoice(int invoiceId)
        {
            SecurityResult result = StorehouseController.CheckAccountIsAdminOrReseller();

            if (!result.Success)
            {
                return(result.ResultCode);
            }
            // void
            EcommerceProvider.VoidCustomerInvoice(ES.SecurityContext.User.UserId, invoiceId);
            //
            return(0);
        }
Пример #17
0
        public async Task <IHttpActionResult> RequestPasswordReset(string loginOrEmail)
        {
            var retVal = new SecurityResult
            {
                //Return success by default for security reason
                Succeeded = true
            };

            try
            {
                var user = await _securityService.FindByNameAsync(loginOrEmail, UserDetails.Full);

                if (user == null)
                {
                    user = await _securityService.FindByEmailAsync(loginOrEmail, UserDetails.Full);
                }

                //Do not permit rejected users and customers
                if (user.Email != null && user != null && user.UserState != AccountState.Rejected && !string.Equals(user.UserType, AccountType.Customer.ToString(), StringComparison.InvariantCultureIgnoreCase))
                {
                    EnsureThatUsersEditable(user.UserName);

                    var uri = Request.RequestUri.AbsoluteUri;
                    uri = uri.Substring(0, uri.IndexOf("/api/platform/security/"));
                    var token = await _securityService.GeneratePasswordResetTokenAsync(user.Id);

                    var notification = _notificationManager.GetNewNotification <ResetPasswordEmailNotification>("Platform", typeof(ResetPasswordEmailNotification).Name, "en");
                    notification.Url       = $"{uri}/#/resetpassword/{user.Id}/{token}";
                    notification.Recipient = user.Email;
                    notification.Sender    = "noreply@" + Request.RequestUri.Host;
                    try
                    {
                        var result = _notificationManager.SendNotification(notification);
                        retVal.Succeeded = result.IsSuccess;
                        if (!retVal.Succeeded)
                        {
                            retVal.Errors = new string[] { result.ErrorMessage };
                        }
                    }
                    catch (Exception ex)
                    {
                        //Display errors only when sending notifications fail
                        retVal.Errors    = new string[] { ex.Message };
                        retVal.Succeeded = false;
                    }
                }
            }
            catch { } // no details in here for security reasons

            return(Ok(retVal));
        }
Пример #18
0
        private SecurityResult ValidateUser(ApplicationUser dbUser)
        {
            var result = new SecurityResult {
                Succeeded = true
            };

            if (dbUser == null)
            {
                result = new SecurityResult {
                    Errors = new[] { "User not found." }
                };
            }

            return(result);
        }
        public bool CheckOperationClientPermissions(GenericSvcResult result)
        {
            // 1. Do security checks
            SecurityResult secResult = StorehouseController.CheckAccountIsAdminOrReseller();

            // ERROR
            if (!secResult.Success)
            {
                result.Succeed    = false;
                result.ResultCode = secResult.ResultCode;
                //
                return(false);
            }
            //
            return(true);
        }
        public bool CheckOperationClientStatus(GenericSvcResult result)
        {
            // 2. Check account status
            SecurityResult secResult = StorehouseController.CheckAccountNotDemoAndActive();

            // ERROR
            if (!secResult.Success)
            {
                result.Succeed    = false;
                result.ResultCode = secResult.ResultCode;
                //
                return(false);
            }
            //
            return(true);
        }
Пример #21
0
        public static int DeleteCategory(int userId, int categoryId)
        {
            SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();

            //
            if (!result.Success)
            {
                return(result.ResultCode);
            }

            return(EcommerceProvider.DeleteCategory(
                       ES.SecurityContext.User.UserId,
                       userId,
                       categoryId
                       ));
        }
Пример #22
0
 private IHttpActionResult ProcessSecurityResult(SecurityResult result)
 {
     if (result == null)
     {
         return(BadRequest());
     }
     else
     {
         if (!result.Succeeded)
         {
             return(BadRequest(result.Errors != null ? string.Join(" ", result.Errors) : "Unknown error."));
         }
         else
         {
             return(Ok());
         }
     }
 }
Пример #23
0
        private void BtnSignIn_Click(object sender, EventArgs e)
        {
            try
            {
                if (FormIsValid())
                {
                    SecurityResult result = Authentication.Authenticate(tbxUsername.Text.Trim(), tbxPassword.Text.Trim());

                    if (result.IsAuthenticated)
                    {
                        GetCurrentSysUser.SetCurrentUserByFiscalUserName(tbxUsername.Text.Trim());
                        UserService.UserLogined(GetCurrentSysUser.Instance.UserID);
                        UserPersonalizationOperaion.SetUserPersonalization();

                        this.Hide();
                        #region  جزيره اي
                        //if (ResultOveral.Any(a => a.id == 267 && a.value == 0))
                        //{
                        //var hub = new Hub(tbxUsername.Text.Trim());
                        //hub.Show();
                        //}
                        #endregion
                        #region تب بار
                        //else if (ResultOveral.Any(a => a.id == 267 && a.value == 1))
                        //{
                        var HubTabBar = new TabBarMenu(tbxUsername.Text.Trim());
                        HubTabBar.Show();
                        //}
                        #endregion
                    }
                    else
                    {
                        lblMessage.Text      = Atiran.UI.WindowsForms.ResourceManager.GetResourceManager().GetString(result.Exceptions[0].ErrorCode);
                        lblMessage.Visible   = true;
                        lblMessage.ForeColor = Color.Red;
                    }
                }
            }
            catch (Exception ex)
            {
                UI.WindowsForms.MessageBoxes.CustomMessageForm.CustomMessageBox.Show("", ex.Message, "e");
            }
        }
Пример #24
0
        public static int AddCategory(int userId, string categoryName, string categorySku, int parentId, string shortDescription, string fullDescription)
        {
            SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();

            //
            if (!result.Success)
            {
                return(result.ResultCode);
            }
            //
            return(EcommerceProvider.AddCategory(
                       ES.SecurityContext.User.UserId,
                       userId,
                       categoryName,
                       categorySku,
                       parentId,
                       shortDescription,
                       fullDescription
                       ));
        }
        private IHttpActionResult ProcessSecurityResult(SecurityResult securityResult)
        {
            IHttpActionResult result;

            if (securityResult == null)
            {
                result = BadRequest();
            }
            else
            {
                if (!securityResult.Succeeded)
                {
                    result = BadRequest(securityResult.Errors != null ? string.Join(" ", securityResult.Errors) : "Unknown error.");
                }
                else
                {
                    result = Ok(securityResult);
                }
            }

            return(result);
        }
Пример #26
0
        public virtual async Task <SecurityResult> UpdateAsync(ApplicationUserExtended user)
        {
            SecurityResult result;

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

            NormalizeUser(user);

            //Update ASP.NET indentity user
            var userName = string.Empty;

            using (var userManager = _userManagerFactory())
            {
                var dbUser = await userManager.FindByIdAsync(user.Id);

                result = ValidateUser(dbUser);

                if (result.Succeeded)
                {
                    userName = dbUser.UserName;

                    //Update ASP.NET indentity user
                    user.Patch(dbUser);
                    var identityResult = await userManager.UpdateAsync(dbUser);

                    result = identityResult.ToCoreModel();

                    //clear cache
                    ResetCache(user.Id, userName);
                }
            }

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

                    if (targetDbAcount == null)
                    {
                        result = new SecurityResult {
                            Errors = new[] { "Account not found." }
                        };
                    }
                    else
                    {
                        var changedDbAccount = user.ToDataModel();
                        using (var changeTracker = GetChangeTracker(repository))
                        {
                            //Detect account changes before patch
                            var changes = DetectAccountChanges(changedDbAccount, targetDbAcount);

                            changeTracker.Attach(targetDbAcount);
                            changedDbAccount.Patch(targetDbAcount);

                            repository.UnitOfWork.Commit();

                            foreach (var key in changes.Keys)
                            {
                                SaveOperationLog(user.Id, string.Format(key, string.Join(", ", changes[key].ToArray())), EntryState.Modified);
                            }
                        }
                    }
                }
            }

            return(result);
        }
Пример #27
0
        public async Task <SecurityResult> UpdateAsync(ApplicationUserExtended user)
        {
            SecurityResult result = null;

            if (user != null)
            {
                var dbUser = await _userManager.FindByIdAsync(user.Id);

                result = ValidateUser(dbUser);

                if (result.Succeeded)
                {
                    dbUser.InjectFrom(user);

                    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
                                });
                            }
                        }
                    }

                    var identityResult = await _userManager.UpdateAsync(dbUser);

                    result = identityResult.ToCoreModel();

                    if (result.Succeeded)
                    {
                        using (var repository = _platformRepository())
                        {
                            var acount = repository.GetAccountByName(user.UserName, UserDetails.Full);

                            if (acount == null)
                            {
                                result = new SecurityResult {
                                    Errors = new[] { "Acount not found." }
                                };
                            }
                            else
                            {
                                acount.RegisterType = (RegisterType)user.UserType;
                                acount.AccountState = (AccountState)user.UserState;
                                acount.MemberId     = user.MemberId;
                                acount.StoreId      = user.StoreId;

                                if (user.ApiAcounts != null)
                                {
                                    var sourceCollection = new ObservableCollection <ApiAccountEntity>(user.ApiAcounts.Select(x => x.ToEntity()));
                                    var comparer         = AnonymousComparer.Create((ApiAccountEntity x) => x.Id);
                                    acount.ApiAccounts.ObserveCollection(x => repository.Add(x), x => repository.Remove(x));
                                    sourceCollection.Patch(acount.ApiAccounts, comparer, (sourceItem, targetItem) => sourceItem.Patch(targetItem));
                                }

                                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(x => repository.Add(x), ra => repository.Remove(ra));
                                    sourceCollection.Patch(acount.RoleAssignments, comparer, (sourceItem, targetItem) => sourceItem.Patch(targetItem));
                                }

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

            return(result);
        }
Пример #28
0
        private static void validateResult(SecurityResult status)
        {
            if (status == SecurityResult.Success) return;

            throw new InvalidOperationException(
                String.Format("Security result error ({0}): {1}",
                status, SecurityItem.SecurityResultToString(status)));
        }
Пример #29
0
        private static string internalGetPassword(string userName, string serviceName, out SecurityResult status)
        {
            // Set up a query dictionary with the base query attributes:
            // item type (generic), username, and service

            NSObject[] keys = new NSObject[] {
                SecurityItem.kSecClass,
                SecurityItem.kSecAttrAccount,
                SecurityItem.kSecAttrService,
                SecurityItem.kSecReturnAttributes,
            };
            NSObject[] objects = new NSObject[] {
                SecurityItem.kSecClassGenericPassword,
                new NSString(userName),
                new NSString(serviceName),
                NSNumber.FromBoolean(true)
            };

            // First do a query for attributes, in case we already have a Keychain item
            // with no password data set. One likely way such an incorrect item could have come about
            // is due to the previous (incorrect) version of this code (which set the password
            // as a generic attribute instead of password data).

            NSDictionary dict = NSDictionary.FromObjectsAndKeys(objects, keys);

            keys[3] = SecurityItem.kSecReturnData;
            NSDictionary passQuery = NSDictionary.FromObjectsAndKeys(objects, keys);

            NSDictionary attributeResult = null;
            status = SecurityItem.CopyMatching(dict, ref attributeResult);
            dict.Dispose();

            if (status != SecurityResult.Success)
            {
                // No existing item found--simply return nil for the password
                if (status == SecurityResult.ItemNotFound)
                    status = SecurityResult.Success;
                return null;
            }

            // We have an existing item, now query for the password data associated with it.
            NSData resultData = null;
            status = SecurityItem.CopyMatching(passQuery, ref resultData);
            passQuery.Dispose();

            if (status != SecurityResult.Success)
            {
                if (status == SecurityResult.ItemNotFound)
                {
                    // We found attributes for the item previously, but no password now, so return a special error.
                    // Users of this API will probably want to detect this error and prompt the user to
                    // re-enter their credentials. When you attempt to store the re-entered credentials
                    // using storeUsername:andPassword:forServiceName:updateExisting:error
                    // the old, incorrect entry will be deleted and a new one with a properly encrypted
                    // password will be added.
                    status = SecurityResult.Deprecated;
                }
                else
                {
                    // Something else went wrong. Simply keep the normal Keychain API error code.
                }
                return null;
            }

            if (resultData != null)
            {
                return NSString.FromData(resultData, NSStringEncoding.UTF8);
            }

            // There is an existing item, but we weren't able to get password data
            // for it for some reason, Possibly as a result of an item being incorrectly
            // entered by the previous code. Set the -1999 error so the code above us
            // can prompt the user again.
            status = SecurityResult.Deprecated;
            return null;
        }
 private static string GetErrorMessage(SecurityResult result)
 {
     return(string.Join(",", result.Errors));
 }
Пример #31
0
        public virtual async Task <SecurityResult> UpdateAsync(ApplicationUserExtended user)
        {
            SecurityResult result;

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

            NormalizeUser(user);

            //Update ASP.NET indentity user
            var             userName = string.Empty;
            ApplicationUser dbUser   = null;

            using (var userManager = _userManagerFactory())
            {
                dbUser = await userManager.FindByIdAsync(user.Id);

                result = ValidateUser(dbUser);

                if (result.Succeeded)
                {
                    userName = dbUser.UserName;

                    //Update ASP.NET indentity user
                    user.Patch(dbUser);
                    var identityResult = await userManager.UpdateAsync(dbUser);

                    result = identityResult.ToCoreModel();

                    //clear cache
                    ResetCache(user.Id, userName);
                }
            }

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

                    if (targetDbAcount == null)
                    {
                        result = new SecurityResult {
                            Errors = new[] { "Account not found." }
                        };
                    }
                    else
                    {
                        var changedDbAccount = user.ToDataModel();
                        using (var changeTracker = GetChangeTracker(repository))
                        {
                            var userChangedEntry = new ChangedEntry <ApplicationUserExtended>(user, dbUser.ToCoreModel(targetDbAcount, _permissionScopeService), EntryState.Modified);
                            changeTracker.Attach(targetDbAcount);
                            changedDbAccount.Patch(targetDbAcount);

                            await _eventPublisher.Publish(new UserChangingEvent(userChangedEntry));

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

            return(result);
        }
        /// <exclude />
        public static FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer, TaskManagerEvent taskManagerEvent)
        {
            if (entityToken == null)
            {
                throw new ArgumentNullException("entityToken");
            }
            if (actionToken == null)
            {
                throw new ArgumentNullException("actionToken");
            }


            string username = UserValidationFacade.GetUsername();

#if NO_SECURITY
#else
            HookingFacade.EnsureInitialization();

            IEnumerable <UserPermissionDefinition>      userPermissionDefinitions      = PermissionTypeFacade.GetUserPermissionDefinitions(username);
            IEnumerable <UserGroupPermissionDefinition> userGroupPermissionDefinitions = PermissionTypeFacade.GetUserGroupPermissionDefinitions(username);
            SecurityResult securityResult = SecurityResolver.Resolve(UserValidationFacade.GetUserToken(), actionToken, entityToken, userPermissionDefinitions, userGroupPermissionDefinitions);
            if (securityResult != SecurityResult.Allowed && !(entityToken is SecurityViolationWorkflowEntityToken))
            {
                return(ExecuteSecurityViolation(actionToken, entityToken, flowControllerServicesContainer));
            }
#endif

            bool ignoreLocking = actionToken.IsIgnoreEntityTokenLocking();

            if (!ignoreLocking && ActionLockingFacade.IsLocked(entityToken))
            {
                return(ExecuteEntityTokenLocked(actionToken, entityToken, flowControllerServicesContainer));
            }

            IActionExecutor actionExecutor = ActionExecutorCache.GetActionExecutor(actionToken);

            ActionEventSystemFacade.FireOnBeforeActionExecution(entityToken, actionToken);

            FlowToken flowToken;
            using (TaskContainer taskContainer = TaskManagerFacade.CreateNewTasks(entityToken, actionToken, taskManagerEvent))
            {
                ITaskManagerFlowControllerService taskManagerService = null;
                if (flowControllerServicesContainer.GetService(typeof(ITaskManagerFlowControllerService)) == null)
                {
                    taskManagerService = new TaskManagerFlowControllerService(taskContainer);
                    flowControllerServicesContainer.AddService(taskManagerService);
                }

                try
                {
                    if (actionExecutor is IActionExecutorSerializedParameters)
                    {
                        string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken);
                        string serializedActionToken = ActionTokenSerializer.Serialize(actionToken);

                        flowToken = Execute(actionExecutor as IActionExecutorSerializedParameters,
                                            serializedEntityToken, serializedActionToken, actionToken,
                                            flowControllerServicesContainer);
                    }
                    else
                    {
                        flowToken = Execute(actionExecutor, entityToken, actionToken,
                                            flowControllerServicesContainer);
                    }
                }
                finally
                {
                    if (taskManagerService != null)
                    {
                        flowControllerServicesContainer.RemoveService(taskManagerService);
                    }
                }

                taskContainer.SetOnIdleTaskManagerEvent(new FlowTaskManagerEvent(flowToken));
                taskContainer.UpdateTasksWithFlowToken(flowToken);

                taskContainer.SaveTasks();
            }

            ActionEventSystemFacade.FireOnAfterActionExecution(entityToken, actionToken, flowToken);

            IManagementConsoleMessageService managementConsoleMessageService = flowControllerServicesContainer
                                                                               .GetService <IManagementConsoleMessageService>();
            if (managementConsoleMessageService != null)
            {
                FlowControllerFacade.RegisterNewFlowInformation(flowToken, entityToken, actionToken,
                                                                managementConsoleMessageService.CurrentConsoleId);
            }
            else
            {
                Log.LogWarning(nameof(ActionExecutorFacade), "Missing ManagementConsoleMessageService, can not register the flow");
            }

            return(flowToken);
        }
        public static OrderResult SubmitCustomerOrder(string contractId, OrderItem[] orderItems, KeyValueBunch extraArgs)
        {
            //
            Contract contract = ContractSystem.ContractController.GetContract(contractId);

            // Impersonate
            ContractSystem.ContractController.ImpersonateAsContractReseller(contract);
            //
            OrderResult oResult = new OrderResult();
            // check account
            SecurityResult sResult = StorehouseController.CheckAccountActive();

            //
            if (!sResult.Success)
            {
                //
                oResult.Succeed = false;
                //
                oResult.ResultCode = sResult.ResultCode;
                //
                return(oResult);
            }
            // check order items not empty
            if (orderItems == null || orderItems.Length == 0)
            {
                //
                oResult.Succeed = false;
                //
                oResult.ResultCode = EMPTY_ORDER_ITEMS_CODE;
                //
                return(oResult);
            }
            //
            ES.TaskManager.StartTask("Storefront", "SUBMIT_CUSTOMER_ORDER");

            //
            try
            {
                string currency = StorehouseController.GetBaseCurrency(contract.ResellerId);
                // ordered services
                List <int> orderedSvcs = new List <int>();
                // build services to be ordered
                for (int i = 0; i < orderItems.Length; i++)
                {
                    //
                    OrderItem orderItem = orderItems[i];
                    //
                    int orderedSvcId = 0;
                    //
                    orderItem.ParentSvcId = (orderItem.ParentIndex > -1) ? orderedSvcs[orderItem.ParentIndex] : orderItem.ParentSvcId;
                    // load svc type
                    ProductType svcType = StorehouseController.GetProductType(orderItem.TypeId);
                    //
                    IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
                        Type.GetType(svcType.ProvisioningController));
                    // add service
                    orderedSvcId = controller.AddServiceInfo(contractId, currency, orderItem);
                    // check service controller result
                    if (orderedSvcId < 1)
                    {
                        // ROLLBACK HERE
                        StorehouseController.BulkServiceDelete(contractId, orderedSvcs.ToArray());
                        oResult.Succeed    = false;
                        oResult.ResultCode = orderedSvcId;
                        return(oResult);
                        // EXIT
                    }
                    //
                    orderedSvcs.Add(orderedSvcId);
                }
                // build invoice lines
                List <InvoiceItem> invoiceLines = InvoiceController.CalculateInvoiceLinesForServices(orderedSvcs);
                //
                int resultCode = InvoiceController.AddInvoice(contractId, invoiceLines, extraArgs);
                // ERROR
                if (resultCode < 1)
                {
                    // ROLLBACK HERE
                    StorehouseController.BulkServiceDelete(contractId, orderedSvcs.ToArray());
                    oResult.Succeed    = false;
                    oResult.ResultCode = resultCode;
                    return(oResult);
                }
                //
                oResult.OrderInvoice = resultCode;
                //
                oResult.Succeed = true;
            }
            catch (Exception ex)
            {
                //
                oResult.ResultCode = -1;
                //
                oResult.Succeed = false;
                //
                ES.TaskManager.WriteError(ex);
            }
            finally
            {
                //
                ES.TaskManager.CompleteTask();
            }
            //
            return(oResult);
        }