コード例 #1
0
 public async Task <IHttpActionResult> ChangePassword([FromBody] ChangePasswordViewModel model, string email)
 {
     try
     {
         if (ModelState.IsValid)
         {
             var user = new User();
             if (_userRepo.IsUserExists(email))
             {
                 user = _userRepo.GetByUserEmail(email);
                 if (!PasswordHashProvider.ValidatePassword(model.OldPassword, user.Password))
                 {
                     return(BadRequest("Wrong Password"));
                 }
                 else
                 {
                     var result = _userRepo.ChangePassword(model, email);
                     return(await SendResonse(result, "Your password changed successfully"));
                 }
             }
             else
             {
                 return(BadRequest("No such user exists"));
             }
         }
         else
         {
             return(BadRequest(string.Join(" ", ModelState.Values.SelectMany(x => x.Errors).Select(e => e.ErrorMessage))));
         }
     }
     catch (Exception e)
     {
         return(await ErrorResult(e));
     }
 }
コード例 #2
0
        private string SignInStudent(LoginLogicModel model)
        {
            using (var context = new AASDBContext())
            {
                var student = context.Students.SingleOrDefault(a => a.Email == model.Username);
                if (student == null)
                {
                    throw new LoginErrorException();
                }

                if (string.IsNullOrWhiteSpace(student.Salt))
                {
                    student.Salt     = PasswordHashProvider.GenerateSalt();
                    student.Password = PasswordHashProvider.ComputePasswordHash(student.Password.Trim(), student.Salt);
                    context.SaveChanges();
                }

                var hash = PasswordHashProvider.ComputePasswordHash(model.Password, student.Salt);

                if (student.Password != hash)
                {
                    throw new LoginErrorException();
                }

                return(ComposeToken(model.Username, UserType.StudentUserType));
            }
        }
コード例 #3
0
 public async Task <IHttpActionResult> Register([FromBody] RegisterViewModel model)
 {
     try
     {
         if (ModelState.IsValid)
         {
             if (_userRepo.IsUserExists(model.Email)) //user is alreasy exists
             {
                 return(BadRequest(model.Email + " " + "is already taken"));
             }
             else
             {
                 var user = new User();
                 user.FirstName = model.FirstName;
                 user.LastName  = model.LastName;
                 user.UserName  = model.UserName;
                 user.Email     = model.Email;
                 user.Password  = PasswordHashProvider.HashPassword(model.Password);
                 var    userId   = _userRepo.Create(user);
                 string location = Request.RequestUri + "/" + user.Id.ToString();
                 return(Created(location, new { Id = userId }));
             }
         }
         else
         {
             return(BadRequest(string.Join(" ", ModelState.Values.SelectMany(x => x.Errors).Select(e => e.ErrorMessage))));
         }
     }
     catch (Exception e)
     {
         return(await ErrorResult(e));
     }
 }
コード例 #4
0
        public void PasswordHash_Encode()
        {
            var hashes = new[]
            {
                PasswordHashProvider.EncodePassword("Password1", new TestPasswordSaltProvider("Salt1")),
                PasswordHashProvider.EncodePassword("Password1", new TestPasswordSaltProvider("Salt2")),
                PasswordHashProvider.EncodePassword("Password2", new TestPasswordSaltProvider("Salt1")),
                PasswordHashProvider.EncodePassword("Password2", new TestPasswordSaltProvider("Salt2")),

                PasswordHashProvider.EncodePassword("Password1", new TestPasswordSaltProvider("Salt1")),
                PasswordHashProvider.EncodePassword("Password1", new TestPasswordSaltProvider("Salt2")),
                PasswordHashProvider.EncodePassword("Password2", new TestPasswordSaltProvider("Salt1")),
                PasswordHashProvider.EncodePassword("Password2", new TestPasswordSaltProvider("Salt2")),
            };

            Assert.AreNotEqual(hashes[0], hashes[1]); // same password, different salt
            Assert.AreNotEqual(hashes[0], hashes[2]); // different password, same salt
            Assert.AreNotEqual(hashes[0], hashes[3]); // different password, different salt
            for (int i = 0; i < 4; i++)
            {
                Assert.AreNotEqual(hashes[i], hashes[i + 4]); // not equal even if created by same params.
            }
            Assert.IsTrue(PasswordHashProvider.CheckPassword("Password1", hashes[0], new TestPasswordSaltProvider("Salt1")));
            Assert.IsTrue(PasswordHashProvider.CheckPassword("Password1", hashes[1], new TestPasswordSaltProvider("Salt2")));
            Assert.IsTrue(PasswordHashProvider.CheckPassword("Password2", hashes[2], new TestPasswordSaltProvider("Salt1")));
            Assert.IsTrue(PasswordHashProvider.CheckPassword("Password2", hashes[3], new TestPasswordSaltProvider("Salt2")));
        }
コード例 #5
0
        private string SignInAdmin(LoginLogicModel model)
        {
            using (var context = new AASDBContext())
            {
                var admin = context.Admins.SingleOrDefault(a => a.Username == model.Username);
                if (admin == null)
                {
                    throw new LoginErrorException();
                }

                if (string.IsNullOrWhiteSpace(admin.Salt))
                {
                    admin.Salt     = PasswordHashProvider.GenerateSalt();
                    admin.Password = PasswordHashProvider.ComputePasswordHash(admin.Password.Trim(), admin.Salt);
                    context.SaveChanges();
                }

                var hash = PasswordHashProvider.ComputePasswordHash(model.Password, admin.Salt);

                if (admin.Password != hash)
                {
                    throw new LoginErrorException();
                }

                return(ComposeToken(model.Username, UserType.AdminUserType));
            }
        }
コード例 #6
0
        public int ChangePassword(ChangePasswordViewModel model, string email)
        {
            var user = _dbContext.Users.Where(x => x.Email == email).FirstOrDefault();

            user.Password = PasswordHashProvider.HashPassword(model.NewPassword);
            var result = _dbContext.SaveChanges();

            return(result);
        }
コード例 #7
0
 public User(Guid id,
             string email,
             string username,
             string password)
 {
     this.Id       = id;
     this.Email    = email;
     this.Username = username;
     this.Password = PasswordHashProvider.ComputeHash(password);
 }
コード例 #8
0
        public IHttpActionResult TestSalt()
        {
            var hash = PasswordHashProvider.GenerateSalt();

            return(Json(new
            {
                Hash = hash,
                Length = hash.Length
            }));
        }
コード例 #9
0
        public void HashesWork()
        {
            var provider = new PasswordHashProvider();

            var generated = provider.Generate("testpassword", 32);

            var generatedAgain = provider.Generate("testpassword", generated.Salt);

            Assert.Equal(generated.Hash, generatedAgain);
        }
コード例 #10
0
ファイル: LoginDemo.cs プロジェクト: vlslavik/SenseNet
        void link_Click(object sender, EventArgs e)
        {
            var link = sender as LinkButton;

            if (link == null)
            {
                return;
            }

            var fullUserName = link.CommandArgument;

            if (string.IsNullOrEmpty(fullUserName))
            {
                return;
            }

            var slashIndex = fullUserName.IndexOf('\\');
            var domain     = fullUserName.Substring(0, slashIndex);
            var username   = fullUserName.Substring(slashIndex + 1);

            IUser user;

            // Elevation: we need to have the user content in hand
            // regardless of the current users permissions (she is
            // a Visitor right now, before logging in).
            using (new SystemAccount())
            {
                user = User.Load(domain, username);
            }

            if (user == null)
            {
                return;
            }

            var password = _demoPasswords[user.Name.ToLower()];

            if (!PasswordHashProvider.CheckPassword(password, user.PasswordHash, (IPasswordSaltProvider)user))
            {
                return;
            }


            FormsAuthentication.SetAuthCookie(user.Username, false);
            var originalUrl = PortalContext.GetLoginOriginalUrl();

            if (String.IsNullOrEmpty(originalUrl))
            {
                originalUrl = Request.RawUrl;
            }

            Response.Redirect(originalUrl);
        }
コード例 #11
0
        public bool UpdatePassword(string email, string password)
        {
            var dbAccount = Context.Set <AuthInternal>().FirstOrDefault(u => u.email == email);

            if (PasswordHashProvider.ValidatePassword(password, dbAccount.password))
            {
                dbAccount.password = string.Empty;
                Context.SaveChanges();
                return(true);
            }

            return(false);
        }
コード例 #12
0
        public override void Save(NodeSaveSettings settings)
        {
            // Check uniqueness first
            if (Id == 0 || PropertyNamesForCheckUniqueness.Any(p => IsPropertyChanged(p)))
            {
                CheckUniqueUser();
            }

            if (_password != null)
            {
                this.PasswordHash = PasswordHashProvider.EncodePassword(_password, this);
            }

            Domain = GenerateDomain();

            var originalId = this.Id;

            // save current password to the list of old passwords
            this.SaveCurrentPassword();

            base.Save(settings);

            // AD Sync
            SynchUser(originalId);

            if (originalId == 0)
            {
                // set creator for performant self permission setting
                // creator of the user will always be the user itself. this way setting permissions to the creators group on /Root/IMS will be adequate for user permissions
                // if you need the original creator, use the auditlog
                Retrier.Retry(3, 200, typeof(Exception), () =>
                {
                    // need to clear this flag to avoid getting an 'Id <> 0' error during copying
                    this.CopyInProgress   = false;
                    this.CreatedBy        = this;
                    this.Owner            = this;
                    this.VersionCreatedBy = this;
                    this.DisableObserver(TypeResolver.GetType(NodeObserverNames.NOTIFICATION, false));
                    this.DisableObserver(TypeResolver.GetType(NodeObserverNames.WORKFLOWNOTIFICATION, false));

                    base.Save(SavingMode.KeepVersion);
                });

                // create profile
                if (IdentityManagement.UserProfilesEnabled)
                {
                    CreateProfile();
                }
            }
        }
コード例 #13
0
        public bool UpdatePassword(string email, string password)
        {
            var dbAccount = Context.Set <AuthInternal>().FirstOrDefault(u => u.email == email);

            if (dbAccount != null)
            {
                var hashNewPsw = PasswordHashProvider.CreateHash(password);
                dbAccount.password = hashNewPsw;

                Context.SaveChanges();
                return(true);
            }

            return(false);
        }
コード例 #14
0
ファイル: User.cs プロジェクト: vlslavik/SenseNet
        public override void Save(NodeSaveSettings settings)
        {
            // Check uniqueness first
            CheckUniqueUser();
            if (base.IsPropertyChanged("CreationDate"))
            {
                if (_password != null)
                {
                    this.PasswordHash = PasswordHashProvider.EncodePassword(_password, this);
                }
            }

            Domain = GenerateDomain();

            var originalId = this.Id;

            // save current password to the list of old passwords
            this.SaveCurrentPassword();

            base.Save(settings);

            // AD Sync
            SynchUser(originalId);

            // set creator for performant self permission setting
            // creator of the user will always be the user itself. this way setting permissions to the creators group on /Root/IMS will be adequate for user permissions
            // if you need the original creator, use the auditlog
            if (originalId == 0)
            {
                //need to clear this flag to avoid getting an 'Id <> 0' error during copying
                this.CopyInProgress   = false;
                this.CreatedBy        = this;
                this.VersionCreatedBy = this;
                this.DisableObserver(TypeHandler.GetType(NodeObserverNames.NOTIFICATION));
                this.DisableObserver(TypeHandler.GetType(NodeObserverNames.WORKFLOWNOTIFICATION));

                base.Save(SavingMode.KeepVersion);
            }

            // create profiles
            if (originalId == 0 && Repository.UserProfilesEnabled)
            {
                CreateProfile();
            }
        }
コード例 #15
0
        protected override async Task Handle(SignInCommand request, CancellationToken cancellationToken)
        {
            var user = await _repository.FindSingleAsync((u) => u.Username == request.Username);

            if (user == null)
            {
                throw new ValidationException("Unknown user");
            }

            var hashedPassword = PasswordHashProvider.ComputeHash(request.Password);

            if (hashedPassword != user.Password)
            {
                throw new ValidationException("Invalid password");
            }

            await _accountService.SignIn(user.Id, user.Username, user.Email);
        }
コード例 #16
0
        public bool CheckPasswordMatch(string passwordInClearText)
        {
            var match = false;

            try
            {
                // Check with the configured provider.
                match = PasswordHashProvider.CheckPassword(passwordInClearText, this.PasswordHash, this);
            }
            catch (SaltParseException)
            {
                // Keep 'match = false' and do not do other thing.
            }

            // If the migration is not enabled, shorting: return with the result.
            if (!Configuration.Security.EnablePasswordHashMigration)
            {
                return(match);
            }

            // If password was matched the migration is not needed.
            if (match)
            {
                return(true);
            }

            // Not match and migration is enabled.

            // Check with the outdated provider
            if (!PasswordHashProvider.CheckPasswordForMigration(passwordInClearText, this.PasswordHash, this))
            {
                // If does not match, game over.
                return(false);
            }

            // Migration: generating a new hash with the configured provider and salt.
            this.PasswordHash = PasswordHashProvider.EncodePassword(passwordInClearText, this);

            using (new SystemAccount())
                Save(SavingMode.KeepVersion);

            return(true);
        }
コード例 #17
0
ファイル: UserManager.cs プロジェクト: junkdood/Otokoneko
        public async ValueTask <string> Login(string name, string password, DateTime expireTime)
        {
            var context     = Context;
            var userService = new UserService(context);
            var user        = await userService.GetSingleAsync(it => it.Name == name);

            if (user == null)
            {
                return(null);
            }

            password = PasswordHashProvider.CreateHash(user.Salt, password, 16);
            if (!EncryptUtils.ComparePassword(user.Password, password))
            {
                return(null);
            }

            var token = EncryptUtils.GenerateRandomString(32);

            return(await AddSession(token, user, expireTime, context) ? token : null);
        }
コード例 #18
0
        public void Register(LoginRequest account)
        {
            var dbUser = _authInternalRepository.FindByEmail(account.Email);

            if (dbUser == null)
            {
                using (var transaction = Context.Database.BeginTransaction())
                {
                    try
                    {
                        _accountRepository.Create(new Account
                        {
                            first_name      = account.FirstName,
                            last_name       = account.LastName,
                            username        = account.UserName,
                            registration_ip = account.RegistrationIP
                        });
                        _authInternalRepository.Create(new AuthInternal
                        {
                            account_id = _accountRepository.GetByUserName(account.UserName).id,
                            email      = account.Email,
                            password   = PasswordHashProvider.CreateHash(account.Password)
                        });

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        throw new Exception(ex.Message);
                    }
                }
            }
            else
            {
                _logger.LogError($"Account with {account.Email} already exist!");
                throw new WebException(HttpStatusCode.BadRequest.ToString());
            }
        }
コード例 #19
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (string.IsNullOrEmpty(context.UserName) || string.IsNullOrEmpty(context.Password))
            {
                context.SetError("invalid_grant", "The username or password is incorrect.");
                return;
            }

            var user = _userRepo.GetByUserEmail(context.UserName);

            if (user == null)
            {
                context.SetError("invalid_username", "The username is not correct.");
                return;
            }
            if (!PasswordHashProvider.ValidatePassword(context.Password, user.Password))
            {
                context.SetError("invalid_password", "The password is not correct.");
                return;
            }
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "as:client_id", context.ClientId ?? string.Empty
                },
                {
                    "userName", context.UserName
                }
            });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
コード例 #20
0
        public Account GetOrCreate(LoginRequest account)
        {
            try
            {
                var dbUser = _authInternalRepository.FindByEmail(account.Email);

                if (dbUser == null)
                {
                    _logger.LogError($"Account with login {account.Email} doesn't exist!");
                    return(null);
                }

                if (PasswordHashProvider.ValidatePassword(account.Password, dbUser.password))
                {
                    return(_accountRepository.GetById(dbUser.account_id));
                }

                return(null);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
コード例 #21
0
ファイル: UserManager.cs プロジェクト: junkdood/Otokoneko
        public async ValueTask <RegisterResult> Register(string name, string password, string invitationCode)
        {
            var context = Context;

            try
            {
                context.BeginTran();

                var invitationService = new InvitationService(context);
                var invitation        = await invitationService.
                                        GetSingleAsync(it => it.InvitationCode == invitationCode);

                if (invitation == null)
                {
                    context.RollbackTran();
                    return(RegisterResult.InvitationCodeNotFound);
                }

                if (invitation.ReceiverId > 0)
                {
                    context.RollbackTran();
                    return(RegisterResult.InvitationCodeHasBeenUsed);
                }

                var salt = EncryptUtils.GenerateRandomBytes(64);
                password = PasswordHashProvider.CreateHash(salt, password, 16);
                var user = new User
                {
                    Id        = IdGenerator.CreateId(),
                    Name      = name,
                    Password  = password,
                    Salt      = salt,
                    Authority = invitation.Authority
                };
                var userService = new UserService(context);
                var result      = userService.Insert(user);
                if (result.ErrorList.Count != 0)
                {
                    context.RollbackTran();
                    return(RegisterResult.UsernameRepeated);
                }

                var success = await invitationService.UpdateAsync(
                    it => new Invitation()
                {
                    UsedTime = DateTime.UtcNow, ReceiverId = user.Id
                },
                    it => it.ObjectId == invitation.ObjectId);

                if (!success)
                {
                    context.RollbackTran();
                    return(RegisterResult.InvitationCodeHasBeenUsed);
                }

                context.CommitTran();
                return(RegisterResult.Success);
            }
            catch
            {
                context.RollbackTran();
                throw;
            }
        }
コード例 #22
0
ファイル: PasswordField.cs プロジェクト: vlslavik/SenseNet
 public static string EncodePassword(string passwordInClearText, IPasswordSaltProvider saltProvider)
 {
     return(PasswordHashProvider.EncodePassword(passwordInClearText, saltProvider));
 }