Ejemplo n.º 1
0
        public async Task <DialogTurnResult> PasswordAsync(DialogContext dialogContext, string text, CancellationToken cancellationToken = default)
        {
            var user = (await _storageService.RetrieveEntityUsingPointQueryAsync <TableEntity>("User", dialogContext.Context.Activity.From.Name, dialogContext.Context.Activity.From.Id)).ToArray();

            if (user.Length == 0)
            {
                var password   = text.Replace("password", "").Trim();
                var userEntity = new UserEntity(dialogContext.Context.Activity.From.Name, dialogContext.Context.Activity.From.Id)
                {
                    Id       = new Guid(dialogContext.Context.Activity.From.Id),
                    Username = dialogContext.Context.Activity.From.Name,
                    Salt     = CryptographyProcessor.CreateSalt(8)
                };
                userEntity.Password  = CryptographyProcessor.GenerateHash(password, userEntity.Salt);
                userEntity.UpdatedAt = DateTime.Now;

                var entity = await _storageService.InsertOrMergeEntityAsync("User", userEntity);

                if (entity == null)
                {
                    await dialogContext.Context.SendActivityAsync(MessageFactory.Text("Try again."), cancellationToken);
                }
                else
                {
                    await dialogContext.Context.SendActivityAsync(MessageFactory.Text("You are successfully set password. To add new password from service use 'add SERVICE_NAME:PASSWORD' command. \nTo get password from service use 'get SERVICE_NAME' command. \n To get list pairs use 'get all' command"), cancellationToken);
                }
            }

            return(await dialogContext.CancelAllDialogsAsync(cancellationToken));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Register([FromBody] RegistrationForm model)
        {
            if (!ModelState.IsValid || model == null)
            {
                return(BadRequest());
            }

            if (await _db.Users.AnyAsync(x => x.Email.Equals(model.Email, StringComparison.OrdinalIgnoreCase)))
            {
                return(BadRequest(ControllerErrorCode.EmailAlreadyExists));
            }

            var cryptoProvider = new CryptographyProcessor();

            var salt = cryptoProvider.CreateSalt(AuthOptions.SaltSize);

            var passHash = cryptoProvider.GenerateHash(model.Password, salt);

            var newUser = new User()
            {
                Email    = model.Email.ToLower(),
                Salt     = salt,
                PassHash = passHash,
                Name     = model.Name,
                SurnName = model.Surname
            };

            await _db.Users.AddAsync(newUser);

            await _db.SaveChangesAsync();

            await SendMailAndGenerateCode(newUser);

            return(Ok("Success!"));
        }
Ejemplo n.º 3
0
        public async Task <DialogTurnResult> LoginAsync(DialogContext dialogContext, string text, CancellationToken cancellationToken = default)
        {
            if (await IsActiveSession(dialogContext, dialogContext.Context.Activity.From, cancellationToken, false))
            {
                await dialogContext.Context.SendActivityAsync(MessageFactory.Text("You are already logged in."), cancellationToken);

                return(await dialogContext.CancelAllDialogsAsync(cancellationToken));
            }

            var user = (await _storageService.RetrieveEntityUsingPointQueryAsync <UserEntity>("User", dialogContext.Context.Activity.From.Name, dialogContext.Context.Activity.From.Id)).ToArray();

            if (user.Length != 0)
            {
                var password = text.Replace("login", "").Trim();
                if (user[0].Password.Equals(CryptographyProcessor.GenerateHash(password, user[0].Salt)))
                {
                    user[0].UpdatedAt = DateTime.UtcNow;
                    await _storageService.InsertOrMergeEntityAsync("User", user[0]);

                    await dialogContext.Context.SendActivityAsync(MessageFactory.Text("You are successfully logged in. To add new password from service use 'add SERVICE_NAME:PASSWORD' command. \nTo get password from service use 'get SERVICE_NAME' command. \n To get list pairs use 'get all' command"), cancellationToken);
                }
                else
                {
                    await dialogContext.Context.SendActivityAsync(MessageFactory.Text("Your password is wrong. Please try again."), cancellationToken);
                }
            }

            return(await dialogContext.CancelAllDialogsAsync(cancellationToken));
        }
Ejemplo n.º 4
0
        private void createNewMainFile()
        {
            hospitalStructure = new HospitalStructure();
            string   salt  = CryptographyProcessor.CreateSalt(hospitalStructure.SaltLength);
            Employee admin = new Employee(
                1,
                "Serhii",
                "Holishevskyi",
                "dnldcode",
                CryptographyProcessor.GenerateHash("password", salt),
                salt,
                Position.Administration);

            hospitalStructure.Employees.Add(admin);

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(HospitalStructure));

            try
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Create))
                {
                    xmlSerializer.Serialize(fs, hospitalStructure);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(
                    $"Error occured: {e.Message}",
                    "Something went wrong...",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                Environment.Exit(0);
            }
        }
        private Users RegisterUser(UserRegistrationRequestDetails registrationDetailsRequest)
        {
            Users userToReturnAfterSuccessfullCreation = null;

            Users newUser = new Users();

            newUser.FirstName  = registrationDetailsRequest.FirstName;
            newUser.LastName   = registrationDetailsRequest.LastName;
            newUser.MiddleName = registrationDetailsRequest.MiddleName;

            newUser.Username = registrationDetailsRequest.Username;
            newUser.Email    = registrationDetailsRequest.Email;

            string applicationSecretSolt     = this._config["Jwt:ExtraApplicationPasswordsEncryptionInAdditionToRandomSalts"];
            int    randomGeneratedSoltLength = int.Parse(this._config["Jwt:CryptographyProcessorRandomSoltLength"]);
            string randomGeneratedSoltForPasswordEncryptionAndDatabaseSaving = CryptographyProcessor.CreateSalt(randomGeneratedSoltLength);

            string encryptedHashedPassword = CryptographyProcessor.GenerateHash(
                registrationDetailsRequest.Password,
                randomGeneratedSoltForPasswordEncryptionAndDatabaseSaving,
                applicationSecretSolt);

            newUser.EcryptedPassword     = encryptedHashedPassword;
            newUser.EncryptionRandomSalt = randomGeneratedSoltForPasswordEncryptionAndDatabaseSaving;

            newUser.BirthDate        = registrationDetailsRequest.BirthDate;
            newUser.RegistrationDate = DateTime.UtcNow;

            newUser.CountryCode = registrationDetailsRequest.CountryCode;
            newUser.CountryName = registrationDetailsRequest.CountryName;

            //Users userToReturnAfterSuccessfullCreation = Business_Logic_Layer_Facade.Instance.Users_InsertUser(newUser);

            return(userToReturnAfterSuccessfullCreation);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Add new User
        /// </summary>
        /// <param name="userModel">User model</param>
        /// <returns>User response model when user is created</returns>
        public UserResponseModel Add(UserRequestModel userModel)
        {
            string _salt         = CryptographyProcessor.CreateSalt(16);
            string _passwordHash = CryptographyProcessor.GenerateHash(userModel.Password, _salt);

            var user = new User
            {
                FirstName    = userModel.FirstName,
                LastName     = userModel.LastName,
                Email        = userModel.Email,
                PasswordHash = _passwordHash,
                ExpiresAt    = DateTime.UtcNow.AddDays(1),
                Salt         = _salt,
                AddedAt      = DateTime.UtcNow
            };

            _unitOfWork.UserRepository.Add(user);
            _unitOfWork.Commit();

            return(_mapper.Map <UserResponseModel>(user));
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> ResetPassword([FromBody] ChangePassByCodeForm form)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ControllerErrorCode.WrongInputData));
            }

            var user = await _db.Users.FirstOrDefaultAsync(x => x.Email.Equals(form.Email, StringComparison.OrdinalIgnoreCase));

            if (user == null)
            {
                return(BadRequest(ControllerErrorCode.AccountNotFound));
            }

            var code = await _db.ForgotCodes.FirstOrDefaultAsync(x => x.Code == form.Code);

            if (code == null)
            {
                return(BadRequest(ControllerErrorCode.WrongRegCode));
            }

            if (code.ExpireDate < DateTime.UtcNow)
            {
                return(BadRequest(ControllerErrorCode.ExpiredCode));
            }

            var cryptoProvider = new CryptographyProcessor();

            var salt = cryptoProvider.CreateSalt(AuthOptions.SaltSize);

            var passHash = cryptoProvider.GenerateHash(form.Password, salt);

            user.PassHash = passHash;

            user.Salt = salt;

            await _db.SaveChangesAsync();

            return(Ok());
        }
        private void buttonMain_Click(object sender, EventArgs e)
        {
            if (errorProvider1.GetError(nameInput) == "" &&
                errorProvider1.GetError(surnameInput) == "" &&
                errorProvider1.GetError(loginInput) == "" &&
                errorProvider1.GetError(passwordInput) == "" &&
                errorProvider1.GetError(gmcInput) == "" &&
                nameInput.Text.Trim() != "" &&
                surnameInput.Text.Trim() != "" &&
                loginInput.Text.Trim() != "" &&
                (passwordInput.Text.Trim() != "" || this.state == "Edit") &&
                (gmcInput.Text.Trim() != "" || ((Position)comboBoxPosition.SelectedItem != Position.Doctor)))
            {
                if (this.state == "Add")
                {
                    string salt = CryptographyProcessor.CreateSalt(Main.HospitalStructure.SaltLength);

                    Position   type       = (Position)comboBoxPosition.SelectedItem;
                    Speciality speciality = (Speciality)comboBoxSpeciality.SelectedItem;
                    string     gmc        = gmcInput.Text == "" ? null : gmcInput.Text;

                    Employee user = new Employee(
                        int.Parse(idInput.Text),
                        nameInput.Text,
                        surnameInput.Text,
                        loginInput.Text,
                        CryptographyProcessor.GenerateHash(passwordInput.Text, salt),
                        salt,
                        type,
                        speciality,
                        gmc);

                    Main.HospitalStructure.Employees.Add(user);

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else if (this.state == "Edit")
                {
                    Position   type       = (Position)comboBoxPosition.SelectedItem;
                    Speciality speciality = (Speciality)comboBoxSpeciality.SelectedItem;
                    string     gmc        = gmcInput.Text == "" ? null : gmcInput.Text;

                    if ((_currentEmployee.TypeOfUser == Position.Doctor || _currentEmployee.TypeOfUser == Position.Nurse) &&
                        (type == Position.Administration || type == Position.Banned))
                    {
                        if (MessageBox.Show(
                                $"Position has been changed from {_currentEmployee.TypeOfUser} to {type}. Do you want to delete all duties of employee?",
                                "Question",
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            List <Duty> listToDelete = new List <Duty>();

                            foreach (Duty d in Main.HospitalStructure.Duties)
                            {
                                if (d.EmployeeId == _currentEmployee.Id)
                                {
                                    listToDelete.Add(d);
                                }
                            }

                            foreach (Duty d in listToDelete)
                            {
                                Main.HospitalStructure.Duties.Remove(d);
                            }
                        }
                    }

                    _currentEmployee.Name    = nameInput.Text;
                    _currentEmployee.Surname = surnameInput.Text;

                    if (passwordInput.Text != "")
                    {
                        _currentEmployee.Password
                            = CryptographyProcessor.GenerateHash(
                                  passwordInput.Text,
                                  _currentEmployee.Salt);
                    }

                    _currentEmployee.TypeOfUser = type;
                    _currentEmployee.Speciality = speciality;
                    _currentEmployee.GMC        = gmc;

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
        }