Beispiel #1
0
        public async Task ChangePassword(MyUserAdapterModel myUserAdapterModel, string newPassword,
                                         string ip)
        {
            CleanTrackingHelper.Clean <SystemEnvironment>(context);
            CleanTrackingHelper.Clean <MyUserPasswordHistory>(context);
            SystemEnvironment systemEnvironment = await context.SystemEnvironment
                                                  .OrderBy(x => x.Id)
                                                  .FirstOrDefaultAsync();

            string encodePassword =
                PasswordHelper.GetPasswordSHA(myUserAdapterModel.Salt, newPassword);

            myUserAdapterModel.Password = encodePassword;
            var myUser = Mapper.Map <MyUser>(myUserAdapterModel);

            CleanTrackingHelper.Clean <MyUser>(context);

            #region 更新下次要變更密碼的時間
            if (systemEnvironment.EnableCheckPasswordAge)
            {
                myUser.ForceChangePasswordDatetime = DateTime.Now
                                                     .AddDays(systemEnvironment.PasswordAge);
            }
            myUser.ForceChangePassword = false;
            #endregion

            context.Entry(myUser).State = EntityState.Modified;
            await context.SaveChangesAsync();

            if (systemEnvironment.EnablePasswordHistory == true)
            {
                MyUserPasswordHistory myUserPasswordHistory = new MyUserPasswordHistory()
                {
                    MyUserId = myUser.Id,
                    IP       = ip,
                    Password = myUser.Password,
                    ChangePasswordDatetime = DateTime.Now,
                };

                await context.AddAsync(myUserPasswordHistory);

                await context.SaveChangesAsync();

                while (true)
                {
                    #region 只會記錄下系統指定的變更密碼數量 systemEnvironment.PasswordHistory
                    var myUserPasswordHistories = await context.MyUserPasswordHistory
                                                  .Where(x => x.MyUserId == myUser.Id)
                                                  .OrderBy(x => x.ChangePasswordDatetime)
                                                  .ToListAsync();

                    if (myUserPasswordHistories.Count > systemEnvironment.PasswordHistory)
                    {
                        var first = myUserPasswordHistories.First();
                        context.Remove(first);
                        await context.SaveChangesAsync();

                        continue;
                    }
                    else
                    {
                        break;
                    }
                    #endregion
                }
            }
            CleanTrackingHelper.Clean <SystemEnvironment>(context);
            CleanTrackingHelper.Clean <MyUser>(context);
            CleanTrackingHelper.Clean <MyUserPasswordHistory>(context);
        }