예제 #1
0
        public async Task <CommandResult> Handle(AuthenticateUserCommand request, CancellationToken cancellationToken)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var user = await _entitiesRepository.GetFirstOrDefaultAsync <User>(u => u.Username == request.Username.ToLower());

            if (user != null)
            {
                if (!user.IsDisabled)
                {
                    if (SecurityUtility.IsMatchingHash(request.Password, user.HashedPassword, user.Salt))
                    {
                        return(new CommandResult()
                        {
                            ObjectRefId = user.Username,
                            ElapsedMs = stopwatch.ElapsedMilliseconds,
                            Type = CommandResultTypes.None
                        });
                    }
                }
            }
            return(new CommandResult()
            {
                ElapsedMs = stopwatch.ElapsedMilliseconds,
                ObjectRefId = null,
                Type = CommandResultTypes.None
            });
        }
예제 #2
0
        protected override bool CheckSignature()
        {
            List <string> list = new List <string>();

            list.Add(PublicToken);
            list.Add(Timestamp);
            list.Add(Nonce);
            //排序
            list.Sort();
            //拼串
            string input = string.Empty;

            foreach (var item in list)
            {
                input += item;
            }
            //加密
            string new_signature = SecurityUtility.SHA1Encrypt(input);

            log.Info("new_signature : " + new_signature);
            //验证
            if (new_signature == Signature)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #3
0
        public ConfirmationResponse Execute(ChangePasswordRequest request)
        {
            request.ThrowExceptionIfInvalid();
            if (request.ForUserId != Identity.FromString(request.UserId))
            {
                throw new UseCaseException("Can't change data of another user.");
            }

            var entity = _personRepository.Read(request.ForUserId);
            var person = _personRepository.FindByEmailAndPasswordHash(entity.Email, SecurityUtility.HashPassword(request.OldPassword));

            if (person == null)
            {
                request.Errors.Add("", "Old password is invalid.");
                throw new InvalidRequestException {
                          Errors = request.Errors
                };
            }

            person.PasswordHash = SecurityUtility.HashPassword(request.NewPassword);

            _personRepository.ChangePassword(person);

            return(new ConfirmationResponse("Password changed successfully.")
            {
                Id = person.Id,
            });
        }
예제 #4
0
        public ActionResult Edit(NewsModel news)
        {
            try
            {
                int userId = -1;
                if (Session["UserId"] != null)
                {
                    userId = int.Parse(Session["UserID"].ToString());
                }

                BLLNews  bll        = new BLLNews();
                NewsInfo newsObjest = new NewsInfo()
                {
                    NewId      = news.NewId,
                    Title      = news.Title,
                    Content    = SecurityUtility.RemoveIllegalCharacters(news.Message),
                    CreateDate = DateTime.Now,
                    IsDelete   = false,
                    IsTop      = false,
                    IsPublic   = true,
                    ViewTimes  = 0,
                    UserId     = userId,
                    ImageUrl   = ""
                };
                //编辑信息 之后提交更新
                bll.Update(newsObjest);
                return(RedirectToAction("Index", "News"));
            }
            catch (Exception)
            {
                return(View());
            }
        }
예제 #5
0
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            oldPassword = oldPassword.Trim();
            if (!SecurityUtility.IsPasswordValid(newPassword))
            {
                return(false);
            }
            var user = SecurityUtility.GetUserByUsername(username);

            if (user == null)
            {
                return(false);
            }
            var feedbackMessage = new System.Text.StringBuilder();

            if (user.Password != oldPassword && user.Password != Cryptography.EncryptPassword(oldPassword, user.Salt))
            {
                return(false);
            }

            user.Password = Cryptography.EncryptPassword(newPassword, user.Salt);
            IRepositoryProvider _repositoryProvider = new RepositoryProvider(new RepositoryFactories());
            var unitofWork = new UnitOfWork(new MisukaDBContext(), _repositoryProvider);

            unitofWork.Repository <Domain.Entity.User>().Update(user);
            var ret = unitofWork.SaveChanges();

            return(ret > 0);
        }
        private bool IsValid(string license)
        {
            try
            {
                if (string.IsNullOrEmpty(license))
                {
                    throw new ArgumentNullException();
                }

                var request = new ValidateRequest
                {
                    License     = license,
                    FingerPrint = SecurityUtility.GetMd5Hash(AppConfigUtility.FingerPrint)
                };

                var response = WebServiceUtility.Post(AppConfigUtility.ValidateLicenseUrl, request.ToJSON());

                if (!response.Success)
                {
                    throw new LicenseNotValidException(response.Message);
                }

                return(true);
            }
            catch (LicenseNotValidException)
            {
                throw;
            }
            catch (Exception ex)
            {
                LogUtility.Log(LogUtility.LogType.SystemError, MethodBase.GetCurrentMethod().Name, ex.Message);
                return(false);
            }
        }
예제 #7
0
        /// <summary>
        /// 检查签名
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private bool CheckSignature()
        {
            string signature = Request.QueryString[SIGNATURE];
            string timestamp = Request.QueryString[TIMESTAMP];
            string nonce     = Request.QueryString[NONCE];

            List <string> list = new List <string>();

            list.Add(TOKEN);
            list.Add(timestamp);
            list.Add(nonce);
            //排序
            list.Sort();
            //拼串
            string input = string.Empty;

            foreach (var item in list)
            {
                input += item;
            }
            //加密
            string new_signature = SecurityUtility.SHA1Encrypt(input);

            //验证
            if (new_signature == signature)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #8
0
        public async void CreateStepWithSecret()
        {
            Mock <IEntitiesRepository> entitiesRepository = new Mock <IEntitiesRepository>();

            entitiesRepository.Setup(sr => sr.GetFirstOrDefaultAsync <StepTemplate>(It.IsAny <Expression <Func <StepTemplate, bool> > >())).Returns(Task.FromResult(SecretSampleData.StepTemplate));
            var stepTemplate = await entitiesRepository.Object.GetFirstOrDefaultAsync <StepTemplate>(st => st.ReferenceId == SecretSampleData.StepTemplate.ReferenceId);

            var newStep = stepTemplate.GenerateStep(stepTemplate.ReferenceId, "", "", "", new Dictionary <string, object>()
            {
                { "secret", "This is a test" }
            }, null, null, ClusterStateService.GetEncryptionKey());

            _node.Setup(n => n.Handle(It.IsAny <AddShardWriteOperation>())).Returns(Task.FromResult(new AddShardWriteOperationResponse()
            {
                IsSuccessful = true
            }));

            var handler = new CreateStepCommandHandler(entitiesRepository.Object, clusterMoq.Object, _node.Object);

            var step = await handler.Handle(new CreateStepCommand()
            {
                StepTemplateId = stepTemplate.ReferenceId,
                Inputs         = new Dictionary <string, object>()
                {
                    { "secret", "This is a test" }
                }
            }, new System.Threading.CancellationToken());

            //Test encryption of step worked
            Assert.NotEqual("This is a test", (string)step.Result.Inputs["secret"]);
            //Test decryption of step
            Assert.Equal("This is a test", SecurityUtility.SymmetricallyDecrypt((string)step.Result.Inputs["secret"], ClusterStateService.GetEncryptionKey()));
        }
예제 #9
0
        public override bool ValidateUser(string username, string password)
        {
            password = password.Trim();
            var user = SecurityUtility.GetUserByUsername(username);

            if (user != null)
            {
                ////  if (!user.Active || user.AccountLocked)
                //if (user.Locked)
                //  return false;

                if (SecurityUtility.IsPasswordEqual(password, user.Password, user.Salt))
                {
                    //Stored valid logged user to session
                    new UserSession(user);
                    user.LastLoginTime    = DateTime.Now;
                    user.FailedLoginTimes = 0;
                    SecurityUtility.UpdateUserInformation(user);
                    return(true);
                }

                user.LastLoginTime = DateTime.Now;
                user.FailedLoginTimes++;


                SecurityUtility.UpdateUserInformation(user);
            }

            return(false);
        }
예제 #10
0
        internal virtual void SaveAuthenticatedIdentity()
        {
            if (SessionData == null)
            {
                return;
            }

            Principal = CreatePrincipal();
            if (Context != null)
            {
                Context.User = Principal;
            }

            if (SessionData.Saved)
            {
                return;
            }

            SessionData.Saved = true;
            if (Context != null)
            {
                AuthenticationCookieManager.Save(SessionData.Username, Context);
            }

            SessionData.RoleIds         = SecurityUtility.GetRoleIds(SessionData.UserId);
            SessionData.IsAdministrator = SessionData.RoleIds != null && SessionData.RoleIds.Contains(SystemConfiguration.Instance.SecuritySettings.AdministratorRole);

            SessionObjectStorageStrategy.Save(SessionData);
        }
예제 #11
0
        public async Task <IActionResult> Login(LoginViewModel vm)
        {
            if (!ModelState.IsValid)
            {
                return(View(vm));
            }

            var repository = _repositoryProvider.Person;
            var person     = repository.FindByEmailAndPasswordHash(vm.Email, SecurityUtility.HashPassword(vm.Password));

            if (person != null)
            {
                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, person.DisplayName),
                    new Claim(ClaimTypes.NameIdentifier, person.Id.ToPresentationIdentity())
                };

                var userIdentity  = new ClaimsIdentity(claims, "SecureLogin");
                var userPrincipal = new ClaimsPrincipal(userIdentity);

                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                              userPrincipal,
                                              new AuthenticationProperties
                {
                    ExpiresUtc   = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });

                return(RedirectToAction(nameof(Index)));
            }
            MessageHandler(MessageType.Error, "Username or password is invalid.");
            return(View());
        }
        /// <summary>
        /// Saves keys
        /// </summary>
        private void OnSaveCommand()
        {
            // check app sid length
            if (this.AppSidText.Length != 36)
            {
                DialogManager.ShowErrorDialog("Incorrect APP SID length! APP SID should be 36 symbols length.");
                return;
            }

            // check app key length
            if (this.AppKeyText.Length != 32)
            {
                DialogManager.ShowErrorDialog("Incorrect APP KEY length! APP KEY should be 32 symbols length.");
                return;
            }

            // update keys to provide new values
            CoreApi.UpdateKeys(this.AppKeyText, this.AppSidText);

            // encrypt keys and save in settings
            byte[] encryptedAppKey = SecurityUtility.Encrypt(Encoding.UTF8.GetBytes(this.AppKeyText));
            byte[] encryptedAppSid = SecurityUtility.Encrypt(Encoding.UTF8.GetBytes(this.AppSidText));
            UserSettingsUtility.SaveCredentials(encryptedAppKey, encryptedAppSid);

            this.view.Close();
        }
예제 #13
0
        public async Task <FunctionSecrets> GetFunctionSecretsAsync(string functionName)
        {
            FunctionSecrets secrets;
            string          secretFilePath = GetFunctionSecretsFilePath(functionName);

            if (FileSystemHelpers.FileExists(secretFilePath))
            {
                // load the secrets file
                string secretsJson = await FileSystemHelpers.ReadAllTextFromFileAsync(secretFilePath);

                secrets = JsonConvert.DeserializeObject <FunctionSecrets>(secretsJson);
            }
            else
            {
                // initialize with new secrets and save it
                secrets = new FunctionSecrets
                {
                    Key = SecurityUtility.GenerateSecretString()
                };

                FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(secretFilePath));
                await FileSystemHelpers.WriteAllTextToFileAsync(secretFilePath, JsonConvert.SerializeObject(secrets, Formatting.Indented));
            }

            secrets.TriggerUrl = String.Format(@"https://{0}/api/{1}?code={2}",
                                               System.Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME") ?? "localhost",
                                               functionName,
                                               secrets.Key);

            return(secrets);
        }
예제 #14
0
        protected string Security(SecurityMode securityMode, string source)
        {
            switch (_securityComponentMode)
            {
            case SecurityComponentMode.Base64:
                _securityUtility = new Base64Helper();
                break;

            case SecurityComponentMode.DES:
                _securityUtility = new DESHelper();
                break;

            case SecurityComponentMode.MD5:
                _securityUtility = new MD5Helper();
                break;

            case SecurityComponentMode.RSACryption:
                _securityUtility = new RSACryptionHelper(_privateKey, _publicKey);
                break;

            case SecurityComponentMode.TripleDES:
                _securityUtility = new TripleDESHelper();
                break;

            default:
                break;
            }
            return(_securityUtility.SecurityUtilityInvoke(securityMode).Invoke(source));
        }
예제 #15
0
        public void Register(RegisterCommand command)
        {
            ISecurityUtility securityUtility = new SecurityUtility();

            ThrowError.Against <ArgumentException>(string.IsNullOrEmpty(command.UserName), String.Format(ErrorMessage.IsRequired, "Tên đăng nhập"));
            ThrowError.Against <ArgumentException>(string.IsNullOrEmpty(command.Password), String.Format(ErrorMessage.IsRequired, "Mật khẩu"));
            var user = securityUtility.GetUserByUsername(command.UserName);

            ThrowError.Against <ArgumentException>(user != null, String.Format(ErrorMessage.Exists, "Tên đăng nhập"));
            ThrowError.Against <ArgumentException>(_personService.Query(t => t.Email == command.Email).Select().Any(), String.Format(ErrorMessage.Exists, "Email"));

            // ThrowError.Against<ArgumentException>(!securityUtility.IsPasswordValid(command.Password), String.Format(ErrorMessage.IsPassword));

            var person = new Person()
            {
                Email    = command.Email,
                FullName = command.FullName,
                PersonId = Guid.NewGuid()
            };

            user = new User()
            {
                Type         = command.Type,
                UserName     = command.UserName,
                CreationDate = DateTime.Now,
                Locked       = false,
                PersonId     = person.PersonId,
                Password     = Cryptography.EncryptPassword(command.Password, "")
            };

            _unitOfWork.Repository <Domain.Entity.User>().Insert(user);
            _personService.Insert(person);
            _unitOfWork.SaveChanges();
        }
예제 #16
0
        public async Task <CommandResult> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var  salt        = SecurityUtility.GenerateSalt(128);
            Guid id          = Guid.NewGuid();
            var  createdUser = await _entitiesRepository.Insert(new Domain.Entities.Users.User(
                                                                    request.Username.ToLower(),
                                                                    SecurityUtility.OneWayHash(request.Password, salt),
                                                                    request.Username.ToLower(),
                                                                    salt,
                                                                    request.CreatedBy,
                                                                    DateTime.UtcNow,
                                                                    id
                                                                    ));

            return(new CommandResult()
            {
                ElapsedMs = stopwatch.ElapsedMilliseconds,
                ObjectRefId = id.ToString(),
                Type = CommandResultTypes.Create
            });
        }
예제 #17
0
        // Retrieves the user record
        private DataSet Retrieve(string sUserName, string sPassword)
        {
            DataSet   dsUser = new DataSet();
            DataTable dtUser = new DataTable();
            DataRow   drUser;
            string    sPasswordSalt;

            // Since the Northwind database does not have a user table, just generate the dataset

            // Add the columns to the table
            dtUser.Columns.Add(FN_USER_NAME);
            dtUser.Columns.Add(FN_PASSWORD_ENCODED);
            dtUser.Columns.Add(FN_PASSWORD_SALT);
            dtUser.Columns.Add(FN_STATUS);

            // Add the data to the row
            drUser = dtUser.NewRow();
            drUser[FN_USER_NAME]        = "DeborahK";
            sPasswordSalt               = SecurityUtility.ComputeSalt();
            drUser[FN_PASSWORD_ENCODED] = SecurityUtility.ComputeHash(sPasswordSalt + sPassword);
            drUser[FN_PASSWORD_SALT]    = sPasswordSalt;
            drUser[FN_STATUS]           = STATUS_ACTIVE;

            //Add the row to the table
            dtUser.Rows.Add(drUser);

            // Add the table to the dataset
            dsUser.Tables.Add(dtUser);

            // Set the table name
            dsUser.Tables[0].TableName = TN_USER;

            return(dsUser);
        }
        public void UtilityTest()
        {
            var admin = SecurityUtility.EncryptAndEncode("admin");

            Assert.True(SecurityUtility.DecodeAndDecrypt(admin) == "admin");
            Assert.True(SecurityUtility.DecodeAndDecrypt("4eIVszyvsMJErvFLw/kxJg==") == "admin");
        }
        /// <summary>
        /// Initializes the change groups dialog with current user group settings
        /// </summary>
        private void InitializeChangeGroupsDialog()
        {
            AvailableGroups.Items.Clear();
            SelectedGroups.Items.Clear();
            IList <Group>  managableGroups    = SecurityUtility.GetManagableGroups();
            IList <string> subscriptionGroups = new List <string>();

            foreach (Group group in managableGroups)
            {
                if (group.SubscriptionPlans != null && group.SubscriptionPlans.Count > 0)
                {
                    if (_User.IsInGroup(group.Id))
                    {
                        subscriptionGroups.Add(group.Name);
                        PHSubscriptionGroups.Controls.Add(new LiteralControl(string.Format("<option disabled='disabled'>{0}</option>", group.Name)));
                    }
                }
                else
                {
                    ListItem newItem       = new ListItem(group.Name, group.Id.ToString());
                    bool     groupSelected = _User.IsInGroup(group.Id);
                    if (groupSelected)
                    {
                        SelectedGroups.Items.Add(newItem);
                    }
                    else
                    {
                        AvailableGroups.Items.Add(newItem);
                    }
                }
            }
            phMyGroupsWarning.Visible   = (_UserId == AbleContext.Current.UserId);
            SubscriptionGroupLI.Visible = subscriptionGroups.Count > 0;
        }
예제 #20
0
        private static RemoteMethodInfo GetRemoteMethod(MethodInfo method)
        {
            string serviceKey = SecurityUtility.HashObject(method.DeclaringType);
            RemoteMethodAttribute rmAttribute = method.GetCustomAttributes(typeof(RemoteMethodAttribute), true)[0] as RemoteMethodAttribute;

            return(new RemoteMethodInfo(SecurityUtility.HashObject(method), serviceKey, method.Name, rmAttribute.Description, rmAttribute.Offline, method, String.Empty));
        }
예제 #21
0
        protected void Page_Init(object sender, System.EventArgs e)
        {
            // locate group to delete
            _GroupId = AlwaysConvert.ToInt(Request.QueryString["GroupId"]);
            Group group = GroupDataSource.Load(_GroupId);

            if (group == null)
            {
                Response.Redirect("Default.aspx");
            }

            // groups managed by the application cannot be deleted
            if (group.IsReadOnly)
            {
                Response.Redirect("Default.aspx");
            }

            // ensure user has permission to edit this group
            IList <Group> managableGroups = SecurityUtility.GetManagableGroups();

            if (managableGroups.IndexOf(group) < 0)
            {
                Response.Redirect("Default.aspx");
            }

            Caption.Text         = string.Format(Caption.Text, group.Name);
            InstructionText.Text = string.Format(InstructionText.Text, group.Name);
            BindGroups(group);
        }
예제 #22
0
 /// <summary>
 /// Encodes the invoke.
 /// </summary>
 /// <param name="method">The method.</param>
 /// <param name="parameter">The parameter.</param>
 /// <param name="encryptKey">The encrypt key.</param>
 /// <param name="package">The package.</param>
 public static void EncodeInvoke(MethodInfo method, object parameters, string encryptKey, ref NetworkInvokePackage package)
 {
     package.Context[METHOD]            = serializer.Serialize <MethodInfo>(method);
     package.Context[METHOD_NAME]       = serializer.Serialize <string>(method.Name);
     package.Context[METHOD_ISGENERIC]  = method.IsGenericMethod;
     package.Context[METHOD_PARAMETERS] = SecurityUtility.DESEncrypt(serializer.Serialize <object>(parameters), encryptKey);
     package.Context[METHOD_INVOKEINFO] = SecurityUtility.DESEncrypt(serializer.Serialize <MethodInvokeInfo>(new MethodInvokeInfo(method)), encryptKey);
 }
예제 #23
0
        private void AuthorizeClientWithBotId(HttpClient client)
        {
            _nonce++;
            var nonceKey = SecurityUtility.RsaEncryptWithPrivate("" + _nonce, keyPair.PrivateKey);

            client.DefaultRequestHeaders.Add("BotKey", _botId);
            client.DefaultRequestHeaders.Add("Nonce", nonceKey);
        }
예제 #24
0
    private static void SaveStringValue(string key, string finalValue)
    {
        string encrypedKey    = Use_Encrypt ? SecurityUtility.GetInstance().EncryptString(key) : key;
        string encryptedValue = Use_Encrypt ? CombineEncryptKeyAndValue(key, finalValue) : finalValue;

        PlayerPrefs.SetString(encrypedKey, encryptedValue);
        PlayerPrefs.Save();
    }
예제 #25
0
        public static CollectionOfConnectStrings EncrpytConnectionString(string key,
                                                                         CollectionOfConnectStrings connectStrings)
        {
            connectStrings.ReadOnlyConnectionString =
                SecurityUtility.EncryptString(key, connectStrings.ReadOnlyConnectionString);

            return(connectStrings);
        }
예제 #26
0
        public BotClient(BotClientOptions options)
        {
            _url    = options.Url;
            _nonce  = 0;
            keyPair = SecurityUtility.GenerateRSAKeyPair(2048);
            var result = RegisterBot(options.Name, keyPair.PublicKey).GetAwaiter().GetResult();

            _botId = result.IdKey;
        }
예제 #27
0
        public BotClient(string botName, string url)
        {
            _url    = url;
            _nonce  = 0;
            keyPair = SecurityUtility.GenerateRSAKeyPair(2048);
            var result = RegisterBot(botName, keyPair.PublicKey).GetAwaiter().GetResult();

            _botId = result.IdKey;
        }
예제 #28
0
 public static SecurityUtility GetInstance()
 {
     if (instance == null)
     {
         instance        = new SecurityUtility();
         instance.offset = Random.Range(0, 100000);
     }
     return(instance);
 }
예제 #29
0
        public Step GenerateStep(string stepTemplateId, string createdBy, string name = "", string description = "", Dictionary <string, object> inputs = null, List <string> stepTestTemplateIds = null, Guid?workflowId = null, string encryptionKey = "", Guid?executionTemplateId = null, Guid?executionScheduleId = null)
        {
            var verifiedInputs = new Dictionary <string, object>();

            if (inputs != null)
            {
                if (inputs.Count() > InputDefinitions.Count() && !AllowDynamicInputs)
                {
                    throw new InvalidStepInputException("Too many step inputs for step template " + Id + " were given, expected " + InputDefinitions.Count() + " got " + inputs.Count());
                }

                if (InputDefinitions.Count() > inputs.Count())
                {
                    string missingInputs = "";
                    foreach (var id in InputDefinitions)
                    {
                        if (!inputs.Select(i => i.Key).Contains(id.Key))
                        {
                            inputs.Add(id.Key, null);
                            //missingInputs += id.Key + " ";
                        }
                    }
                    //throw new InvalidStepInputException("Missing step inputs for step template " + Id + ", expected " + InputDefinitions.Count() + " got " + inputs.Count() + " missing ");
                }

                foreach (var input in inputs)
                {
                    var foundTemplate = InputDefinitions.Where(tp => tp.Key == input.Key).FirstOrDefault();

                    if (!IsStepInputValid(input))
                    {
                        throw new InvalidStepInputException("Step input " + input.Key + " is not found in the template definition.");
                    }

                    if ((AllowDynamicInputs && !InputDefinitions.ContainsKey(input.Key)) || InputDefinitions.ContainsKey(input.Key))
                    {
                        if (InputDefinitions.ContainsKey(input.Key) && InputDefinitions[input.Key].Type == InputDataTypes.Secret && !InputDataUtility.IsInputReference(input, out _, out _))
                        {
                            verifiedInputs.Add(input.Key.ToLower(), SecurityUtility.SymmetricallyEncrypt((string)input.Value, encryptionKey));
                        }
                        else
                        {
                            verifiedInputs.Add(input.Key.ToLower(), input.Value);
                        }
                    }
                }
            }
            else if (inputs == null && InputDefinitions.Count() > 0)
            {
                throw new InvalidStepInputException("No inputs were specified however step template " + Id + " has " + InputDefinitions.Count() + " inputs.");
            }

            var newStep = new Step(Guid.NewGuid(), name, description, stepTemplateId, createdBy, verifiedInputs, encryptionKey, workflowId, executionTemplateId, executionScheduleId);

            return(newStep);
        }
예제 #30
0
        public UploadFileResult UploadFile(string fileID, string fileName, byte[] data, bool isFirstChunk, bool isLastChunk, Dictionary <string, string> customParams)
        {
            UploadFileResult result       = new UploadFileResult();
            string           extension    = Path.GetExtension(fileName);
            string           tempFileName = "";
            string           tempFilePath = "";

            string tempUpFilePath = TempPathForUploadedFiles;

            if (!Directory.Exists(tempUpFilePath))
            {
                Directory.CreateDirectory(tempUpFilePath);
            }

            if (isFirstChunk)
            {
                // 第一个文件块
                ServiceLog.Log("大文件上传", "UploadFileService", fileName, "开始上传啦");
                tempFileName = GetNewFileName(tempUpFilePath, extension) + "_temp";
                tempFilePath = Path.Combine(tempUpFilePath, tempFileName);
            }
            else
            {
                // 非第一个文件块
                tempFileName = fileID;
                tempFilePath = Path.Combine(tempUpFilePath, tempFileName);
            }

            // 临时文件名作为文件唯一标识
            result.FileID = tempFileName;

            // 生成 SHA1 散列值
            result.SHA1 = SecurityUtility.SHA1(data);

            // 写入数据
            using (FileStream fs = File.Open(tempFilePath, FileMode.Append))
            {
                fs.Write(data, 0, data.Length);
                fs.Flush();
                fs.Close();
            }

            if (isLastChunk)
            {
                // 保存上传文件
                result.FileID = DealUploadedFile(fileName, tempFilePath, customParams);

                // 删除临时文件
                if (File.Exists(tempFilePath))
                {
                    File.Delete(tempFilePath);
                }
            }

            return(result);
        }