예제 #1
0
        public AuthService(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            salt = BCryptHelper.GenerateSalt();

            var applicationUser = new ApplicationUser()
            {
                Id           = 1,
                Email        = "*****@*****.**",
                UserName     = "******",
                FirstName    = "mayur",
                LastName     = "agarwal",
                PasswordHash = BCryptHelper.HashPassword("password", salt)
            };

            var testApplicationUser = new ApplicationUser()
            {
                Id           = 2,
                Email        = "*****@*****.**",
                UserName     = "******",
                FirstName    = "test",
                LastName     = "test",
                PasswordHash = BCryptHelper.HashPassword("test", salt)
            };

            _applicationUsers = new Dictionary <string, ApplicationUser>()
            {
                { "mayur", applicationUser },
                { "test", testApplicationUser }
            };
        }
        public KeyValuePair <string, string> GenerateHashAndSalt(string plainText)
        {
            var salt = GenerateSaltForHash();
            var hash = BCryptHelper.HashPassword(plainText, salt);

            return(new KeyValuePair <string, string>(hash, salt));
        }
예제 #3
0
        public async Task <ActionResult> Register(User model)
        {
            var checkEmail = _userRepository.GetByEmail(model.Email);

            if (checkEmail != null)
            {
                return(BadRequest("Email already taken!"));
            }
            else
            {
                User user = new User();

                var mypass = model.Password;
                var mysalt = BCryptHelper.GenerateSalt(12);

                user.Email    = model.Email;
                user.Password = BCryptHelper.HashPassword(mypass, mysalt);

                var result = await _userRepository.PostAsync(user);

                if (result != null)
                {
                    await _roleRepository.InsertUserRole(user.Id, 2);

                    return(Ok("Register Success!"));
                }
                else
                {
                    return(BadRequest("Failed to register"));
                }
            }
        }
예제 #4
0
        // Ovde ubaciti Session za atribut umjesto ovih zajebancija ...
        public string GenerateSessionKey(Session session, string key)//string username, string key, string useragent, string ip, Datet)
        {
            // randomly generated key will be hashed with user's current password's salt
            User user = context.Users.FirstOrDefault(u => u.Username == session.User.Username);

            if (user.Sessions.Any(u => u.UserAgent == session.UserAgent && u.IP == session.IP && u.Key != null && u.Authorised))
            {
                return(null);
            }
            else
            {
                string salt      = user.Salt;
                string encrypted = BCryptHelper.HashPassword(key, salt).Remove(0, salt.Length);

                if (session.User.Remember)
                {
                    session.Expires = DateTime.Now.AddMonths(12);
                }

                session.User = user;
                session.Key  = encrypted;

                context.Sessions.Add(session);
                context.SaveChanges();

                context.Entry(user).State = EntityState.Modified;
                context.Users.Attach(user);
                user.Sessions.Add(session);

                context.SaveChanges();

                return(encrypted);
            }
        }
        public static bool Register(this SqlConnection connection, User user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (connection.IsUnique(user))
            {
                var sqlQuery = @"INSERT INTO [User] (Id, Nickname, Password, StatusId, LastAvailable, RegistrationDate) 
                             VALUES (@Id, @Nickname, @Password, @StatusId, @LastAvailable, @RegistrationDate)";

                DynamicParameters parameter = new DynamicParameters();

                parameter.Add("@Id", user.Id);
                parameter.Add("@Nickname", user.Nickname);

                string salt           = BCryptHelper.GenerateSalt();
                string hashedPassword = BCryptHelper.HashPassword(user.Password, salt);

                parameter.Add("@Password", hashedPassword);
                parameter.Add("@StatusId", user.StatusId);
                parameter.Add("@LastAvailable", user.LastAvailable);
                parameter.Add("@RegistrationDate", user.RegistrationDate);

                connection.Query(sqlQuery, parameter);

                return(true);
            }

            return(false);
        }
예제 #6
0
        public Login()
        {
            InitializeComponent();

            StartPosition = FormStartPosition.CenterScreen;
            AcceptButton  = btnLogin;

            DefaultPokemonService = new Pokemon.PokemonService();
            string path = Path.Combine(Application.UserAppDataPath, "\\accounts.json");

            try
            {
                string json = System.IO.File.ReadAllText(path);
                DefaultAccountService = JsonConvert.DeserializeObject <AccountService>(json);
            }
            catch (Exception e)
            {
                DefaultAccountService = new AccountService();
            }

            DefaultAccounts[0] = new Account("admin", BCryptHelper.HashPassword("admin", BCryptHelper.GenerateSalt()));

            foreach (Account a in DefaultAccounts)
            {
                if (a != null)
                {
                    DefaultAccountService.createAccount(a.Username, a);
                }
            }
        }
예제 #7
0
        private string HashPassword(string password)
        {
            var salt           = BCryptHelper.GenerateSalt();
            var hashedPassword = BCryptHelper.HashPassword(password, salt);

            return(hashedPassword);
        }
예제 #8
0
 public PlayerInfo(string username, string vorname, string nachname, string password, bool loggedin)
 {
     this.username = username;
     this.vorname  = vorname;
     this.nachname = nachname;
     this.password = BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt());
 }
예제 #9
0
 public void Event_Register(Client client, string login, string email, string password)
 {
     Task.Factory.StartNew(() =>
     {
         try
         {
             if (!Database.ReturnEmail(email))
             {
                 string dbpassword = BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt());
                 Database.RegisterAccount(login, dbpassword, email, client.Address);
                 client.TriggerEvent("RegisterResultTrue");
             }
             else
             {
                 NAPI.Util.ConsoleOutput("не рег");
                 client.TriggerEvent("RegisterResultFalse");
             }
         }
         catch (Exception ex)
         {
             Globals.log.Trace(ex);
             NAPI.Util.ConsoleOutput("[EXCEPTION CreateCharacter] " + ex.Message);
             NAPI.Util.ConsoleOutput("[EXCEPTION CreateCharacter] " + ex.StackTrace);
         }
     });
 }
        public async Task <IActionResult> OnPostAsync()
        {
            if (string.IsNullOrEmpty(Input.NewPassword))
            {
                Input.NewPassword     = IdentityUserDefaultPwd.DefaultPassword;
                Input.ConfirmPassword = IdentityUserDefaultPwd.DefaultPassword;
            }

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Ne peut pas charger le num's '{_userManager.GetUserId(User)}'."));
            }

            var changePasswordResult =
                await _userManager.ChangePasswordAsync(user, Input.OldPassword.ToLower(), Input.NewPassword.ToLower());

            if (!changePasswordResult.Succeeded)
            {
                foreach (var error in changePasswordResult.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
                return(Page());
            }

            // Si impossible de trouver l'utilisateur dans la BDD UserData, on annule le changement de mdp
            var userData = _context.UserData.Find(user.UserName);

            if (userData == null)
            {
                changePasswordResult =
                    await _userManager.ChangePasswordAsync(user, Input.NewPassword.ToLower(), Input.OldPassword.ToLower());

                ModelState.AddModelError(string.Empty, "Impossible de trouver l'utilisateur dans la BDD UserData.");
                foreach (var error in changePasswordResult.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
                return(Page());
            }

            userData.FoysApiHasPassword = Input.NewPassword.ToLower() != IdentityUserDefaultPwd.DefaultPassword;

            userData.DateDerniereModif      = DateTime.Now;
            userData.FoysApiPasswordSalt    = BCryptHelper.GenerateSalt();
            userData.FoysApiPasswordHash    = BCryptHelper.HashPassword(Input.NewPassword.ToLower(), userData.FoysApiPasswordSalt);
            _context.Attach(userData).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            await _signInManager.RefreshSignInAsync(user);

            return(Redirect("/pg"));
        }
예제 #11
0
        public Register(string userName, string password)
        {
            string salt = BCryptHelper.GenerateSalt();

            _passwordHash = BCryptHelper.HashPassword(password, salt);
            _userName     = userName;
        }
예제 #12
0
 public IHttpActionResult Register(RegisterRequest register)
 {
     try
     {
         if (!ModelState.IsValid)
         {
             return(BadRequest(ModelState));
         }
         //student info
         var student = new StudentModel()
         {
             Email            = register.Email,
             FirstName        = register.FirstName,
             LastName         = register.LastName,
             PhoneNumber      = register.PhoneNumber,
             DateOfBirth      = register.DateOfBirth,
             EducationEndDate = register.EducationEndDate,
             Nationality      = register.Nationality
         };
         //password hash
         string mySalt         = BCryptHelper.GenerateSalt();
         var    hashedPassword = BCryptHelper.HashPassword(register.Password, mySalt);
         var    result         = studentHandler.Create(student, hashedPassword);
         return(Ok("Success"));
     }
     catch (Exception)
     {
         return(Ok("Something went wrong"));
     }
 }
예제 #13
0
        public IActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if (model.NewPassword != model.ConfirmNewPassword)
            {
                ModelState.AddModelError("", "New Password does not match Confirm New Password");
                return(View());
            }


            var user = this._context.Users.FirstOrDefault(u =>
                                                          u.Id == model.UserId);

            if (user != null)
            {
                if (BCryptHelper.CheckPassword(model.OldPassword, user.Password) == false)
                {
                    ModelState.AddModelError("", "Incorrect old Password.");
                    return(View());
                }

                user.Password    = BCryptHelper.HashPassword(model.NewPassword, BCryptHelper.GenerateSalt(8));
                user.LoginStatus = Infrastructures.Domain.Enums.LoginStatus.Active;

                this._context.Users.Update(user);
                this._context.SaveChanges();

                return(RedirectPermanent("Notify"));
            }

            return(View());
        }
예제 #14
0
        public ActionResult Register(Users users)
        {
            try
            {
                string password       = users.Password;
                string salt           = BCryptHelper.GenerateSalt(7);
                string hashedPassword = BCryptHelper.HashPassword(password, salt);
                string verifyCode     = BCryptHelper.GenerateSalt(5);
                users.Password   = hashedPassword;
                users.Salt       = salt;
                users.Active     = 0;
                users.verifyCode = verifyCode;
                db.Users.Add(users);
                db.SaveChanges();

                TempData["Email"]      = users.Email;
                TempData["verifyCode"] = users.verifyCode;
                TempData["Action"]     = "Register";
                return(RedirectToAction("Email", "Account"));
            }
            catch
            {
                TempData["Type"]    = "Danger";
                TempData["Message"] = "Registration failed! Email already in use!";
                return(View());
            }
        }
예제 #15
0
        public async Task <IdentityResponse> RegisterAsync(Users user)
        {
            var checkEmail = await _context.Users
                             .FirstOrDefaultAsync(x => x.email == user.email);

            if (checkEmail != null)
            {
                return(new IdentityResponse
                {
                    errors = new[] { "email already exist." }
                });
            }
            var checkUsername = await _context.Users
                                .FirstOrDefaultAsync(x => x.username == user.username);

            if (checkUsername != null)
            {
                return(new IdentityResponse
                {
                    errors = new[] { "username already exist." }
                });
            }
            string salt = BCryptHelper.GenerateSalt(10);

            user.password = BCryptHelper.HashPassword(user.password, salt);

            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            return(GenerateAuthenticationResultForUser(user));
        }
예제 #16
0
        public bool AddNewCustomerAccount(CustomerAccount model)
        {
            string encryptedPassword = BCryptHelper.HashPassword(model.Password, BCryptHelper.GenerateSalt(6));

            model.Password = encryptedPassword;
            return(Repository.AddNewCustomerAccount(model));
        }
예제 #17
0
 public ActionResult Register(RegisterModel model)
 {
     if (model == null)
     {
         ViewBag.LoginError = "Hatalı kullanıcı adı ya da şifre!";
         return(RedirectToAction("Login"));
     }
     else
     {
         using (var ctx = new IFSAppContext())
         {
             var u = ctx.Users.Where(w => w.Username == model.Username).SingleOrDefault();
             if (u != null)
             {
                 ViewBag.RegisterError = "Kullanıcı adı mevcut";
                 return(RedirectToAction("Login"));
             }
             UserModel user = new UserModel()
             {
                 DefaultCityName = model.DefaultCityName,
                 Name            = model.Name,
                 Username        = model.Username,
                 Password        = BCryptHelper.HashPassword(model.Password, BCryptHelper.GenerateSalt(12)),
                 UserType        = "Son Kullanıcı",
                 Status          = 1,
             };
             ctx.Users.Add(user);
             ctx.SaveChanges();
             return(RedirectToAction("Login"));
         }
     }
 }
예제 #18
0
        private string EncodePassword(string password, MembershipPasswordFormat membershipPasswordFormat, string salt)
        {
            if (password == null)
            {
                return(null);
            }

            if (membershipPasswordFormat == MembershipPasswordFormat.Clear)
            {
                return(password);
            }

            if (membershipPasswordFormat == MembershipPasswordFormat.Hashed)
            {
                return(BCryptHelper.HashPassword(password, salt));
            }

            var passwordBytes = Encoding.Unicode.GetBytes(password);
            var saltBytes     = Convert.FromBase64String(salt);
            var allBytes      = new byte[saltBytes.Length + passwordBytes.Length];

            Buffer.BlockCopy(saltBytes, 0, allBytes, 0, saltBytes.Length);
            Buffer.BlockCopy(passwordBytes, 0, allBytes, saltBytes.Length, passwordBytes.Length);

            return(Convert.ToBase64String(EncryptPassword(allBytes)));
        }
예제 #19
0
        private void btnRegister_Click(object sender, EventArgs e)
        {
            String username = txtLogin.Text;
            String password = txtPassword.Text;

            txtLogin.Enabled    = false;
            txtPassword.Enabled = false;

            if (!String.IsNullOrWhiteSpace(username) || !String.IsNullOrWhiteSpace(password))
            {
                String  hashed  = BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt());
                Account account = new Account(username, hashed);

                if (!DefaultAccountService.createAccount(username, account))
                {
                    MessageBox.Show("Register failed, username taken.");
                }
                else
                {
                    MessageBox.Show("Register succeeded.");
                }
            }
            else
            {
                MessageBox.Show("Invalid inputs!");
            }

            txtLogin.Enabled    = true;
            txtPassword.Enabled = true;
            txtPassword.Clear();
        }
예제 #20
0
        public IActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = this._context.Users.FirstOrDefault(u => u.EmailAddress.ToLower() == model.EmailAddress.ToLower());

            if (user != null)
            {
                var newPassword = RandomString(9);
                user.Password    = BCryptHelper.HashPassword(newPassword, BCryptHelper.GenerateSalt(9));
                user.LoginStatus = Infrastructures.Domain.Enums.LoginStatus.Active;

                this._context.Users.Update(user);
                this._context.SaveChanges();

                this.EmailSendNow(
                    ForgotPasswordEmailTemplate(newPassword, user.UserName),
                    user.EmailAddress,
                    user.UserName,
                    "Fixit.ph Website - Forgot Password"
                    );

                return(RedirectToAction("OTP"));
            }
            ModelState.AddModelError("", "Email-Address does'nt exist!");
            return(View(model));
        }
예제 #21
0
        public void CreateUser(User user, Role role)
        {
            if (context.Users.Count() == 0 && context.Roles.Count() == 0)
            {
                // no need explaining why I use bcrypt
                // but in case you wonder, this is just the thread you need - https://news.ycombinator.com/item?id=4073477
                string salt = BCryptHelper.GenerateSalt(10);
                user.Password = BCryptHelper.HashPassword(user.Password, salt);
                user.Salt     = salt;

                context.Roles.Add(role);
                context.Users.Add(user);
                context.SaveChanges();

                context.Users.Attach(user);
                context.Roles.FirstOrDefault(u => u.Name == role.Name).Users.Add(user);

                Profile profile = new Profile {
                    Name = context.Blogs.FirstOrDefault().Name, User = user
                };


                context.Profiles.Add(profile);
                context.SaveChanges();
            }
            else
            {
                throw new Exception("It seems that you've already registred master user for this instance.");//"User named " + user.Username + " is already here.");
            }
        }
예제 #22
0
        public static void Main(string[] args)
        {
            // Pasre command line args to config on startup
            var argConf = new ConfigurationBuilder()
                          .AddCommandLine(args)
                          .Build();

            // If config includes 'generateKeyHash', the program will
            // generate a hash of the passed key based on the passed
            // parameters and then exit the program with 0 without
            // actually starting the web server.
            if (argConf["generateKeyHash"] != null)
            {
                var rounds = argConf.GetValue <int>("hashRounds");
                rounds = rounds > 0 ? rounds : 12;

                var salt = BCryptHelper.GenerateSalt(rounds);

                Console.WriteLine(
                    "Generating Hash of passed keyword...\n\n" +
                    $"Hash Rounds:     {rounds}\n" +
                    $"Using Salt:      {salt}");

                var hash = BCryptHelper.HashPassword(argConf["generateKeyHash"], salt);

                Console.WriteLine($"Generated Hash:  ${hash}");

                return;
            }

            // Start the web server
            CreateWebHostBuilder(args).Build().Run();
        }
예제 #23
0
        public IActionResult ResetPassword(Guid?userId)
        {
            var user = this._context.Users.FirstOrDefault(u => u.Id == userId);

            if (user != null)
            {
                var password = RandomString(8);

                user.Password    = BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt(9));
                user.LoginStatus = Infrastructures.Domain.Enums.LoginStatus.NeedToChangePassword;
                this._context.Users.Update(user);
                this._context.SaveChanges();

                this.EmailSendNow(
                    ResetPasswordEmailTemplate(password, user.UserName),
                    user.EmailAddress,
                    user.UserName,
                    "CarWashBookings.Ph - Password Reset"
                    );

                //this.SMSSendNow("Your password has been reset by an Admin. Please use this one-time password : "******" to login to the system.", user.PhoneNumber);
            }

            return(RedirectToAction("index"));
        }
예제 #24
0
        public string EncryptPassword(string userEnteredPassword)
        {
            userEnteredPassword += setupsConfiguration.PasswordSalt;
            string hash = BCryptHelper.GenerateSalt();

            return(BCryptHelper.HashPassword(userEnteredPassword, hash));
        }
        /// <summary>
        /// Hashing Password
        /// </summary>
        /// <param name="plainTextPassword"></param>
        /// <returns></returns>
        public string GetPasswordHash(string plainTextPassword)
        {
            string salt           = BCryptHelper.GenerateSalt();
            string hashedPassword = BCryptHelper.HashPassword(plainTextPassword, salt);

            return(hashedPassword);
        }
예제 #26
0
        public async static Task <int> RegisterPlayer(string username, string password, string email, string socialName, string ip)
        {
            if (await CheckIfPlayerRegistered(username))
            {
                return(0);
            }
            else
            {
                using (MySqlConnection connection = new MySqlConnection(Data.DatabaseHandler.connectionHandle))
                {
                    await connection.OpenAsync().ConfigureAwait(false);

                    MySqlCommand command = connection.CreateCommand();

                    string pSalt    = BCryptHelper.GenerateSalt();
                    string pEncrypt = BCryptHelper.HashPassword(password, pSalt);

                    command.CommandText = "INSERT INTO users (name, password, salt, email, socialName, ip) VALUES (@username, @password, @salt, @email, @socialName, @ip)";
                    command.Parameters.AddWithValue("@username", username);
                    command.Parameters.AddWithValue("@password", pEncrypt);
                    command.Parameters.AddWithValue("@salt", pSalt);
                    command.Parameters.AddWithValue("@email", email);
                    command.Parameters.AddWithValue("@socialName", socialName);
                    command.Parameters.AddWithValue("@ip", ip);

                    await command.ExecuteNonQueryAsync().ConfigureAwait(false);

                    return((int)command.LastInsertedId);
                }
            }
        }
예제 #27
0
        /// <summary>
        /// Implements <see cref="IPasswordHashing.HashPassword(string)"/>
        /// </summary>
        public string HashPassword(string actualPassword)
        {
            var salt = BCryptHelper.GenerateSalt();
            var hash = BCryptHelper.HashPassword(actualPassword, salt);

            return(hash);
        }
예제 #28
0
        public async static Task <int> LoginPlayer(string username, string password)
        {
            int    lastid   = 0;
            string saltuser = await GetSaltPlayer(username);

            string penc = BCryptHelper.HashPassword(password, saltuser);

            using (MySqlConnection connection = new MySqlConnection(Data.DatabaseHandler.connectionHandle))
            {
                await connection.OpenAsync().ConfigureAwait(false);

                MySqlCommand command = connection.CreateCommand();
                command.CommandText = "SELECT * FROM users WHERE name = @username AND password = @password";
                command.Parameters.AddWithValue("@username", username);
                command.Parameters.AddWithValue("@password", penc);

                DbDataReader reader = await command.ExecuteReaderAsync().ConfigureAwait(false);

                if (reader.HasRows)
                {
                    await reader.ReadAsync().ConfigureAwait(false);

                    {
                        lastid = reader.GetInt32(reader.GetOrdinal("id"));
                    }
                }
                return(lastid);
            }
        }
        public void Save(IUserSaveDto dto)
        {
            _userSaveDtoValidator.Check(dto);

            if (dto.Id != null)
            {
                var user = _dao.Get(dto.Id.Value);
                user.Name = dto.Name;
                _dao.Update(user);
            }
            else
            {
                if (_dao.HasEmail(dto.Email))
                {
                    throw new EmailAlreadyExistsException();
                }

                _dao.Create(new User
                {
                    Name     = dto.Name,
                    Email    = dto.Email,
                    Password = BCryptHelper.HashPassword(dto.Password, BCryptHelper.GenerateSalt())
                });
            }
        }
예제 #30
0
        private string GenerateEncryptedPassword(string password)
        {
            var salt         = BCryptHelper.GenerateSalt();
            var passwordHash = BCryptHelper.HashPassword(password, salt);

            return(passwordHash);
        }