예제 #1
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));
        }
예제 #2
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));
        }
예제 #3
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!"));
        }
예제 #4
0
        //  public DbSet<FormFile> Images { get; set; }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            /*modelBuilder.Entity<Location>(entity =>
             * {
             *  entity.HasKey(e => e.Id);
             * });*/

            //data seed

            //superadmin
            modelBuilder.Entity <User>().HasData(new User()
            {
                Id           = -2,
                Email        = "admin",
                PasswordHash = CryptographyProcessor.Hash("admin"),
                UserRole     = UserRoles.SuperAdmin
            });

            modelBuilder.Entity <Field>().HasIndex(field => field.ParentType);

            // modelBuilder.Entity<Field>().HasOne<FieldValue>().WithMany(value => value.FieldId)

            modelBuilder.Entity <Field>()
            .Property(c => c.ParentType)
            .HasConversion <int>();

            base.OnModelCreating(modelBuilder);
        }
        private Users AuthenticateUser(UserLoginDetails loginDetailsRequest)
        {
            Users userDetailsToReturnForAuthentication = null;

            // First step is to check if the username/email is in the databsae
            //var userDetails = BusinessLogicLayerFacade.Instance.Users_GetByUsername(loginDetailsRequest.Username);
            Users userDetails = null;

            if (userDetails != null)
            {
                // There is such a user grab the salted hashed string and generate the password and check if its right against the stored encryptedPassword in the database
                string passwordSaltInDatabase      = userDetails.EncryptionRandomSalt;
                string encryptedPasswordInDatabase = userDetails.EcryptedPassword;
                string applicationSecretSolt       = this._config["Jwt:ExtraApplicationPasswordsEncryptionInAdditionToRandomSalts"];

                bool arePasswordsEqualAfterHashAndEncryptions = CryptographyProcessor.ArePasswordsEqual(loginDetailsRequest.Password,
                                                                                                        encryptedPasswordInDatabase,
                                                                                                        passwordSaltInDatabase,
                                                                                                        applicationSecretSolt);

                if (!arePasswordsEqualAfterHashAndEncryptions)
                {
                    // Authentication failed! return "null" for current userDetails so Jwt token will not be created
                    userDetails = null;
                    userDetailsToReturnForAuthentication = null;
                }
                else
                {
                    // Authentication passed successfully -- return the current userDetails for Jwt token generation
                    userDetailsToReturnForAuthentication = userDetails;
                }
            }

            return(userDetailsToReturnForAuthentication);
        }
예제 #6
0
        public async Task <IActionResult> Login([FromBody] LogInForm model)
        {
            if (!ModelState.IsValid || model == null)
            {
                return(BadRequest(ModelState));
            }

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

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

            var salt = user.Salt;

            var passHash = user.PassHash;

            var cryptoProvider = new CryptographyProcessor();

            if (!cryptoProvider.AreEqual(model.Password, passHash, salt))
            {
                return(BadRequest(ControllerErrorCode.AccountOrPasswordWrong));
            }

            if (!user.IsConfirmed)
            {
                return(BadRequest(ControllerErrorCode.NotConfirmed));
            }

            var token = await _token.GetTokenAsync(user);

            return(Ok(token));
        }
예제 #7
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);
        }
예제 #9
0
        private void buttonLogin_Click(object sender, EventArgs e)
        {
            if (errorProvider1.GetError(loginInput) == "" &&
                errorProvider1.GetError(passwordInput) == "" &&
                loginInput.Text.Trim() != "" &&
                passwordInput.Text.Trim() != "")
            {
                Employee currentUser = hospitalStructure.Employees.
                                       Where(user => user.Login == loginInput.Text).
                                       FirstOrDefault();

                if (currentUser == null)
                {
                    MessageBox.Show(
                        "No user found with given login.", "Something went wrong...",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return;
                }

                if (currentUser.IsBanned())
                {
                    MessageBox.Show(
                        "You are banned!",
                        "Something went wrong...",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return;
                }

                if (CryptographyProcessor.AreEqual(passwordInput.Text, currentUser.Password, currentUser.Salt))
                {
                    var t = new Thread(() => Application.Run(new Main(currentUser, hospitalStructure)));
                    t.Start();

                    Thread.Sleep(50);
                    this.Close();
                }
                else
                {
                    MessageBox.Show(
                        "Password is wrong! Please try again!",
                        "Something went wrong...",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }
            }
        }
예제 #10
0
        /// <summary>
        /// Check user method to verify if such a user exists
        /// </summary>
        /// <param name="model">User login model</param>
        /// <returns>true/false if user found/not found</returns>
        public async Task <bool> CheckUser(UserLoginModel model)
        {
            var user = await _unitOfWork.UserRepository.FindOneAsync(u => u.Email == model.Email);

            if (user == null)
            {
                throw new ArgumentException($"User with Email: {model.Email} doesn't exists");
            }

            if (!CryptographyProcessor.AreEqual(model.Password, user.PasswordHash, user.Salt))
            {
                throw new ArgumentException("You have entered an invalid password");
            }

            return(true);
        }
예제 #11
0
        public async Task <IActionResult> CreateAccount(string email, string pass, UserRoles userRole)
        {
            if (_dbContext.Users.Any(user => user.Email.ToLower() == email.ToLower()))
            {
                return(BadRequest("User with such email already exists"));
            }

            //if requested creation of admins then checking rights
            if (userRole == UserRoles.Admin)
            {
                if (User.FindFirst("AccessLevel")?.Value != UserRoles.SuperAdmin.ToString())
                {
                    return(Unauthorized("you have to be  SuperAdmin to create other admins"));
                }
            }

            if (userRole == UserRoles.SiteAdmin)
            {
                if (User.FindFirst("AccessLevel")?.Value != UserRoles.Admin.ToString() &&
                    User.FindFirst("AccessLevel")?.Value != UserRoles.SuperAdmin.ToString())
                {
                    return(Unauthorized("you have to be Admin or superAdmin to create site admins"));
                }
            }

            //generate pass
            //todo: in prod make pass stronger
            // var pass = Guid.NewGuid().ToString("n").Substring(0, 3);
            var computedHash = CryptographyProcessor.Hash(pass);

            //send email
            //  var res = await _mailService.SendRegistrationMail(email, pass);

            var usr = new User()
            {
                Email        = email,
                PasswordHash = computedHash,
                UserRole     = userRole
            };

            _dbContext.Users.Add(usr);
            _dbContext.SaveChanges();

            return(Ok(usr));
        }
예제 #12
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));
        }
예제 #13
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());
        }
예제 #14
0
 public async Task <IActionResult> GetHash(string password)
 {
     return(Ok(CryptographyProcessor.Hash(password)));
 }
        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();
                }
            }
        }