private async Task <object> GenerateJwtToken(string email, AspUser user)
        {
            var userRole = await userManager.GetRolesAsync(user);

            user = userManager.Users
                   .Include(u => u.EmployeeUser)
                   .Where(u => u.Id == user.Id).FirstOrDefault();

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Role, userRole[0], "Role"),
                new Claim("id", user.EmployeeUser.Id.ToString()),
                new Claim("username", user.UserName),
                new Claim("role", userRole[0])
                // add more Claims if it's necessary
            };

            var jwtSettings = this.configuration.GetSection("Jwt");
            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["JwtKey"]));
            var creds       = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires     = DateTime.Now.AddDays(1);

            var token = new JwtSecurityToken(
                jwtSettings["JwtIssuer"],
                jwtSettings["JwtIssuer"],
                claims,
                expires: expires,
                signingCredentials: creds
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Exemplo n.º 2
0
        public async Task <IdentityResult> Register(EmployeeDto model)
        {
            var user = new AspUser {
                UserName = model.Email, Email = model.Email
            };
            var result = await userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                //TODO: Add toastr
                await userManager.AddToRoleAsync(user, "user");

                user.EmployeeUser = new EmployeeUser()
                {
                    IsActive            = true,
                    Birthday            = model.DateOfBirth,
                    DepartmentId        = model.DepartmentId,
                    EmployeePositionId  = model.PositionId,
                    FirstName           = model.FirstName,
                    LastName            = model.LastName,
                    InCompanyFrom       = model.StartingDate,
                    PersonalDescription = model.Description,
                    ManagerId           = model.ManagerId,
                };

                await userManager.UpdateAsync(user);
            }

            return(result);
        }
Exemplo n.º 3
0
 public ActionResult Login(AspUserLoginForm form)
 {
     try
     {
         ViewBag.Success = true;
         ViewBag.Message = "Success";
         if (!ModelState.IsValid)
         {
             throw new Exception();
         }
         AspUserService service = new AspUserService();
         int?           id      = service.CheckPassword(form.Mail, form.Password);
         if (id is null)
         {
             throw new Exception();
         }
         AspUser user = service.Get((int)id);
         Utils.SessionUser = user;
         return(RedirectToAction("Index"));
     }
     catch (Exception)
     {
         ViewBag.Success = false;
         ViewBag.Message = "Failed";
         return(View(form));
     }
 }
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    throw new ApplicationException("Error loading external login information during confirmation.");
                }
                var user = new AspUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(nameof(ExternalLogin), model));
        }
Exemplo n.º 5
0
        private AspUser ConvertUser(MembershipUser membership)
        {
            AspUser user = new AspUser();

            if (membership == null)
            {
                return(null);
            }
            user.UserId                  = Utilities.ToGuid(membership.ProviderUserKey);
            user.UserName                = membership.UserName;
            user.IsApproved              = membership.IsApproved;
            user.IsLockedOut             = membership.IsLockedOut;
            user.IsOnline                = membership.IsOnline;
            user.Comment                 = membership.Comment;
            user.CreationDate            = membership.CreationDate;
            user.Email                   = membership.Email;
            user.LastActivityDate        = membership.LastActivityDate;
            user.LastLockoutDate         = membership.LastLockoutDate;
            user.LastLoginDate           = membership.LastLoginDate;
            user.LastPasswordChangedDate = membership.LastPasswordChangedDate;
            user.PasswordQuestion        = membership.PasswordQuestion;
            user.ProviderName            = membership.ProviderName;
            user.ProviderUserKey         = membership.ProviderUserKey;
            user.Password                = "******";
            return(user);
        }
Exemplo n.º 6
0
        private void InitializeData()
        {
            this.InputSalesPinVerifyColor    = "White";
            this.InputSalesPinVerify         = "Unverified";
            this.InputCustomerPinVerifyColor = "Red";
            this.InputCustomerPinVerify      = "Unverified";

            IsCustomerPinEnabled = false;
            IsSalesPinEnabled    = false;
            IsPayBtnEnabled      = false;
            IsBuyInputEnabled    = true;

            if (Application.Current.Properties.ContainsKey("checkinCust"))
            {
                _aspUser = (AspUser)Application.Current.Properties["checkinCust"];

                Application.Current.Properties["checkinCust"] = null;

                this.DepartmentName     = _aspUser.DepartmentName;
                this.Email              = _aspUser.Email;
                this.FirstName          = _aspUser.FirstName;
                this.LastName           = _aspUser.LastName;
                this.MealEntitledPerDay = _aspUser.MealEntitledPerDay.ToString();
            }
        }
Exemplo n.º 7
0
        private AspUser GetSaveAspUser(AspUser aspUser)
        {
            aspUser.IsResetPassword = chkResetPassword.IsChecked == true;
            aspUser.IsApproved      = chkAccountApproved.IsChecked == true;
            aspUser.Email           = txtEmail.Text;
            if (chkChangePasswordQuestionAnswer.IsChecked == true)
            {
                aspUser.PasswordQuestion = txtPasswordQuestion.Text;
                aspUser.PasswordAnswer   = txtPasswordAnswer.Text;
                if (string.IsNullOrEmpty(aspUser.PasswordQuestion))
                {
                    aspUser.PasswordQuestion = ResourceHelper.GetReourceValue("UserAccount_DefaultPasswordQuestion");
                }
                if (string.IsNullOrEmpty(aspUser.PasswordAnswer))
                {
                    aspUser.PasswordAnswer = ResourceHelper.GetReourceValue("UserAccount_DefaultPasswordAnswer");
                }
                aspUser.InputPassword = txtInputPassword.Password;
            }
            else
            {
                aspUser.PasswordQuestion = string.Empty;
                aspUser.PasswordAnswer   = string.Empty;
            }

            aspUser.ErrorMessage = string.Empty;
            return(aspUser);
        }
        protected void Login_Click(object sender, EventArgs e)
        {
            AspUser myuser = new AspUser();

            // check if he is valid
            if (AuthenticatedUser(Username.Text, Password.Text) == 1)
            {
                // get from db to get its information
                myuser = db.AspUser.Where(u => u.Username == Username.Text && u.Password == Password.Text).FirstOrDefault();
                ExtendedMethod.LoginedUser = myuser;
                var rolename = myuser.Role.Name;

                // make a ticket to it
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, myuser.Username, DateTime.Now, DateTime.Now.AddMinutes(2880),
                                                                                 RememberMe.Checked, rolename, FormsAuthentication.FormsCookiePath);

                string     hash   = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

                if (ticket.IsPersistent)
                {
                    cookie.Expires = ticket.Expiration;
                }
                Response.Cookies.Add(cookie);
                Response.Redirect(FormsAuthentication.GetRedirectUrl(myuser.Username, RememberMe.Checked));
            }
            else
            {
                LoginError.Text = "Error Login : Username Or Password Wrong .";
            }
        }
 public static AspUser GetUserData(string UserName)
 {
     try {
         AspUser Logined = db.AspUser.ToList().Where(o => o.Username == UserName).First();
         return(Logined);
     } catch (Exception ex) {
         return(null);
     }
 }
Exemplo n.º 10
0
 public AspUser UnlockAspUser(AspUser oldUser)
 {
     if (oldUser != null)
     {
         MembershipUser memberShipUser = Membership.GetUser(oldUser.UserId);
         memberShipUser.UnlockUser();
         oldUser = GetAspUser(oldUser.UserId);
     }
     return(oldUser);
 }
Exemplo n.º 11
0
        public AspUser GetAspUser(Guid userId)
        {
            AspUser        result = null;
            List <AspUser> list   = ListAspUser(null, userId, null);

            if (list != null && list.Count > 0)
            {
                result = list[0];
            }
            return(result);
        }
Exemplo n.º 12
0
        void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (chkChangePasswordQuestionAnswer.IsChecked == true &&
                (string.IsNullOrEmpty(txtPasswordQuestion.Text) || string.IsNullOrEmpty(txtPasswordAnswer.Text)))
            {
                MessageBox.Show(ResourceHelper.GetReourceValue("UserAccount_QuestionPasswordEmpty"), ResourceHelper.GetReourceValue("Common_ValidationError"), MessageBoxButton.OK);
                return;
            }

            if (uiUsers.SelectedValue != null && (Guid)uiUsers.SelectedValue != Guid.Empty)//Means update user
            {
                Guid    userId  = (Guid)uiUsers.SelectedValue;
                AspUser aspUser = _aspUsers.FirstOrDefault(i => i.UserId == userId);
                if (aspUser != null)
                {
                    Globals.IsBusy = true;
                    aspUser        = GetSaveAspUser(aspUser);
                    DataServiceHelper.SaveAspUserAsync(aspUser, SaveAspUserCompleted);
                }
                if (chkChangePasswordQuestionAnswer.IsChecked == true &&
                    string.IsNullOrEmpty(txtInputPassword.Password))
                {
                    MessageBox.Show(ResourceHelper.GetReourceValue("UserAccount_.InputPasswordEmpty"), ResourceHelper.GetReourceValue("Common_ValidationError"), MessageBoxButton.OK);
                    return;
                }
            }
            else//means create new user
            {
                if (string.IsNullOrEmpty(uiUsers.Text) || string.IsNullOrEmpty(txtPassword.Password))
                {
                    MessageBox.Show(ResourceHelper.GetReourceValue("UserAccount_.UserPasswordEmpty"), ResourceHelper.GetReourceValue("Common_ValidationError"), MessageBoxButton.OK);
                    return;
                }
                AspUser newUser = new AspUser();
                newUser.OrganisationId = Globals.UserLogin.UserOrganisationId;
                newUser.UserName       = uiUsers.Text;
                newUser.Password       = txtPassword.Password;
                newUser = GetSaveAspUser(newUser);
                if (_currentOrgId > 0)
                {
                    newUser.OrganisationId = _currentOrgId;
                }
                if (string.IsNullOrEmpty(newUser.PasswordQuestion))
                {
                    newUser.PasswordQuestion = ResourceHelper.GetReourceValue("UserAccount_DefaultPasswordQuestion");
                }
                if (string.IsNullOrEmpty(newUser.PasswordAnswer))
                {
                    newUser.PasswordAnswer = ResourceHelper.GetReourceValue("UserAccount_DefaultPasswordAnswer");
                }
                Globals.IsBusy = true;
                DataServiceHelper.SaveAspUserAsync(newUser, CreateAspUserCompleted);
            }
        }
Exemplo n.º 13
0
        public ActionResult Save(AspUserVm user)
        {
            if (CheckCookies() == true)
            {
                AspUser _user = new AspUser
                {
                    UserId          = user.AspUser.UserId,
                    FirstName       = user.AspUser.FirstName,
                    LastName        = user.AspUser.LastName,
                    Email           = user.AspUser.Email,
                    Phone           = user.AspUser.Phone,
                    AspRoleId       = user.AspUser.AspRoleId,
                    Password        = Crypto.encrypt(user.AspUser.Password),
                    AspStudentLvlId = user.AspUser.AspStudentLvlId,
                    StudentID       = user.AspUser.StudentID,
                    AuthKey         = user.AspUser.AuthKey
                };
                if (!ModelState.IsValid)
                {
                    var viewModel = new AspUserVm
                    {
                        AspUser       = _user,
                        AspRole       = _context.Roles.ToList(),
                        AspStudentLvl = _context.StudentLvl.ToList()
                    };
                    return(View("UserForm", viewModel));
                }

                if (user.AspUser.UserId == 0)
                {
                    _context.Users.Add(_user);
                }
                else
                {
                    var userInDb = _context.Users.Single(c => c.UserId == _user.UserId);
                    _context.Users.Remove(userInDb);
                    _context.SaveChanges();
                    userInDb.FirstName = _user.FirstName;
                    userInDb.LastName  = _user.LastName;
                    userInDb.Email     = _user.Email;
                    userInDb.Phone     = _user.Phone;
                    userInDb.UserId    = _user.UserId;
                    userInDb.AspRoleId = _user.AspRoleId;
                    _context.Users.Add(userInDb);
                }
                _context.SaveChanges();
                return(RedirectToAction("Index"));
            }
            else
            {
                return(RedirectToAction("Logout", "User"));
            }
        }
        /// <summary>
        /// Returns Jwt token when user logged successfully.
        /// </summary>
        /// <param name="user"></param>
        /// <param name="notifyState">any push state, messages or notifications</param>
        /// <returns></returns>
        private IActionResult JwtAuth([NotNull] AspUser user, UserImpulseState notifyState)
        {
            var identity = _jwtFactory.GenerateClaimsIdentity(user.UserName, user.Id.ToString());

            return(Json(new {
                Result = FeedResult.Success,
                userId = user.Id,
                userName = user.UserName,
                auth_token = _jwtFactory.GenerateEncodedToken(identity),
                expires_in = (int)_jwtOptions.ValidFor.TotalSeconds,
                impulses = notifyState
            }));
        }
Exemplo n.º 15
0
 void btnUnlock_Click(object sender, RoutedEventArgs e)
 {
     if (uiUsers.SelectedValue != null && (Guid)uiUsers.SelectedValue != Guid.Empty)
     {
         Guid    userId  = (Guid)uiUsers.SelectedValue;
         AspUser aspUser = _aspUsers.FirstOrDefault(i => i.UserId == userId);
         if (aspUser != null)
         {
             Globals.IsBusy = true;
             DataServiceHelper.UnlockAspUserAsync(aspUser, UnlockAspUserCompleted);
         }
     }
 }
Exemplo n.º 16
0
        protected AspUser UserModel()
        {
            string  EncryptPass = FormsAuthentication.HashPasswordForStoringInConfigFile(Password.Text, "SHA1");
            AspUser myuser      = new AspUser();

            myuser.Username = Username.Text;
            myuser.Email    = Email.Text;
            myuser.Phone    = Phone.Text;
            myuser.Password = Password.Text;
            myuser.RoleID   = Convert.ToInt32(AddRoleListTxt.SelectedValue);
            myuser.LoginID  = ExtendedMethod.LoginedUser.Id;

            return(myuser);
        }
Exemplo n.º 17
0
 void UnlockAspUserCompleted(AspUser aspUser)
 {
     for (int i = 0; i < _aspUsers.Count; i++)
     {
         if (_aspUsers[i].UserId == aspUser.UserId)
         {
             _aspUsers[i] = aspUser;
             RebindUserAccountData();
             MessageBox.Show(ResourceHelper.GetReourceValue("UserAccount_UserUnlocked"));
             break;
         }
     }
     Globals.IsBusy = true;
 }
Exemplo n.º 18
0
 void chkChangePasswordQuestionAnswer_Checked(object sender, RoutedEventArgs e)
 {
     txtPasswordQuestion.Visibility             = txtPasswordQuestionLabel.Visibility
                                                = txtPasswordAnswer.Visibility = txtPasswordAnswerLabel.Visibility
                                                                                     = chkChangePasswordQuestionAnswer.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
     lblInputPassword.Visibility = txtInputPassword.Visibility = System.Windows.Visibility.Collapsed;
     if (uiUsers.SelectedValue != null && (Guid)uiUsers.SelectedValue != Guid.Empty)
     {
         Guid    userId  = (Guid)uiUsers.SelectedValue;
         AspUser aspUser = _aspUsers.FirstOrDefault(i => i.UserId == userId);
         if (aspUser != null)
         {
             lblInputPassword.Visibility             = txtInputPassword.Visibility
                                                     = chkChangePasswordQuestionAnswer.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
         }
     }
 }
Exemplo n.º 19
0
 public static G.AspUser ToGlobal(this AspUser entity)
 {
     if (entity is null)
     {
         return(null);
     }
     return(new G.AspUser()
     {
         Id = entity.Id,
         Mail = entity.Mail,
         Password = entity.Password,
         LastName = entity.LastName,
         FirstName = entity.FirstName,
         BirthDate = entity.BirthDate,
         RegNational = entity.RegNational,
         Bio = entity.Bio
     });
 }
Exemplo n.º 20
0
 public ActionResult Register(AspUserRegisterForm form)
 {
     try
     {
         if (!ModelState.IsValid)
         {
             throw new Exception();
         }
         AspUserService _service = new AspUserService();
         AspUser        data     = form.ToClient();
         int            id       = _service.Insert(data);
         ViewBag.id = id;
         return(RedirectToAction("Login"));
     }
     catch (Exception)
     {
         return(View(form));
     }
 }
        public async Task <JsonResult> Register([FromBody] RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return(ValidationFail);
            }
            try
            {
                var user = new AspUser
                {
                    UserName = model.Name,
                    Email    = model.Email,
                    GenderId = (byte)model.GenderId,
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = HttpUtility.UrlEncode(code);
                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

                    _logger.LogInformation($"User {user.UserName} created a new account with password.");
                    return(Json(new AccountFeedback()
                    {
                        Result = FeedResult.Redirect,
                        Message = "Your account has been successfully created. You've been sent an email to activate your account."
                    }));
                }
                AddErrors(result);
                return(ValidationFail);
            }
            catch (Exception)
            {
                return(Json(new AccountFeedback()
                {
                    Message = "Something went wrong. Make sure you passed valid email."
                }));
            }
        }
Exemplo n.º 22
0
        public async Task <IActionResult> Register([FromBody] RegisterRequest request)
        {
            var user = new AspUser {
                Email = request.Email, UserName = request.Email
            };
            var created = await userManager.CreateAsync(user, request.Password);

            if (!created.Succeeded)
            {
                var duplicateEmail = created.Errors.Any(e => e.Code == "DuplicateEmail");
                return(BadRequest(duplicateEmail ? "Account with this email address already exists" : "Something wrong have happend"));
            }


            var newUser = await userManager.FindByEmailAsync(request.Email);

            await rnkUserService.Create(new Guid(newUser.Id));

            return(Ok());
        }
Exemplo n.º 23
0
        void SaveAspUserCompleted(AspUser aspUser)
        {
            for (int i = 0; i < _aspUsers.Count; i++)
            {
                if (_aspUsers[i].UserId == aspUser.UserId)
                {
                    if (aspUser.IsSavedQAError)
                    {
                        MessageBox.Show(ResourceHelper.GetReourceValue("UserAccount_InputPasswordIncorrect"));
                    }
                    else if (!string.IsNullOrEmpty(aspUser.ErrorMessage))
                    {
                        MessageBox.Show(aspUser.ErrorMessage);
                    }
                    else
                    {
                        _aspUsers[i] = aspUser;
                        SavedAspUser = aspUser;
                        if (SaveUserAccountComplete != null)
                        {
                            SaveUserAccountComplete(this, null);
                        }
                        RebindUserAccountData();
                        if (!string.IsNullOrEmpty(aspUser.NewGenPassword))
                        {
                            txtResetPasswordInfo.Text       = string.Format(ResourceHelper.GetReourceValue("UserAccount_NewGenPassword"), aspUser.NewGenPassword);
                            txtResetPasswordInfo.Visibility = System.Windows.Visibility.Visible;
                        }
                        else
                        {
                            txtResetPasswordInfo.Visibility = System.Windows.Visibility.Collapsed;
                        }

                        MessageBox.Show(Globals.UserMessages.RecordsSaved);
                    }

                    break;
                }
            }
            Globals.IsBusy = false;
        }
Exemplo n.º 24
0
        public string GenerateJwtToken(AspUser user)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.UserName)
            };

            var key    = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSecurityKey"]));
            var creds  = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expiry = DateTime.Now.AddDays(Convert.ToInt32(configuration["JwtExpiryInDays"]));

            var token = new JwtSecurityToken(
                configuration["JwtIssuer"],
                configuration["JwtAudience"],
                claims,
                expires: expiry,
                signingCredentials: creds
                );

            var tokenHanlder = new JwtSecurityTokenHandler();

            return(tokenHanlder.WriteToken(token));
        }
Exemplo n.º 25
0
        public static void PopulateAspUser(AspUser input, System.Data.IDataReader reader)
        {
            input.ApplicationId = Utilities.ToGuid(reader[Medical.Apartment.Common.AspUser.ColumnNames.ApplicationId]);
            input.UserId = Utilities.ToGuid(reader[Medical.Apartment.Common.AspUser.ColumnNames.UserId]);
            input.Password = Utilities.ToString(reader[Medical.Apartment.Common.AspUser.ColumnNames.Password]);
            input.PasswordFormat = Utilities.ToInt(reader[Medical.Apartment.Common.AspUser.ColumnNames.PasswordFormat]);
            input.PasswordSalt = Utilities.ToString(reader[Medical.Apartment.Common.AspUser.ColumnNames.PasswordSalt]);
            input.MobilePIN = Utilities.ToString(reader[Medical.Apartment.Common.AspUser.ColumnNames.MobilePIN]);
            input.Email = Utilities.ToString(reader[Medical.Apartment.Common.AspUser.ColumnNames.Email]);

            input.Email = Utilities.ToString(reader[Medical.Apartment.Common.AspUser.ColumnNames.Email]);
            input.LoweredEmail = Utilities.ToString(reader[Medical.Apartment.Common.AspUser.ColumnNames.LoweredEmail]);
            input.PasswordQuestion = Utilities.ToString(reader[Medical.Apartment.Common.AspUser.ColumnNames.PasswordQuestion]);
            input.PasswordAnswer = Utilities.ToString(reader[Medical.Apartment.Common.AspUser.ColumnNames.PasswordAnswer]);
            input.IsApproved = Utilities.ToBool(reader[Medical.Apartment.Common.AspUser.ColumnNames.IsApproved]);
            input.IsLockedOut = Utilities.ToBool(reader[Medical.Apartment.Common.AspUser.ColumnNames.IsLockedOut]);
            input.CreationDate = Utilities.ToDateTime(reader[Medical.Apartment.Common.AspUser.ColumnNames.CreateDate]);
            input.LastLoginDate = Utilities.ToDateTime(reader[Medical.Apartment.Common.AspUser.ColumnNames.LastLoginDate]);
            input.LastPasswordChangedDate = Utilities.ToDateTime(reader[Medical.Apartment.Common.AspUser.ColumnNames.LastPasswordChangedDate]);
            input.LastLockoutDate = Utilities.ToDateTime(reader[Medical.Apartment.Common.AspUser.ColumnNames.LastLockoutDate]);

            input.FailedPasswordAttemptCount = Utilities.ToInt(reader[Medical.Apartment.Common.AspUser.ColumnNames.FailedPasswordAttemptCount]);
            input.FailedPasswordAttemptWindowStart = Utilities.ToDateTime(reader[Medical.Apartment.Common.AspUser.ColumnNames.FailedPasswordAttemptWindowStart]);
            input.FailedPasswordAnswerAttemptCount = Utilities.ToInt(reader[Medical.Apartment.Common.AspUser.ColumnNames.FailedPasswordAnswerAttemptCount]);
            input.FailedPasswordAnswerAttemptWindowStart = Utilities.ToDateTime(reader[Medical.Apartment.Common.AspUser.ColumnNames.FailedPasswordAnswerAttemptWindowStart]);
            input.Comment = Utilities.ToString(reader[Medical.Apartment.Common.AspUser.ColumnNames.Comment]);
            input.UserName = Utilities.ToString(reader[Medical.Apartment.Common.AspUser.ColumnNames.UserName]);
            input.LoweredUserName = Utilities.ToString(reader[Medical.Apartment.Common.AspUser.ColumnNames.LoweredUserName]);
            input.MobileAlias = Utilities.ToString(reader[Medical.Apartment.Common.AspUser.ColumnNames.MobileAlias]);

            input.IsAnonymous = Utilities.ToBool(reader[Medical.Apartment.Common.AspUser.ColumnNames.IsAnonymous]);
            
            input.OrganisationId = Utilities.ToNInt(reader[Medical.Apartment.Common.AspUser.ColumnNames.OrganisationId]);
            input.SiteId = Utilities.ToNInt(reader[Medical.Apartment.Common.AspUser.ColumnNames.SiteId]);
            if (reader.ColumnExists(Medical.Apartment.Common.AspUser.ColumnNames.MinRoleLevel))
                input.MinRoleLevel = Utilities.ToNInt(reader[Medical.Apartment.Common.AspUser.ColumnNames.MinRoleLevel]);
            else
                input.MinRoleLevel = 1000;
        }
Exemplo n.º 26
0
        public bool DeleteAspUser(AspUser aspUser, long?employeeId)
        {
            bool userDeleted = Membership.DeleteUser(aspUser.UserName);

            return(userDeleted);
        }
Exemplo n.º 27
0
        public void RebindUserAccountData()
        {
            bool exist = false;

            txtInputPassword.Password = string.Empty;
            if (uiUsers.SelectedValue != null && (Guid)uiUsers.SelectedValue != Guid.Empty)
            {
                Guid    userId  = (Guid)uiUsers.SelectedValue;
                AspUser aspUser = _aspUsers.FirstOrDefault(i => i.UserId == userId);
                if (aspUser != null)
                {
                    exist = true;
                    uiImageOnline.Visibility = chkResetPassword.Visibility = System.Windows.Visibility.Visible;
                    txtPassword.Password     = aspUser.Password;
                    txtPassword.IsEnabled    = false;
                    txtEmail.Text            = string.Empty;

                    if (!string.IsNullOrEmpty(aspUser.Email))
                    {
                        txtEmail.Text = aspUser.Email;
                    }
                    //uiEmployees.IsEnabled = false;
                    chkAccountApproved.IsChecked = aspUser.IsApproved;
                    chkResetPassword.IsChecked   = false;
                    txtResetPasswordInfo.Text    = string.Empty;
                    if (aspUser.IsLockedOut)
                    {
                        chkResetPassword.IsEnabled   = false;
                        chkAccountApproved.IsEnabled = false;
                        btnUnlock.IsEnabled          = this.IsEditable;
                        ucInformation.InfoMessage    = string.Format(ResourceHelper.GetReourceValue("UserAccount_LockedOutMessage"), aspUser.LastLockoutDate);
                    }
                    else
                    {
                        btnUnlock.IsEnabled          = false;
                        chkAccountApproved.IsEnabled = true;
                        chkResetPassword.IsEnabled   = true;
                        ucInformation.InfoMessage    = string.Format(ResourceHelper.GetReourceValue("UserAccount_CreatedInfo"), aspUser.CreationDate.ToString(), aspUser.LastActivityDate.ToString());
                    }
                    if (!string.IsNullOrEmpty(aspUser.PasswordQuestion))
                    {
                        txtPasswordQuestion.Text = aspUser.PasswordQuestion;
                    }
                    if (!string.IsNullOrEmpty(aspUser.PasswordAnswer))
                    {
                        txtPasswordAnswer.Text = aspUser.PasswordAnswer;
                    }

                    chkChangePasswordQuestionAnswer.IsChecked = false;

                    if (aspUser.IsOnline) /*This displays after adding new Admins incorrectly, as the UserID reset triggers this method, ie after saving a new siteAdmin as Org admin.*/
                    {                     /*Dont know where else it is used though, so shall leave for now*/
                        uiImageOnline.Source = new BitmapImage(new Uri(OnlineImage, UriKind.Relative));
                        nsTooltips.ToolTip tooltip = new nsTooltips.ToolTip()
                        {
                            DisplayTime  = new Duration(TimeSpan.FromSeconds(10)),
                            InitialDelay = new Duration(TimeSpan.FromMilliseconds(0)),
                            Content      = ResourceHelper.GetReourceValue("UserAccount_OnlineTooltip")
                        };
                        nsTooltips.ToolTipService.SetToolTip(uiImageOnline, tooltip);
                    }
                    else
                    {
                        uiImageOnline.Source = new BitmapImage(new Uri(OfflineImage, UriKind.Relative));
                        nsTooltips.ToolTip tooltip = new nsTooltips.ToolTip()
                        {
                            DisplayTime  = new Duration(TimeSpan.FromSeconds(10)),
                            InitialDelay = new Duration(TimeSpan.FromMilliseconds(0)),
                            Content      = ResourceHelper.GetReourceValue("UserAccount_OfflineTooltip")
                        };
                        nsTooltips.ToolTipService.SetToolTip(uiImageOnline, tooltip);
                    }
                }
            }

            if (!exist)
            {
                ResetControlStatus();
            }
        }
Exemplo n.º 28
0
 internal static void SaveAspUserAsync(AspUser saveUser, SaveAspUserCallBack callback)
 {
     Guid callerKey = Guid.NewGuid();
     ApartmentServiceClient proxy = GetProxy(callerKey, callback);
     proxy.SaveAspUserCompleted += new EventHandler<SaveAspUserCompletedEventArgs>(proxy_SaveAspUserCompleted);
     proxy.SaveAspUserAsync(saveUser, callerKey);
 }
Exemplo n.º 29
0
        public ActionResult Register(RegistrationVm model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var viewModel = new RegistrationVm()
                    {
                        //CatId = model.CatId,
                        //CityId = model.CityId,
                        //RegionId = model.RegionId,
                        //RoleId = model.User.RoleId,
                        //Categories = model.Categories,
                        //Cities = model.Cities,
                        //Regiones = model.Regiones,
                        User  = model.User,
                        Roles = _context.Roles.ToList()
                    };
                    return(View(viewModel));
                }

                var addPath = Path.Combine(Server.MapPath("~/Content/UserProfile/"), model.File.FileName);
                var data    = new byte[model.File.ContentLength];
                model.File.InputStream.Read(data, 0, model.File.ContentLength);
                using (var sw = new FileStream(addPath, FileMode.Create))
                {
                    sw.Write(data, 0, data.Length);
                }

                int insertedRoleId = 2;
                if (model.User.RoleId == 0)
                {
                    insertedRoleId = 2;
                }
                var newUser = new AspUser()
                {
                    Name     = model.User.Name,
                    Email    = model.User.Email,
                    Password = Crypto.encrypt(model.User.Password),
                    Image    = model.File.FileName,
                    Phone    = model.User.Phone,
                    RoleId   = insertedRoleId
                };

                // --------------------- Insert Data in User Table --------------------------
                _context.Users.Add(newUser);
                _context.SaveChanges();

                // --------------------- Insert Data in User_meta Table ---------------------

                // [Insert User Country]
                AspUserMeta obj = new AspUserMeta();
                obj.UserId  = newUser.Id;
                obj.ColName = "Country";
                obj.Value   = model.CatId.ToString();
                _context.UsersMeta.Add(obj);
                _context.SaveChanges();

                // [Insert User City]
                obj.UserId  = newUser.Id;
                obj.ColName = "City";
                obj.Value   = model.CityId.ToString();
                _context.UsersMeta.Add(obj);
                _context.SaveChanges();

                // [Insert User Region]
                obj.UserId  = newUser.Id;
                obj.ColName = "Region";
                obj.Value   = model.CityId.ToString();
                _context.UsersMeta.Add(obj);
                _context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                                                       validationErrors.Entry.Entity.ToString(),
                                                       validationError.ErrorMessage);
                        // raise a new exception nesting
                        // the current instance as InnerException
                        raise = new InvalidOperationException(message, raise);
                    }
                }
                throw raise;
            }


            return(RedirectToAction("Index"));
        }
Exemplo n.º 30
0
        void SaveAspUserCompleted(AspUser aspUser)
        {
            for (int i = 0; i < _aspUsers.Count; i++)
            {
                if (_aspUsers[i].UserId == aspUser.UserId)
                {
                    if (aspUser.IsSavedQAError)
                    {
                        MessageBox.Show(ResourceHelper.GetReourceValue("UserAccount_InputPasswordIncorrect"));
                    }
                    else if (!string.IsNullOrEmpty(aspUser.ErrorMessage))
                    {
                        MessageBox.Show(aspUser.ErrorMessage);
                    }
                    else
                    {
                        _aspUsers[i] = aspUser;
                        SavedAspUser = aspUser;
                        if (SaveUserAccountComplete != null)
                        {
                            SaveUserAccountComplete(this, null);
                        }
                        RebindUserAccountData();
                        if (!string.IsNullOrEmpty(aspUser.NewGenPassword))
                        {
                            txtResetPasswordInfo.Text = string.Format(ResourceHelper.GetReourceValue("UserAccount_NewGenPassword"), aspUser.NewGenPassword);
                            txtResetPasswordInfo.Visibility = System.Windows.Visibility.Visible;
                        }
                        else
                        {
                            txtResetPasswordInfo.Visibility = System.Windows.Visibility.Collapsed;
                        }
                        
                        MessageBox.Show(Globals.UserMessages.RecordsSaved);
                    }

                    break;
                }
            }
            Globals.IsBusy = false;
        }
Exemplo n.º 31
0
        public AspUser SaveAspUser(AspUser saveUser)
        {
            if (saveUser != null)
            {
                MembershipProvider simpleProvider = Membership.Providers["SimpleProvider"];

                if (saveUser.UserId == Guid.Empty) //means this is new user : create user
                {
                    // Insert New Membership Account
                    MembershipCreateStatus status;
                    MembershipUser         newUser = Membership.CreateUser(saveUser.UserName, saveUser.Password, saveUser.Email,
                                                                           saveUser.PasswordQuestion, saveUser.PasswordAnswer, saveUser.IsApproved, out status);

                    if (status == MembershipCreateStatus.Success)
                    {
                        Guid newUserId = Utilities.ToGuid(newUser.ProviderUserKey);
                        ApartmentMethods.UpdateAspUserOrganisationId(newUserId, saveUser.OrganisationId);
                        saveUser = GetAspUser(newUserId);
                    }
                    else
                    {
                        switch (status)
                        {
                        case MembershipCreateStatus.DuplicateEmail:
                            saveUser.ErrorMessage = "The e-mail address already exists in the database for the application."; break;

                        case MembershipCreateStatus.DuplicateProviderUserKey:
                            saveUser.ErrorMessage = "The provider user key already exists in the database for the application."; break;

                        case MembershipCreateStatus.DuplicateUserName:
                            saveUser.ErrorMessage = "The user name already exists in the database for the application."; break;

                        case MembershipCreateStatus.InvalidAnswer:
                            saveUser.ErrorMessage = "The password answer is not formatted correctly."; break;

                        case MembershipCreateStatus.InvalidEmail:
                            saveUser.ErrorMessage = "The e-mail address is not formatted correctly."; break;

                        case MembershipCreateStatus.InvalidProviderUserKey:
                            saveUser.ErrorMessage = "The provider user key is of an invalid type or format."; break;

                        case MembershipCreateStatus.InvalidQuestion:
                            saveUser.ErrorMessage = "The password question is not formatted correctly."; break;

                        case MembershipCreateStatus.InvalidUserName:
                            saveUser.ErrorMessage = "The user name was not found in the database."; break;

                        case MembershipCreateStatus.InvalidPassword:
                            saveUser.ErrorMessage = "The password is not formatted correctly."; break;

                        default:
                            saveUser.ErrorMessage = "Fail to create new user";
                            break;
                        }
                    }
                }
                else
                {
                    MembershipUser memberShipUser = Membership.GetUser(saveUser.UserId);
                    int?           updateCode     = null;
                    if (memberShipUser.UserName != saveUser.UserName)
                    {
                        updateCode     = ApartmentMethods.UpdateMembershipUserName(Membership.ApplicationName, memberShipUser.UserName, saveUser.UserName);
                        memberShipUser = Membership.GetUser(saveUser.UserId);
                    }

                    string newGenPassword = string.Empty;
                    bool   saveQAerror    = false;
                    if (updateCode == null || updateCode == 0)
                    {
                        memberShipUser.Email      = saveUser.Email;
                        memberShipUser.IsApproved = saveUser.IsApproved;
                        Membership.UpdateUser(memberShipUser);

                        if (!string.IsNullOrEmpty(saveUser.PasswordQuestion) && !string.IsNullOrEmpty(saveUser.PasswordAnswer))
                        {
                            saveQAerror = !memberShipUser.ChangePasswordQuestionAndAnswer(saveUser.InputPassword, saveUser.PasswordQuestion, saveUser.PasswordAnswer);
                        }

                        if (saveUser.IsResetPassword)
                        {
                            if (simpleProvider != null)
                            {
                                MembershipUser simpleUser = simpleProvider.GetUser(saveUser.UserId, false);
                                if (simpleUser != null)
                                {
                                    if (saveUser.IsResetPassword)
                                    {
                                        newGenPassword = simpleUser.ResetPassword();
                                    }
                                }
                            }
                        }
                    }
                    saveUser = GetAspUser(saveUser.UserId);
                    saveUser.NewGenPassword = newGenPassword;
                    saveUser.IsSavedQAError = saveQAerror;
                }
            }

            return(saveUser);
        }
Exemplo n.º 32
0
        internal static void UnlockAspUserAsync(AspUser oldUser, UnlockAspUserCallBack callback)
        {
            Guid callerKey = Guid.NewGuid();

            ApartmentServiceClient proxy = GetProxy(callerKey, callback);
            proxy.UnlockAspUserCompleted += new EventHandler<UnlockAspUserCompletedEventArgs>(proxy_UnlockAspUserCompleted);
            proxy.UnlockAspUserAsync(oldUser, callerKey);
        }
Exemplo n.º 33
0
        void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (chkChangePasswordQuestionAnswer.IsChecked == true
                 && (string.IsNullOrEmpty(txtPasswordQuestion.Text) || string.IsNullOrEmpty(txtPasswordAnswer.Text)))
            {
                MessageBox.Show(ResourceHelper.GetReourceValue("UserAccount_QuestionPasswordEmpty"), ResourceHelper.GetReourceValue("Common_ValidationError"), MessageBoxButton.OK);
                return;
            }

            if (uiUsers.SelectedValue != null && (Guid)uiUsers.SelectedValue != Guid.Empty)//Means update user
            {
                Guid userId = (Guid)uiUsers.SelectedValue;
                AspUser aspUser = _aspUsers.FirstOrDefault(i => i.UserId == userId);
                if (aspUser != null)
                {
                    Globals.IsBusy = true;
                    aspUser = GetSaveAspUser(aspUser);
                    DataServiceHelper.SaveAspUserAsync(aspUser, SaveAspUserCompleted);
                }
                if (chkChangePasswordQuestionAnswer.IsChecked == true
                    && string.IsNullOrEmpty(txtInputPassword.Password))
                {
                    MessageBox.Show(ResourceHelper.GetReourceValue("UserAccount_.InputPasswordEmpty"), ResourceHelper.GetReourceValue("Common_ValidationError"), MessageBoxButton.OK);
                    return;
                }
            }
            else//means create new user
            {
                if (string.IsNullOrEmpty(uiUsers.Text) || string.IsNullOrEmpty(txtPassword.Password))
                {
                    MessageBox.Show(ResourceHelper.GetReourceValue("UserAccount_.UserPasswordEmpty"), ResourceHelper.GetReourceValue("Common_ValidationError"), MessageBoxButton.OK);
                    return;
                }
                AspUser newUser = new AspUser();
                newUser.OrganisationId = Globals.UserLogin.UserOrganisationId;
                newUser.UserName = uiUsers.Text;
                newUser.Password = txtPassword.Password;
                newUser = GetSaveAspUser(newUser);
                if (_currentOrgId > 0)
                {
                    newUser.OrganisationId = _currentOrgId;
                }
                if (string.IsNullOrEmpty(newUser.PasswordQuestion))
                    newUser.PasswordQuestion = ResourceHelper.GetReourceValue("UserAccount_DefaultPasswordQuestion");
                if (string.IsNullOrEmpty(newUser.PasswordAnswer))
                    newUser.PasswordAnswer = ResourceHelper.GetReourceValue("UserAccount_DefaultPasswordAnswer");
                Globals.IsBusy = true;
                DataServiceHelper.SaveAspUserAsync(newUser, CreateAspUserCompleted);
            }
        }
Exemplo n.º 34
0
        public static AspUser AspUser(System.Data.IDataReader reader)
        {
            AspUser result = null;

            if (null != reader && reader.Read())
            {
                result = new AspUser();
                PopulateAspUser(result, reader);
            }

            return result;
        }
Exemplo n.º 35
0
        void CreateAspUserCompleted(AspUser aspUser)
        {
            //if (!string.IsNullOrEmpty(aspUser.ErrorMessage))
            //{
            //    Globals.IsBusy = false;
            //    MessageBox.Show(aspUser.ErrorMessage);
            //    return;
            //}
            //_aspUsers.Add(aspUser);
            //SavedAspUser = aspUser;
            //if (SaveUserAccountComplete != null)
            //{
            //    SaveUserAccountComplete(this, null);
            //}
            //Dictionary<Guid, string> userItemSource = uiUsers.ItemsSource as Dictionary<Guid, string>;
            //userItemSource.Add(aspUser.UserId, aspUser.UserName);
            //userItemSource.OrderBy(i => i.Value);
            //uiUsers.ItemsSource = null;
            //uiUsers.ItemsSource = userItemSource;
            //uiUsers.SelectedValue = aspUser.UserId;
            //RebindUserAccountData();
            //Globals.IsBusy = false;
            //MessageBox.Show(Globals.UserMessages.RecordsSaved);

            if (!string.IsNullOrEmpty(aspUser.ErrorMessage))
            {
                Globals.IsBusy = false;
                MessageBox.Show(aspUser.ErrorMessage);
                return;
            }
            _aspUsers.Add(aspUser);
            SavedAspUser = aspUser;
            if (SaveUserAccountComplete != null)
            {
                SaveUserAccountComplete(this, null);
            }
            Dictionary<Guid, string> userItemSource = uiUsers.ItemsSource as Dictionary<Guid, string>;
            userItemSource.Add(aspUser.UserId, aspUser.UserName);
            userItemSource.OrderBy(i => i.Value);
            uiUsers.ItemsSource = null;
            uiUsers.ItemsSource = userItemSource;
            uiUsers.SelectedValue = aspUser.UserId;
            RebindUserAccountData();
            if (Globals.UserLogin.IsUserPortalAdministrator)
            {
                UserRoleAuth uraOrgAdmin = new UserRoleAuth();
                uraOrgAdmin.RoleId = SecurityHelper.OrganisationAdministratorRoleId;
                uraOrgAdmin.WholeOrg = true;
                uraOrgAdmin.UserId = aspUser.UserId;
                uraOrgAdmin.IsChanged = true;
                uraOrgAdmin.CreatedBy = uraOrgAdmin.UpdatedBy = Globals.UserLogin.UserName;

                UserRoleAuth uraSecurityAdmin = new UserRoleAuth();
                uraSecurityAdmin.RoleId = SecurityHelper.SecurityAdminRoleId;
                uraSecurityAdmin.WholeOrg = true;
                uraSecurityAdmin.UserId = aspUser.UserId;
                uraSecurityAdmin.IsChanged = true;
                uraSecurityAdmin.CreatedBy = uraSecurityAdmin.UpdatedBy = Globals.UserLogin.UserName;

                List<UserRoleAuth> saveList = new List<UserRoleAuth>();
                saveList.Add(uraOrgAdmin);
                saveList.Add(uraSecurityAdmin);
                DataServiceHelper.SaveUserRoleAuthAsync(saveList, SaveUserRoleAuthCompleted);
            }
            else
            {
                Globals.IsBusy = false;
                MessageBox.Show(Globals.UserMessages.RecordsSaved);
            }

        }
Exemplo n.º 36
0
 public bool DeleteAspUser(AspUser aspUser, long? employeeId)
 {
     bool userDeleted = Membership.DeleteUser(aspUser.UserName);
     return userDeleted;
 }
Exemplo n.º 37
0
        void CreateAspUserCompleted(AspUser aspUser)
        {
            //if (!string.IsNullOrEmpty(aspUser.ErrorMessage))
            //{
            //    Globals.IsBusy = false;
            //    MessageBox.Show(aspUser.ErrorMessage);
            //    return;
            //}
            //_aspUsers.Add(aspUser);
            //SavedAspUser = aspUser;
            //if (SaveUserAccountComplete != null)
            //{
            //    SaveUserAccountComplete(this, null);
            //}
            //Dictionary<Guid, string> userItemSource = uiUsers.ItemsSource as Dictionary<Guid, string>;
            //userItemSource.Add(aspUser.UserId, aspUser.UserName);
            //userItemSource.OrderBy(i => i.Value);
            //uiUsers.ItemsSource = null;
            //uiUsers.ItemsSource = userItemSource;
            //uiUsers.SelectedValue = aspUser.UserId;
            //RebindUserAccountData();
            //Globals.IsBusy = false;
            //MessageBox.Show(Globals.UserMessages.RecordsSaved);

            if (!string.IsNullOrEmpty(aspUser.ErrorMessage))
            {
                Globals.IsBusy = false;
                MessageBox.Show(aspUser.ErrorMessage);
                return;
            }
            _aspUsers.Add(aspUser);
            SavedAspUser = aspUser;
            if (SaveUserAccountComplete != null)
            {
                SaveUserAccountComplete(this, null);
            }
            Dictionary <Guid, string> userItemSource = uiUsers.ItemsSource as Dictionary <Guid, string>;

            userItemSource.Add(aspUser.UserId, aspUser.UserName);
            userItemSource.OrderBy(i => i.Value);
            uiUsers.ItemsSource   = null;
            uiUsers.ItemsSource   = userItemSource;
            uiUsers.SelectedValue = aspUser.UserId;
            RebindUserAccountData();
            if (Globals.UserLogin.IsUserPortalAdministrator)
            {
                UserRoleAuth uraOrgAdmin = new UserRoleAuth();
                uraOrgAdmin.RoleId    = SecurityHelper.OrganisationAdministratorRoleId;
                uraOrgAdmin.WholeOrg  = true;
                uraOrgAdmin.UserId    = aspUser.UserId;
                uraOrgAdmin.IsChanged = true;
                uraOrgAdmin.CreatedBy = uraOrgAdmin.UpdatedBy = Globals.UserLogin.UserName;

                UserRoleAuth uraSecurityAdmin = new UserRoleAuth();
                uraSecurityAdmin.RoleId    = SecurityHelper.SecurityAdminRoleId;
                uraSecurityAdmin.WholeOrg  = true;
                uraSecurityAdmin.UserId    = aspUser.UserId;
                uraSecurityAdmin.IsChanged = true;
                uraSecurityAdmin.CreatedBy = uraSecurityAdmin.UpdatedBy = Globals.UserLogin.UserName;

                List <UserRoleAuth> saveList = new List <UserRoleAuth>();
                saveList.Add(uraOrgAdmin);
                saveList.Add(uraSecurityAdmin);
                DataServiceHelper.SaveUserRoleAuthAsync(saveList, SaveUserRoleAuthCompleted);
            }
            else
            {
                Globals.IsBusy = false;
                MessageBox.Show(Globals.UserMessages.RecordsSaved);
            }
        }
Exemplo n.º 38
0
 public AspUser UnlockAspUser(AspUser oldUser)
 {
     if (oldUser != null)
     {
         MembershipUser memberShipUser = Membership.GetUser(oldUser.UserId);
         memberShipUser.UnlockUser();
         oldUser = GetAspUser(oldUser.UserId);
     }
     return oldUser;
 }
Exemplo n.º 39
0
 private AspUser GetSaveAspUser(AspUser aspUser)
 {
     aspUser.IsResetPassword = chkResetPassword.IsChecked == true;
     aspUser.IsApproved = chkAccountApproved.IsChecked == true;
     aspUser.Email = txtEmail.Text;
     if (chkChangePasswordQuestionAnswer.IsChecked == true)
     {
         aspUser.PasswordQuestion = txtPasswordQuestion.Text;
         aspUser.PasswordAnswer = txtPasswordAnswer.Text;
         if (string.IsNullOrEmpty(aspUser.PasswordQuestion))
             aspUser.PasswordQuestion = ResourceHelper.GetReourceValue("UserAccount_DefaultPasswordQuestion");
         if (string.IsNullOrEmpty(aspUser.PasswordAnswer))
             aspUser.PasswordAnswer = ResourceHelper.GetReourceValue("UserAccount_DefaultPasswordAnswer");
         aspUser.InputPassword = txtInputPassword.Password;
     }
     else
     {
         aspUser.PasswordQuestion = string.Empty;
         aspUser.PasswordAnswer = string.Empty;
     }
     
     aspUser.ErrorMessage = string.Empty;
     return aspUser;
 }
Exemplo n.º 40
0
        public AspUser SaveAspUser(AspUser saveUser)
        {
            if (saveUser != null)
            {
                MembershipProvider simpleProvider = Membership.Providers["SimpleProvider"];

                if (saveUser.UserId == Guid.Empty) //means this is new user : create user
                {
                    // Insert New Membership Account
                    MembershipCreateStatus status;
                    MembershipUser newUser = Membership.CreateUser(saveUser.UserName, saveUser.Password, saveUser.Email,
                            saveUser.PasswordQuestion, saveUser.PasswordAnswer, saveUser.IsApproved, out status);

                    if (status == MembershipCreateStatus.Success)
                    {
                        Guid newUserId = Utilities.ToGuid(newUser.ProviderUserKey);
                        ApartmentMethods.UpdateAspUserOrganisationId(newUserId, saveUser.OrganisationId);
                        saveUser = GetAspUser(newUserId);
                    }
                    else
                    {
                        switch (status)
                        {
                            case MembershipCreateStatus.DuplicateEmail:
                                saveUser.ErrorMessage = "The e-mail address already exists in the database for the application."; break;
                            case MembershipCreateStatus.DuplicateProviderUserKey:
                                saveUser.ErrorMessage = "The provider user key already exists in the database for the application."; break;
                            case MembershipCreateStatus.DuplicateUserName:
                                saveUser.ErrorMessage = "The user name already exists in the database for the application."; break;
                            case MembershipCreateStatus.InvalidAnswer:
                                saveUser.ErrorMessage = "The password answer is not formatted correctly."; break;
                            case MembershipCreateStatus.InvalidEmail:
                                saveUser.ErrorMessage = "The e-mail address is not formatted correctly."; break;
                            case MembershipCreateStatus.InvalidProviderUserKey:
                                saveUser.ErrorMessage = "The provider user key is of an invalid type or format."; break;
                            case MembershipCreateStatus.InvalidQuestion:
                                saveUser.ErrorMessage = "The password question is not formatted correctly."; break;
                            case MembershipCreateStatus.InvalidUserName:
                                saveUser.ErrorMessage = "The user name was not found in the database."; break;
                            case MembershipCreateStatus.InvalidPassword:
                                saveUser.ErrorMessage = "The password is not formatted correctly."; break;
                            default:
                                saveUser.ErrorMessage = "Fail to create new user";
                                break;

                        }

                    }
                }
                else
                {
                    MembershipUser memberShipUser = Membership.GetUser(saveUser.UserId);
                    int? updateCode = null;
                    if (memberShipUser.UserName != saveUser.UserName)
                    {
                        updateCode = ApartmentMethods.UpdateMembershipUserName(Membership.ApplicationName, memberShipUser.UserName, saveUser.UserName);
                        memberShipUser = Membership.GetUser(saveUser.UserId);
                    }

                    string newGenPassword = string.Empty;
                    bool saveQAerror = false;
                    if (updateCode == null || updateCode == 0)
                    {
                        memberShipUser.Email = saveUser.Email;
                        memberShipUser.IsApproved = saveUser.IsApproved;
                        Membership.UpdateUser(memberShipUser);

                        if (!string.IsNullOrEmpty(saveUser.PasswordQuestion) && !string.IsNullOrEmpty(saveUser.PasswordAnswer))
                        {
                            saveQAerror = !memberShipUser.ChangePasswordQuestionAndAnswer(saveUser.InputPassword, saveUser.PasswordQuestion, saveUser.PasswordAnswer);
                        }

                        if (saveUser.IsResetPassword)
                        {
                            if (simpleProvider != null)
                            {
                                MembershipUser simpleUser = simpleProvider.GetUser(saveUser.UserId, false);
                                if (simpleUser != null)
                                {
                                    if (saveUser.IsResetPassword)
                                    {
                                        newGenPassword = simpleUser.ResetPassword();
                                    }
                                }
                            }
                        }
                    }
                    saveUser = GetAspUser(saveUser.UserId);
                    saveUser.NewGenPassword = newGenPassword;
                    saveUser.IsSavedQAError = saveQAerror;
                }
            }

            return saveUser;
        }
Exemplo n.º 41
0
 void UnlockAspUserCompleted(AspUser aspUser)
 {
     for (int i = 0; i < _aspUsers.Count; i++)
     {
         if (_aspUsers[i].UserId == aspUser.UserId)
         {
             _aspUsers[i] = aspUser;
             RebindUserAccountData();
             MessageBox.Show(ResourceHelper.GetReourceValue("UserAccount_UserUnlocked"));
             break;
         }
     }
     Globals.IsBusy = true;
 }
Exemplo n.º 42
0
 private AspUser ConvertUser(MembershipUser membership)
 {
     AspUser user = new AspUser();
     if (membership == null)
         return null;
     user.UserId = Utilities.ToGuid(membership.ProviderUserKey);
     user.UserName = membership.UserName;
     user.IsApproved = membership.IsApproved;
     user.IsLockedOut = membership.IsLockedOut;
     user.IsOnline = membership.IsOnline;
     user.Comment = membership.Comment;
     user.CreationDate = membership.CreationDate;
     user.Email = membership.Email;
     user.LastActivityDate = membership.LastActivityDate;
     user.LastLockoutDate = membership.LastLockoutDate;
     user.LastLoginDate = membership.LastLoginDate;
     user.LastPasswordChangedDate = membership.LastPasswordChangedDate;
     user.PasswordQuestion = membership.PasswordQuestion;
     user.ProviderName = membership.ProviderName;
     user.ProviderUserKey = membership.ProviderUserKey;
     user.Password = "******";
     return user;
 }