public void UpdateUser(User inUserDto) { try { //Begin transaction Start(); UserDalc userDalc = new UserDalc(GetTransaction()); userDalc.UpdateUser(inUserDto); //Commit transaction SetComplete(); } catch (MNException ex) { //Abort transaction SetAbort(); //TODO: Log error throw ex; } catch (Exception ex) { //Abort transaction SetAbort(); //TODO: Log error throw ex; } }
public User GetUser(User inUserDto, bool includeRoles) { User outUserDto = null; try { UserDalc userDalc = new UserDalc(); outUserDto = userDalc.GetUser(inUserDto); if (includeRoles) { RoleDalc roleDalc = new RoleDalc(); inUserDto.UserId = outUserDto.UserId; outUserDto.RolesList = roleDalc.GetRoleList(inUserDto); } } catch (MNException mnEx) { //TODO: Log error throw mnEx; } catch (Exception ex) { //TODO: Log error throw ex; } return(outUserDto); }
public ActionStatus UpdatePassword(User inUserDto) { ActionStatus status = new ActionStatus(); try { UserDalc userDalc = new UserDalc(GetTransaction()); //Start tran Start(); User outUserDto = userDalc.GetUser(inUserDto); inUserDto.PasswordHash = Authentication.GenerateSaltedHash(inUserDto.Password, outUserDto.PasswordSalt); inUserDto.AccountStatus = Constants.Account_Status_Active; userDalc.UpdateUserPasswordHash(inUserDto); //commit tran SetComplete(); status.IsSuccessful = true; status.Messages.Add(new ActionMessage("Your password has been successfully changed.")); } catch (MNException mnEx) { //TODO: Log error //abort tran SetAbort(); throw mnEx; } catch (Exception ex) { //TODO: Log error //abort tran SetAbort(); throw ex; } if (!status.IsSuccessful) { status.Messages.Add( new ActionMessage("Could not change your password. Please contact the system administrator.")); } return(status); }
private static void InitializeDatabase() { Console.Write("Database initializing... "); try { UserDalc userDalc = new UserDalc(); userDalc.Save(new User() { Login = "******", Name = "George Clooney", Email = "*****@*****.**" }); userDalc.Save(new User() { Login = "******", Name = "Johnny Depp", Email = "*****@*****.**" }); userDalc.Save(new User() { Login = "******", Name = "Clint Eastwood", Email = "*****@*****.**" }); userDalc.Save(new User() { Login = "******", Name = "Audrey Hepburn", Email = "*****@*****.**" }); userDalc.Save(new User() { Login = "******", Name = "Sophie Marceau", Email = "*****@*****.**" }); userDalc.Save(new User() { Login = "******", Name = "Jack Nicholson", Email = "*****@*****.**" }); userDalc.Save(new User() { Login = "******", Name = "Gwyneth Paltrow", Email = "*****@*****.**" }); userDalc.Save(new User() { Login = "******", Name = "Patrick Stewart", Email = "*****@*****.**" }); Console.WriteLine("[OK]"); } catch (Exception ex) { Debug.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); Console.WriteLine("[failed]"); } }
/// <summary> /// Attempts to look up an existing user based on user ID. Returns the User object if found, /// else null. If an existing user is found, this method overwrites its first name, middle initial, /// last name, /// </summary> /// <param name="userId"></param> /// <returns></returns> public static bool TryGetExistingUser(int? userId, UserViewModel uvm, out User existingUser) { existingUser = null; if (userId.HasValue) { // Look up the corresponding client record and check the name against it. existingUser = new UserDalc().GetUser(userId.Value); if (existingUser != null && existingUser.FirstName == uvm.User.FirstName && (existingUser.MiddleInitial ?? "") == (uvm.User.MiddleInitial ?? "") && existingUser.LastNameOrCompany == uvm.User.LastNameOrCompany && existingUser.Addresses.Any(a => a.Equals(uvm.User.Addresses.First()))) { // Assume it's the same guy and associate with the existing record. return true; } } return false; }
public ActionStatus DeleteUser(User inUserDto) { ActionStatus status = new ActionStatus(); try { UserDalc userDalc = new UserDalc(GetTransaction()); //Start tran Start(); userDalc.DeleteUser(inUserDto); //commit tran SetComplete(); status.IsSuccessful = true; status.Messages.Add(new ActionMessage("User successfully deleted.")); } catch (MNException mnEx) { //TODO: Log error //abort tran SetAbort(); throw mnEx; } catch (Exception ex) { //TODO: Log error //abort tran SetAbort(); throw ex; } return(status); }
public ActionStatus ResetPassword(User inUserDto) { ActionStatus status = new ActionStatus(); try { UserDalc userDalc = new UserDalc(GetTransaction()); //Start tran Start(); //Get the password salt User outUserDto = userDalc.GetUser(inUserDto); //Generate a new password string newPassword = Membership.GeneratePassword(10, 0); //Generate a hash from the new password and salt inUserDto.PasswordHash = Authentication.GenerateSaltedHash(newPassword, outUserDto.PasswordSalt); //Set the account status to stale so that users have to change the password inUserDto.AccountStatus = Constants.Account_Status_Stale; //Update the password userDalc.UpdateUserPasswordHash(inUserDto); //Create a new mail message MailMessage msg = new MailMessage(); //Set the subject msg.Subject = string.Format(ConfigurationManager.AppSettings["EmailSubject"], "Password Reset"); //Set the to address msg.To.Add(inUserDto.EmailAddress); string msgBody = ConfigurationManager.AppSettings["ResetPassEmail"]; msg.IsBodyHtml = true; //set the message body msg.Body = string.Format(msgBody, inUserDto.EmailAddress, newPassword); //Init a new smtpclient SmtpClient client = new SmtpClient(); //Use the client to send the message client.Send(msg); //commit tran SetComplete(); status.IsSuccessful = true; status.Messages.Add( new ActionMessage( string.Format("Password was successfully reset and emailed to {0}", inUserDto.EmailAddress))); } catch (MNException mnEx) { //TODO: Log error //abort tran SetAbort(); throw mnEx; } catch (Exception ex) { //TODO: Log error //abort tran SetAbort(); throw ex; } if (!status.IsSuccessful) { status.Messages.Add(new ActionMessage("Failed to reset password.")); } return(status); }
public JsonResult SetAdmin(int userId, bool isAdmin) { try { if (ActualUser.IsAdmin) { // Check to see whether the account being set is in the allowed domains, hpwd.com and intera.com var udalc = new UserDalc(); var specimen = udalc.GetUser(userId); if (specimen == null) { return Json(new { success = false, error = "Specified user does not exist." }); } if (specimen.Email.EndsWith("@hpwd.com") || specimen.Email.EndsWith("@intera.com")) { udalc.SetAdmin(userId, isAdmin); return Json(new { success = true }); } else { return Json(new { success = false, error = "This account is a non-HPWD account and cannot become an admin." }); } } else { return Json(new { success = false, error = "Your account does not have sufficient privileges to perform this action." }); } } catch (Exception ex) { Logger.LogError(ex); return Json(new { success = false, error = ex.Message }); } }
public ActionResult AddUser(AdminCreateUserViewModel uvm) { string flashMsg = null, vError = null; if (!Helpers.UserHelper.PopulatePhoneNumbers(uvm, Request, out vError, out flashMsg)) { if (!string.IsNullOrEmpty(vError)) { ModelState.AddModelError("PhoneNumbers", vError); } if (!string.IsNullOrEmpty(flashMsg)) { this.FlashError(flashMsg); } return View(CREATE_VIEWNAME, uvm); } ModelState.Clear(); TryValidateModel(uvm); // Validate each phone number. foreach (var p in uvm.User.PhoneNumbers) { TryValidateModel(p); } if (ModelState.IsValid) { var udalc = new UserDalc(); try { User existingUser; // MWinckler.20111101: This is my interpretation of the requirements, // not explicitly stated by the client. // This model is either a brand-new client record or the user autocompleted // the last name into an existing client record. If the latter, then // x_user_id will be populated. However, even if that's populated, check // the name against the existing client name. If it doesn't match, then // assume the user actually meant to create a new record. int? x_user_id = Request["x_user_id"].TryToInteger(); bool success = false; if (Helpers.UserHelper.TryGetExistingUser(x_user_id, uvm, out existingUser)) { success = udalc.AssociateExistingUser(existingUser, uvm.User); } else { success = udalc.CreateUser(uvm.User, uvm.User.Password); } if (success) { this.FlashInfo("Account created."); // TODO: Act-as the new user and redirect to user profile page. ActAs(uvm.User.Id); return RedirectToAction("Details", "User"); } else { this.FlashError("Errors occurred while trying to create the account."); } } catch (ValidationException ex) { foreach (var err in ex.ValidationErrors) { ModelState.AddModelError("", err); } this.FlashError("Errors occurred while trying to create the account."); } } return View(CREATE_VIEWNAME, uvm); }
/// <summary> /// Looks up the username (email address) of the given user, /// and also finds any associated property descriptions (via /// either ownership or authorized producership) and returns /// the entire result as a JSON array. /// /// In the event of an "act as" situation, the data returned /// will be for the _acted as_ user, with the sole exception /// of "data.actualClientId", which will be the client ID of /// the true (admin) user. /// </summary> /// <param name="ticket">(string) The FormsAuthentication ticket to decrypt.</param> /// <returns>(JSON) A JSON object containing username and any associated property descriptions.</returns> public JsonResult GetUserData(string ticket) { /* Sample result format { status:{success:true, errors:[]}, data: { ActualClientId:1234, ActingAsClientId:5678, EmailAddress:"*****@*****.**", property_descriptions: [ { OwnerName:"Matt", PropertyDesc:"123 Fifth Ave.", PropId:123, IsCurrentUserOwner:true }, { OwnerName:"Meng", PropertyDsec:"555 wherever st.", PropId:555, IsCurrentUserOwner:false } ], VisibleContiguousAcresIds:[4,2,1,662,124] } } */ bool success = true; var errors = new List<string>(); List<PropertyDescription> propDescs = null; User actualUser = null, actingUser = null; int[] caIds = new int[] { }; try { actualUser = actingUser = GetUserFromAuthTicket(ticket); if (actualUser != null) { // If this user is an admin and is acting for someone else, // pull that someone else's info instead. if (actualUser.IsAdmin && actualUser.ActingAsUserId.HasValue) { actingUser = new UserDalc().GetUser(actualUser.ActingAsUserId.Value); } // Pull property descriptions for this user, including owned and // authorized properties propDescs = (from pd in new UserDalc().GetAssociatedProperties(actingUser.Id) select new PropertyDescription(pd)).ToList(); // Retrieve the contiguous acres IDs that this user is permitted to see, // namely, the ones associated with properties that are associated with // the user's account, PLUS the contiguous acres definitions the user // created (regardless of association). caIds = new PropertyDalc().GetContiguousAcresIds(actingUser.Id, (from pd in propDescs select new Tuple<string, string>(pd.ParcelId, pd.County))); } } catch (Exception ex) { success = false; errors.Add("Exception occurred: " + ex.Message); } object ret; if (actualUser == null || actingUser == null) { ret = new JsonResponse(false, "No such user exists."); } else { var d = new { ActualUserId = actualUser.Id, ActingUserId = actingUser.Id, DisplayName = actingUser.DisplayName, EmailAddress = actingUser.Email, PropertyDescriptions = propDescs.OrderBy(x => x.OwnerName).ToArray() ?? new PropertyDescription[] {}, VisibleContiguousAcresIds = caIds, PhoneNumber = string.Join("; ", actingUser.PhoneNumbers) }; ret = new JsonResponse(success, (object)d, errors.ToArray()); } return Json(ret, JsonRequestBehavior.AllowGet); }
/// <summary> /// Associates a property with the user account specified by actingUserId. /// </summary> /// <param name="actualUserId">(int) The actual logged-in user.</param> /// <param name="actingUserId"> /// (int) The "act-as" user (may be the same as the logged-in user; /// actualUser must have privileges to act-as if this ID is different). /// This is the user account the property will be associated with. /// </param> /// <param name="role">(PropertyRole) The acting user's role in relation to the property.</param> /// <param name="parcelId">(string) The parcel ID (PropertyNumber) corresponding to the property in appraisal roll records.</param> /// <param name="county">(string) The county of the </param> /// <param name="productionTypes"></param> /// <returns></returns> public JsonResult AddProperty(string authTicket, int actualUserId, int actingUserId, PropertyRole role, string parcelId, string county, DisclaimerDataType productionTypes) { var errors = new List<string>(); Func<JsonResult> jsonStatus = () => { return Json(new JsonResponse(errors.Count == 0, errors.ToArray())); }; // 0. Verify that all required data is present. if (actualUserId < 1) { errors.Add("Parameter 'actualUserId' is required and must be greater than 0."); } if (actingUserId < 1) { errors.Add("Parameter 'actingUserId' is required and must be greater than 0."); } if (string.IsNullOrWhiteSpace(parcelId)) { errors.Add("Parameter 'parcelId' is required and cannot be blank."); } if (string.IsNullOrWhiteSpace(county)) { errors.Add("Parameter 'county' is required and cannot be blank."); } if (!Enum.IsDefined(typeof(PropertyRole), role)) { errors.Add("Invalid property role: " + role.ToString()); } // Check for validity of production types - this is a flags enum, // so valid values are anything > 0 and < (sum of all values) var maxVal = Enum.GetValues(typeof(DisclaimerDataType)).Cast<int>().Sum(); if (productionTypes < 0 || (int)productionTypes > maxVal || (productionTypes == 0 && role != PropertyRole.installer)) { errors.Add("Invalid production type: " + productionTypes.ToString()); } if (errors.Count > 0) { return jsonStatus(); } var udalc = new UserDalc(); User actualUser = GetUserFromAuthTicket(authTicket); User actingUser = udalc.GetUser(actingUserId); if (actualUser == null) { errors.Add("Unable to find user account based on provided auth ticket."); } if (actingUser == null) { errors.Add("Unable to find user account corresponding to actingUserId == " + actingUserId.ToString()); } if (errors.Count > 0) { return jsonStatus(); } if (actualUser.Id != actualUserId) { // Bizarre - the auth ticket is not for the specified user id. errors.Add("Unauthorized action: The specified authentication ticket does not match the provided actual user ID."); return jsonStatus(); } // 1. Ensure actual user has permission to pose as acting user if (actualUserId != actingUserId && !actualUser.IsAdmin) { errors.Add("Unauthorized action: You do not have permission to act for that user."); return jsonStatus(); } var propDalc = new PropertyDalc(); // 2. Verify that the property matches values in AppraisalRolls. // Also check to ensure there is only one property matching this parcel id // and county. (This is in response to a bug in production where there // where many parcelIds of 0 in Cochran county; without this check // some hundreds of records would be associated with the user account.) int propertyCount = propDalc.GetPropertyCount(parcelId, county); if (propertyCount == 0) { errors.Add(string.Format("Unable to find a matching appraisal roll record for parcel ID '{0}', county '{1}'", parcelId, county)); return jsonStatus(); } else if (propertyCount > 1) { errors.Add(string.Format("Multiple ({0}) records found for parcel ID '{1}', county '{2}'. Cannot add property when duplicates exist.", propertyCount, parcelId, county)); return jsonStatus(); } // 3. If the property has already been associated with the user account, // return an error message to that effect. if (propDalc.IsPropertyAssociated(actingUserId, parcelId, county)) { errors.Add("The property is already associated with your account. If you wish to change roles, please delete the existing property from your account and add it again with the different role."); return jsonStatus(); } // 4. Create the association. propDalc.AssociateProperty(actingUser, new Property(parcelId, county, ""), role, true, productionTypes, false); return jsonStatus(); }
public JsonResult ChangeUserRole(string authTicket, int actingUserId, int actualUserId, PropertyRole? role, string parcelId, string county, DisclaimerDataType? productionTypes) { try { List<string> errors = new List<string>(); Func<JsonResult> jsonStatus = () => { return Json(new JsonResponse(errors.Count == 0, errors.ToArray())); }; // 0. Verify that all required data is present. if (actualUserId < 1) { errors.Add("Parameter 'actualUserId' is required and must be greater than 0."); } if (actingUserId < 1) { errors.Add("Parameter 'actingUserId' is required and must be greater than 0."); } if (string.IsNullOrWhiteSpace(parcelId)) { errors.Add("Parameter 'parcelId' is required and cannot be blank."); } if (string.IsNullOrWhiteSpace(county)) { errors.Add("Parameter 'county' is required and cannot be blank."); } if (!role.HasValue) { // Default to operator role = PropertyRole.authorized_producer; } if (!Enum.IsDefined(typeof(PropertyRole), role)) { errors.Add("Invalid property role: " + role.ToString()); } if (!productionTypes.HasValue) { productionTypes = DisclaimerDataType.agriculture; } // Check for validity of production types - this is a flags enum, // so valid values are anything > 0 and < (sum of all values) var maxVal = Enum.GetValues(typeof(DisclaimerDataType)).Cast<int>().Sum(); if (productionTypes < 0 || (int)productionTypes > maxVal || (productionTypes == 0 && role != PropertyRole.installer)) { errors.Add("Invalid production type: " + productionTypes.ToString()); } if (errors.Count > 0) { return jsonStatus(); } var udalc = new UserDalc(); User actualUser = GetUserFromAuthTicket(authTicket); User actingUser = udalc.GetUser(actingUserId); if (actualUser == null) { errors.Add("Unable to find user account based on provided auth ticket."); } if (actingUser == null) { errors.Add("Unable to find user account corresponding to actingUserId == " + actingUserId.ToString()); } if (errors.Count > 0) { return jsonStatus(); } if (actualUser.Id != actualUserId) { // Bizarre - the auth ticket is not for the specified user id. errors.Add("Unauthorized action: The specified authentication ticket does not match the provided actual user ID."); return jsonStatus(); } // 1. Ensure actual user has permission to pose as acting user if (actualUserId != actingUserId && !actualUser.IsAdmin) { errors.Add("Unauthorized action: You do not have permission to act for that user."); return jsonStatus(); } var propDalc = new PropertyDalc(); // 2. Verify that the property matches values in AppraisalRolls. if (!propDalc.DoesPropertyExist(parcelId, county)) { errors.Add(string.Format("Unable to find a matching appraisal roll record for parcel ID '{0}', county '{1}'", parcelId, county)); return jsonStatus(); } // 3. If the property has not been associated with the user account, // return an error message to that effect. int clientPropertyId; if (!propDalc.IsPropertyAssociated(actingUserId, parcelId, county, out clientPropertyId)) { errors.Add("The specified property is not associated with your account. Please first add the property to your account."); return jsonStatus(); } propDalc.ChangePropertyRoleAndProductionType(actingUser, clientPropertyId, role.Value, productionTypes.Value); return jsonStatus(); } catch (Exception ex) { return Json(new JsonResponse(false, ex.Message)); } }
public JsonResult EmailCAOwner(int caId, string message) { if (ActualUser == null) { return Json(new JsonResponse(false, "You are not authorized to perform that action.")); } if (string.IsNullOrWhiteSpace(message)) { return Json(new JsonResponse(false, "You must specify a message to send.")); } var ca = new GisDalc().GetContiguousAcres(caId); if (ca == null) { return Json(new JsonResponse(false, "No CA corresponding to CA ID " + caId + " was found.")); } var owner = new UserDalc().GetUser(ca.OwnerClientId); if (owner == null) { return Json(new JsonResponse(false, "No owner information found for CA ID " + caId + " (owner ID " + ca.OwnerClientId + ").")); } // Prepend some boilerplate to each message explaining to the owner // what in the world this thing is message = @"This message has been sent from the High Plains Water District website on behalf of " + ActingUser.DisplayName.Trim() + " (" + ActingUser.Email + @") regarding the contiguous acres described as '" + ca.Description + @"', which our records indicate you own. To respond, you can reply directly to this email. " + ActingUser.DisplayName.Trim() + @"'s original message follows. -------- " + message; MailHelper.Send(owner.Email, ActingUser.Email, "HPWD: Message for owner of " + ca.Description, message); return Json(new JsonResponse(true)); }
public ActionStatus RegisterUser(Registration regDto) { // Create the Database object, using the default database service. The // default database service is determined through configuration. SqlDatabase db = new SqlDatabase(Config.ConnString); ActionStatus status = new ActionStatus(); Int32 userId; using (DbConnection connection = db.CreateConnection()) { connection.Open(); DbTransaction txn = null; try { UserDalc dalc = new UserDalc(); User inUserDto = new User(); inUserDto.EmailAddress = regDto.EmailAddress; if (dalc.Exists(inUserDto)) { status.Messages.Add(new ActionMessage(true, 1, "The email address you used already exists.")); } else { txn = connection.BeginTransaction(); UserInsertHelper usrHlpr = new UserInsertHelper(); usrHlpr.InitCommand(db, regDto); userId = usrHlpr.Execute(db, txn); AddressInsertHelper addrHlpr = new AddressInsertHelper(); addrHlpr.InitCommand(db, regDto, userId); addrHlpr.Execute(db, txn); UserRoleInsertHelper roleHlpr = new UserRoleInsertHelper(); roleHlpr.InitCommand(db, regDto.DefaultRoleId, userId); roleHlpr.Execute(db, txn); status.IsSuccessful = true; // Commit the transaction. txn.Commit(); } } catch (SqlException sqlEx) { // Roll back the transaction. txn.Rollback(); Console.WriteLine(sqlEx.ToString()); throw new DataException("An exception occured adding a user to the database.", sqlEx); } finally { connection.Close(); } } return(status); }