예제 #1
0
 public int ChangePassword(Doctor doctor, string oldPassword, string newPassword, string newPasswordRepeat)
 {
     if (!string.IsNullOrEmpty(oldPassword) && !string.IsNullOrWhiteSpace(oldPassword) && !string.IsNullOrEmpty(newPassword) && !string.IsNullOrWhiteSpace(newPassword) && !string.IsNullOrEmpty(newPasswordRepeat) && !string.IsNullOrWhiteSpace(newPasswordRepeat) && doctor != null)
     {
         if (doctor.Password == PasswordCrypto.EncryptToSha512(oldPassword))
         {
             if (newPassword == newPasswordRepeat)
             {
                 using (RepositoryDoctor repositoryDoctor = new RepositoryDoctor())
                 {
                     doctor.Password = PasswordCrypto.EncryptToSha512(newPassword);
                     repositoryDoctor.CUDOperation(doctor, EntityState.Modified);
                     return(repositoryDoctor.SaveChanges());
                 }
             }
             else
             {
                 return(-4);
             }
         }
         else
         {
             return(-3);
         }
     }
     else
     {
         return(-1);
     }
 }
예제 #2
0
        private bool ValidateUserPassword(User user, string passWord)
        {
            //newly created user is entering the system first time
            if (user.CreateDate.Equals(user.PasswordUpdateDate))
            {
                //is timed out?
                if (user.PasswordUpdateDate.AddHours(1) < DateTime.Now)
                {
                    throw new PasswordExpiredException();
                }
            }

            if (user.PasswordHash.Equals(PasswordCrypto.EncryptUserPassword(user.UserName, passWord)))
            {
                //update successfull attempt
                user.LastSuccessAttempt  = DateTime.Now;
                user.InvalidAttemptCount = 0;

                UserDao.Update(user);

                return(true);
            }
            else
            {
                //update invalid attempt
                user.LastInvalidAttempt   = DateTime.Now;
                user.InvalidAttemptCount += 1;

                UserDao.Update(user);

                throw new InvalidPasswordException();
            }
        }
예제 #3
0
        public VoidOperationContract ResetPassword(ResetPasswordContract contract)
        {
            try
            {
                using (NeedAGolferDataContext dataContext = new NeedAGolferDataContext())
                {
                    var golferRetriever = RetrieverFactory.CreateInterface <IGolferRetriever>();
                    var golfer          = golferRetriever.SelectByUsernameAndEmail(contract.UserAccount, contract.EmailAddress);

                    string salt           = PasswordCrypto.GetSalt();
                    string hashedPassword = PasswordCrypto.ComputeHash(contract.Password, "SHA256", salt);
                    golfer.PasswordHash = hashedPassword;
                    golfer.PasswordSalt = salt;

                    dataContext.Golfers.Attach(golfer, true);
                    dataContext.SubmitChanges();
                    dataContext.Connection.Close();

                    return(new VoidOperationContract()
                    {
                        ErrorMessage = ""
                    });
                }
            }
            catch (Exception ex)
            {
                return(new VoidOperationContract()
                {
                    ErrorMessage = ex.Message
                });
            }
        }
예제 #4
0
 public Doctor DoctorLogIn(string userName, string password)
 {
     using (RepositoryDoctor repositoryDoctor = new RepositoryDoctor())
     {
         string encryptedPassword = PasswordCrypto.EncryptToSha512(password);
         return(repositoryDoctor.FirstWithExplicitLoad(I => I.Ssn == userName && I.Password == encryptedPassword && I.IsActive == true));
     }
 }
예제 #5
0
 public Admin AdminLogIn(string userName, string password)
 {
     using (RepositoryAdmin repositoryAdmin = new RepositoryAdmin())
     {
         string encryptedPassword = PasswordCrypto.EncryptToSha512(password);
         return(repositoryAdmin.FirstWithExplicitLoad(I => I.UserName == userName && I.Password == encryptedPassword));
     }
 }
예제 #6
0
        private static PasswordCrypto EncryptPassword(string password)
        {
            ICryptoService cryptoService = new PBKDF2();
            var            crypto        = new PasswordCrypto();

            crypto.Salt     = cryptoService.GenerateSalt();
            crypto.Password = cryptoService.Compute(password);
            return(crypto);
        }
예제 #7
0
 public int ForgotPassword(string ssn, string name, string surname, string phone, string mail, DateTime birthday, string newPassword, string newPasswordRepeat)
 {
     if (!string.IsNullOrEmpty(ssn) && !string.IsNullOrWhiteSpace(ssn) && !string.IsNullOrEmpty(name) && !string.IsNullOrWhiteSpace(name) && !string.IsNullOrEmpty(surname) && !string.IsNullOrWhiteSpace(surname) && !string.IsNullOrEmpty(newPassword) && !string.IsNullOrWhiteSpace(newPassword) && !string.IsNullOrEmpty(newPasswordRepeat) && !string.IsNullOrWhiteSpace(newPasswordRepeat) && birthday != null)
     {
         string tempPhone;
         string tempMail;
         if (string.IsNullOrEmpty(phone.Trim()))
         {
             tempPhone = null;
         }
         else
         {
             tempPhone = phone;
         }
         if (string.IsNullOrEmpty(mail.Trim()))
         {
             tempMail = null;
         }
         else
         {
             tempMail = mail;
         }
         using (RepositoryMember repositoryMember = new RepositoryMember())
         {
             Member member = repositoryMember.FirstWithExplicitLoad(I => I.Ssn == ssn);
             if (member != null)
             {
                 if (member.Name == BLLHelper.TrimName(name) && member.Surname == BLLHelper.TrimSurname(surname) && member.Phone == tempPhone && member.Mail == tempMail && member.Birthday.ToString("dd.MM.yyyy") == birthday.ToString("dd.MM.yyyy"))
                 {
                     if (newPassword == newPasswordRepeat)
                     {
                         member.Password = PasswordCrypto.EncryptToSha512(newPassword);
                         repositoryMember.CUDOperation(member, EntityState.Modified);
                         return(repositoryMember.SaveChanges());
                     }
                     else
                     {
                         return(-4);
                     }
                 }
                 else
                 {
                     return(-6);
                 }
             }
             else
             {
                 return(-5);
             }
         }
     }
     else
     {
         return(-1);
     }
 }
예제 #8
0
 public int AdminNewRecord(string userName)
 {
     using (RepositoryAdmin repositoryAdmin = new RepositoryAdmin())
     {
         repositoryAdmin.CUDOperation(new Admin()
         {
             Id       = Guid.NewGuid(),
             UserName = userName,
             Password = PasswordCrypto.EncryptToSha512("demo")
         }, EntityState.Added);
         return(repositoryAdmin.SaveChanges());
     }
 }
예제 #9
0
        private void addNewUser()
        {
            User createdUser = new User(tbLogin.Text, tbName.Text, PasswordCrypto.Encrypt(tbPass.Text));

            createdUser = userService.CreateUser(createdUser);
            if (createdUser != null && createdUser.Id > 0)
            {
                MessageBox.Show("Utworzono użytkownika " + tbLogin.Text, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Close();
            }
            else
            {
                Application.Exit();
            }
        }
예제 #10
0
        private string GetHashedPassword(string username, string password)
        {
            var saltQueryable = from golfer in dataContext.Golfers
                                where (golfer.ScreenName == username)
                                select golfer.PasswordSalt;

            if (saltQueryable.Count() == 0)
            {
                return(string.Empty);
            }
            string salt           = saltQueryable.FirstOrDefault();
            string hashedPassword = PasswordCrypto.ComputeHash(password, "SHA256", salt);

            return(hashedPassword);
        }
예제 #11
0
 public int ResetAdminPassword(Admin admin, string password)
 {
     if (admin != null && !string.IsNullOrEmpty(password) && !string.IsNullOrWhiteSpace(password))
     {
         using (RepositoryAdmin repositoryAdmin = new RepositoryAdmin())
         {
             admin.Password = PasswordCrypto.EncryptToSha512(password);
             repositoryAdmin.CUDOperation(admin, EntityState.Modified);
             return(repositoryAdmin.SaveChanges());
         }
     }
     else
     {
         return(-1);
     }
 }
예제 #12
0
 public int ResetDoctorPassword(Doctor doctor, string password)
 {
     if (doctor != null && !string.IsNullOrEmpty(password) && !string.IsNullOrWhiteSpace(password))
     {
         using (RepositoryDoctor repositoryDoctor = new RepositoryDoctor())
         {
             doctor.Password = PasswordCrypto.EncryptToSha512(password);
             repositoryDoctor.CUDOperation(doctor, EntityState.Modified);
             return(repositoryDoctor.SaveChanges());
         }
     }
     else
     {
         return(-1);
     }
 }
예제 #13
0
        public VoidOperationContract CreateGolfer(CreateGolferContract createContract)
        {
            VoidOperationContract contract = new VoidOperationContract();

            try
            {
                using (NeedAGolferDataContext dataContext = new NeedAGolferDataContext())
                {
                    var existing = from golfers in dataContext.Golfers
                                   where (golfers.ScreenName == createContract.Name || golfers.EmailAddress == createContract.EmailAddress)
                                   select golfers;

                    if (existing.Count() == 0)
                    {
                        Golfer golfer = new Golfer();
                        golfer.EmailAddress         = createContract.EmailAddress;
                        golfer.AllowEmails          = false;
                        golfer.PhoneNumber          = createContract.PhoneNumber;
                        golfer.IsAvailable          = true;
                        golfer.Handicap             = createContract.Handicap;
                        golfer.Latitude             = createContract.Latitude;
                        golfer.Longitude            = createContract.Longitude;
                        golfer.LastUpdated          = DateTime.Now;
                        golfer.ScreenName           = createContract.Name;
                        golfer.AvailabilityDistance = createContract.AvailabilityDistanceInMiles;

                        string salt           = PasswordCrypto.GetSalt();
                        string hashedPassword = PasswordCrypto.ComputeHash(createContract.Password, "SHA256", salt);
                        golfer.PasswordHash = hashedPassword;
                        golfer.PasswordSalt = salt;

                        dataContext.Golfers.InsertOnSubmit(golfer);
                        dataContext.SubmitChanges();
                        dataContext.Connection.Close();
                    }
                    else
                    {
                        contract.ErrorMessage = "There is already a user registered with this screen name or email address.  Please try again.";
                    }
                }
            }
            catch (Exception ex)
            {
                contract.ErrorMessage = ex.Message;
            }
            return(contract);
        }
예제 #14
0
        static void Main(string[] args)
        {
            IConfiguration       config         = GetConfiguration();
            ISqlDbAccess         db             = new SqliteDbAccess(config);
            IPasswordCrypto      crypto         = new PasswordCrypto();
            SqliteUserService    userService    = new SqliteUserService(db, crypto);
            SqliteMessageService messageService = new SqliteMessageService(db);
            UserInputValidator   validator      = new UserInputValidator();
            LoginRoutine         loginRoutine   = new LoginRoutine(userService, validator);


            //Console.WriteLine("Logging in");
            //Console.Write("username: "******"Your password: "******"Signing up result: { confirmed }");
            //Console.ReadLine();


            //MessageRoutine messageRoutine = new MessageRoutine(messageService, userService);

            ////MessageModel message = new MessageModel()
            ////{
            ////    Message = "This is the first message.",
            ////    FromUserId = 1
            ////};

            ////messageRoutine.SendMessage(message, "juusvali");

            //List<MessageFullModel> newMessages = messageRoutine.GetNewMessages(2);

            //foreach (var item in newMessages)
            //{
            //    Console.WriteLine($"To: { item.ToUserId }, from: { item.UserName }");
            //    Console.WriteLine(item.Message);
            //}
        }
예제 #15
0
        public User Login(User user)
        {
            var userFromDb = new User();

            using (var session = NHibernateHelper.OpenSession())
            {
                userFromDb = session.Query <User>()
                             .Where(u => u.Login == user.Login)
                             .FirstOrDefault <User>();

                if (userFromDb == null)
                {
                    return(userFromDb);
                }
                else
                {
                    if (PasswordCrypto.Decrypt(userFromDb.Password).Equals(user.Password))
                    {
                        userFromDb.isLogged = true;
                    }
                }
            }
            return(userFromDb);
        }
예제 #16
0
        public int MemberRegister(MemberEnumGender gender, string ssn, string password, string name, string surname, string phone, string mail, DateTime birthday)
        {
            int returnValueInt = 0;

            if (!string.IsNullOrEmpty(ssn) && !string.IsNullOrWhiteSpace(ssn) && !string.IsNullOrEmpty(password) && !string.IsNullOrWhiteSpace(password) && !string.IsNullOrEmpty(name) && !string.IsNullOrWhiteSpace(name) && !string.IsNullOrEmpty(surname) && !string.IsNullOrWhiteSpace(surname) && ssn.Length == 11 && birthday != null)
            {
                string tempPhone;
                string tempMail;
                if (string.IsNullOrEmpty(phone.Trim()))
                {
                    tempPhone = null;
                }
                else
                {
                    tempPhone = phone;
                }
                if (string.IsNullOrEmpty(mail.Trim()))
                {
                    tempMail = null;
                }
                else
                {
                    tempMail = mail;
                }
                using (RepositoryMember repositoryMember = new RepositoryMember())
                {
                    if (!repositoryMember.AnyWithExplicitLoad(I => I.Ssn == ssn))
                    {
                        if (!repositoryMember.AnyWithExplicitLoad(I => I.Phone == phone))
                        {
                            if (!repositoryMember.AnyWithExplicitLoad(I => I.Mail == mail))
                            {
                                repositoryMember.CUDOperation(new Member()
                                {
                                    Id       = Guid.NewGuid(),
                                    Ssn      = ssn,
                                    Name     = BLLHelper.TrimName(name),
                                    Surname  = BLLHelper.TrimSurname(surname),
                                    Gender   = gender,
                                    Birthday = birthday,
                                    Phone    = tempPhone,
                                    Mail     = tempMail,
                                    Password = PasswordCrypto.EncryptToSha512(password),
                                    Picture  = BLLHelper.DefaultUserPic()
                                }, EntityState.Added);
                                returnValueInt = repositoryMember.SaveChanges();
                            }
                            else
                            {
                                returnValueInt = -102;
                            }
                        }
                        else
                        {
                            returnValueInt = -101;
                        }
                    }
                    else
                    {
                        returnValueInt = -100;
                    }
                }
            }
            else
            {
                returnValueInt = -1;
            }
            return(returnValueInt);
        }
예제 #17
0
 private void HashPassword(User user, string passWord)
 {
     user.PasswordHash        = PasswordCrypto.EncryptUserPassword(user.UserName, passWord);
     user.InvalidAttemptCount = 0;
     user.PasswordUpdateDate  = DateTime.Now;
 }
예제 #18
0
      static void Main(string[] args)
      {
          /* Add main Pivet assembly */
          LoadedAssemblies.Add(Assembly.GetExecutingAssembly());
          /* Load any plugin DLLs */
          if (Directory.Exists("plugins"))
          {
              DirectoryInfo dir = new DirectoryInfo("plugins");

              foreach (FileInfo file in dir.GetFiles("*.dll"))
              {
                  Logger.Write("Loaded plugin: " + file.Name);
                  Assembly assembly = Assembly.LoadFrom(file.FullName);

                  if (assembly.GetTypes().Where(p => (typeof(IDataProcessor).IsAssignableFrom(p) && !p.IsInterface && !p.IsAbstract)).Count() > 0)
                  {
                      LoadedAssemblies.Add(assembly);
                  }
              }
          }
          /* by default no custom commit message */
          CustomCommitMessage = "";

          var configFile          = "config.json";
          var jobToRun            = "";
          var wantsBuilder        = false;
          var passwordEncryptMode = false;

          ShowProgress = false;

          if (args.Contains("-e"))
          {
              passwordEncryptMode = true;
          }

          if (args.Length > 1)
          {
              for (var x = 0; x < args.Length - 1; x++)
              {
                  if (args[x].ToLower().Equals("-c"))
                  {
                      configFile = args[x + 1];
                      x++;
                  }
                  if (args[x].ToLower().Equals("-j"))
                  {
                      jobToRun = args[x + 1];
                      x++;
                  }
                  if (args[x].ToLower().Equals("-b"))
                  {
                      wantsBuilder = true;
                  }
                  if (args[x].ToLower().Equals("-v"))
                  {
                      ShowProgress = true;
                  }
                  if (args[x].ToLower().Equals("-m"))
                  {
                      CustomCommitMessage = args[x + 1];
                      x++;
                  }
              }
          }
          else if (args.Length == 1)
          {
              if (args[0].ToLower().Equals("-b"))
              {
                  wantsBuilder = true;
              }
              if (args[0].ToLower().Equals("-v"))
              {
                  ShowProgress = true;
              }
          }

          if (passwordEncryptMode)
          {
              bool   passwordMatch = false;
              string pass          = "";
              while (passwordMatch == false)
              {
                  Console.Write("Enter the password you want to encrypt: ");
                  pass = ReadPassword('*');
                  Console.Write("Please confirm the password: "******"Passwords did not match. Please try again.");
                  }
              }

              Console.WriteLine("Encrypted: " + PasswordCrypto.EncryptPassword(pass));
              return;
          }

          if (File.Exists(configFile) == false)
          {
              if (wantsBuilder)
              {
                  configFile = ConfigBuilder.RunBuilder();
              }

              if (configFile == "")
              {
                  Logger.Error("Pivet cannot run without a configuration file.");
                  return;
              }
          }
          else
          {
              if (wantsBuilder)
              {
                  Console.Write("Found an existing config file, would you like to modify it? (y/n)");
                  if (Console.ReadLine() == "y")
                  {
                      configFile = ConfigBuilder.RunBuilder(configFile);
                  }
              }
          }

          string j = File.ReadAllText(configFile);

          try
          {
              GlobalConfig = JsonConvert.DeserializeObject <Config>(j);
          }
          catch (Exception ex)
          {
              Logger.Error("Failed to parse config.json, please validate all required fields are present.");
              Logger.Error(ex.ToString());
              Console.ReadKey();
              return;
          }

          Logger.Write($"Config loaded. {GlobalConfig.Environments.Count} Environment(s) found, {GlobalConfig.Profiles.Count} Profile(s) found.");

          foreach (var job in GlobalConfig.Jobs)
          {
              if (jobToRun.Length > 0)
              {
                  if (job.Name.Equals(jobToRun))
                  {
                      EnvironmentConfig environment = GlobalConfig.Environments.Where(e => e.Name.Equals(job.EnvironmentName)).FirstOrDefault();
                      if (environment == null)
                      {
                          Logger.Error($"Could not run profile '{jobToRun}', unable to find environment named '{job.EnvironmentName}'");
                          return;
                      }
                      else
                      {
                          JobRunner.Run(GlobalConfig, job);
                      }
                  }
              }
              else
              {
                  EnvironmentConfig environment = GlobalConfig.Environments.Where(e => e.Name.Equals(job.EnvironmentName)).FirstOrDefault();
                  if (environment == null)
                  {
                      Logger.Error($"Could not run profile '{jobToRun}', unable to find environment named '{job.EnvironmentName}'");
                  }
                  else
                  {
                      JobRunner.Run(GlobalConfig, job);
                  }
              }
          }
          Logger.Write("All done!");
      }
예제 #19
0
 public int DoctorNewRecord(Hospital hospital, string ssn, string appellation, string expertise, string ageRange, string name, string surname, DateTime birthday, string phone, string mail, string city, string county)
 {
     if (!string.IsNullOrEmpty(ssn) && !string.IsNullOrWhiteSpace(ssn) && ssn.Length == 11 && !string.IsNullOrEmpty(appellation) && !string.IsNullOrWhiteSpace(appellation) && !string.IsNullOrEmpty(expertise) && !string.IsNullOrWhiteSpace(expertise) && !string.IsNullOrEmpty(ageRange) && !string.IsNullOrWhiteSpace(ageRange) && !string.IsNullOrEmpty(surname) && !string.IsNullOrWhiteSpace(surname) && !string.IsNullOrEmpty(name) && !string.IsNullOrWhiteSpace(name) && birthday != null && hospital != null)
     {
         string tempPhone;
         string tempMail;
         string tempCity;
         string tempCounty;
         if (string.IsNullOrEmpty(phone.Trim()))
         {
             tempPhone = null;
         }
         else
         {
             tempPhone = phone;
         }
         if (string.IsNullOrEmpty(mail.Trim()))
         {
             tempMail = null;
         }
         else
         {
             tempMail = mail;
         }
         if (string.IsNullOrEmpty(city.Trim()))
         {
             tempCity = null;
         }
         else
         {
             tempCity = city;
         }
         if (string.IsNullOrEmpty(county.Trim()))
         {
             tempCounty = null;
         }
         else
         {
             tempCounty = county;
         }
         using (RepositoryDoctor repositoryDoctor = new RepositoryDoctor())
         {
             if (!repositoryDoctor.AnyWithExplicitLoad(I => I.Ssn == ssn))
             {
                 if (!repositoryDoctor.AnyWithExplicitLoad(I => I.Phone == phone))
                 {
                     if (!repositoryDoctor.AnyWithExplicitLoad(I => I.Mail == mail))
                     {
                         Doctor doctor = new Doctor()
                         {
                             Id          = Guid.NewGuid(),
                             Ssn         = ssn,
                             Appellation = BLLHelper.GetEnumValueFromDescription <DoctorEnumAppellation>(appellation),
                             Expertise   = BLLHelper.GetEnumValueFromDescription <DoctorEnumExpertise>(expertise),
                             AgeRange    = BLLHelper.GetEnumValueFromDescription <DoctorEnumAgeRange>(ageRange),
                             Name        = BLLHelper.TrimName(name),
                             Surname     = BLLHelper.TrimSurname(surname),
                             Birthday    = birthday,
                             Phone       = tempPhone,
                             Mail        = tempMail,
                             City        = tempCity,
                             County      = tempCounty,
                             Picture     = BLLHelper.DefaultDoctorPic(),
                             Password    = PasswordCrypto.EncryptToSha512(ssn),
                             UpdateTime  = DateTime.Now,
                             HospitalId  = hospital.Id
                         };
                         repositoryDoctor.CUDOperation(doctor, EntityState.Added);
                         return(repositoryDoctor.SaveChanges());
                     }
                     else
                     {
                         return(-112);
                     }
                 }
                 else
                 {
                     return(-111);
                 }
             }
             else
             {
                 return(-110);
             }
         }
     }
     else
     {
         return(-1);
     }
 }