/// <summary> /// Initializes Session variables when application is set to development Mode. This event fires when user /// session begins. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Session_Start(Object sender, EventArgs e) { SecurityController sc = new SecurityController(); if (sc.CheckDevelopmentMode()) { //default development values: must be corresponding record in development database or development mode will cause error on login page try { UserDa da = new UserDa(); int userLoginId = da.RecordUserLogin(HttpContext.Current.User.Identity.Name); Session[SessionKey.DatasetId] = 1; Session[SessionKey.PatientId] = 1; Session[SessionKey.LoginId] = 0;// userLoginId; Session[SessionKey.GroupViewCode] = "PATIENT LISTS,PATIENT DATA,FORMS,DATA ANALYSIS,PROTOCOL MANAGER,EFORMS"; Session[SessionKey.PtMRN] = "00000000"; Session[SessionKey.PtFirstName] = "John"; Session[SessionKey.PtLastName] = "Doe"; Session[SessionKey.PtDOB] = "01/01/1950"; } catch (System.Data.SqlClient.SqlException noDevelopmentModeInfoInDatabaseException) { string output = "<strong>Your system is in Development Mode and does not have the required User and Patient in the database.<br>" + "Development mode puts a default user and patient in session so you can update code without logging in after each change.<br>We recommend using developmentMode only if you will be making very frequent updates to the code. It should ALWAYS be turned off when testing." + "<br><br><font color=red>To turn OFF development mode, set the \"developmentMode\" key equal to FALSE in the web.config file.</font><br><br>" + "To use developmentMode, add the UserName \"DevModeUser\" to your Users table, and add the following patient to your Patients table:<br>PtMRN = 00000000<br>PtFirstName = John<br>PtLastName = Doe<br>PtDOB = 01/01/1950"; Response.Write(output); Response.Write("<br><br><br>Exception Detail: " + noDevelopmentModeInfoInDatabaseException.Message); } return; } }
// sometimes occures in a transaction with insertion of new patient record public void InsertAppointmentRecord(Hashtable appointmentArgs, int patientId, SqlTransaction trans) { // add our appointment stuff here SqlCommand apptcmd = DataAccessHelper.CreateCommand(APPT_SQL, trans); // use the transaction from above, somehow apptcmd.CommandType = CommandType.Text; DataAccessHelper.AddIntInputParam(apptcmd, "ApptPatientId", patientId); DataAccessHelper.AddStringInputParam(apptcmd, "ApptFirstName", (string)appointmentArgs["ApptFirstName"]); DataAccessHelper.AddStringInputParam(apptcmd, "ApptLastName", (string)appointmentArgs["ApptLastName"]); DataAccessHelper.AddStringInputParam(apptcmd, "ApptMRN", (string)appointmentArgs["ApptMRN"]); DataAccessHelper.AddStringInputParam(apptcmd, "ApptPhysician", (string)appointmentArgs["ApptPhysician"]); DataAccessHelper.AddStringInputParam(apptcmd, "ApptVisitType", (string)appointmentArgs["ApptVisitType"]); DataAccessHelper.AddStringInputParam(apptcmd, "ApptDept", (string)appointmentArgs["ApptDept"]); DataAccessHelper.AddStringInputParam(apptcmd, "ApptNotes", (string)appointmentArgs["ApptNotes"]); DataAccessHelper.AddDateTimeInputParam(apptcmd, "ApptClinicDate", (DateTime)appointmentArgs["ApptClinicDate"]); DataAccessHelper.AddDateTimeInputParam(apptcmd, "ApptTime", (DateTime)appointmentArgs["ApptTime"]); SecurityController sc = new SecurityController(); string username = sc.GetUserName(); DateTime now = DateTime.Now; DataAccessHelper.AddStringInputParam(apptcmd, "EnteredBy", username); DataAccessHelper.AddDateTimeInputParam(apptcmd, "EnteredTime", now); DataAccessHelper.AddStringInputParam(apptcmd, "UpdatedBy", username); DataAccessHelper.AddDateTimeInputParam(apptcmd, "UpdatedTime", now); apptcmd.ExecuteNonQuery(); }
private void Authenticate() { SecurityController s = HttpContext.Current.User as SecurityController; if (s != null) { if (s.IsInAnyRoles("ADMIN", "Gold", "Silver", "Bronze")) { } else { Response.Redirect("Default.aspx"); } if (s.IsInAnyRoles("ADMIN")) { } else { AdminStuff(); } } else { FormsAuthentication.SignOut(); Response.Redirect("login.aspx"); } }
public bool ChangePassword() { //Validamos que no haya errores en el UserControl if (!dxErrorProvider1.HasErrors && ValidateUC()) { using (WaitCursorHelper waitn = new WaitCursorHelper(this)) { //Cambiamos el Password try { SecurityController.UserChangePassword(UserName, txtOldPassword.Text, txtNewPassword.Text); MessageViewer.Show("Su contraseña fue cambiada exitosamente"); } catch (Exception ex) { this.ExceptionViewer.Show(ex); return(false); } } return(true); } else { return(false); } }
protected void Page_Load(object sender, EventArgs e) { SecurityController s = HttpContext.Current.User as SecurityController; if (s != null) { if (!s.IsInRole("Admin")) { Response.Redirect("Default.aspx"); } } else { Response.Redirect("Default.aspx"); } DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/HomeGallery/image1.jpg")); dir.Refresh(); dir = new DirectoryInfo(Server.MapPath("~/HomeGallery/image2.jpg")); dir.Refresh(); dir = new DirectoryInfo(Server.MapPath("~/HomeGallery/image3.jpg")); dir.Refresh(); Image1.ImageUrl = "HomeGallery/image1.jpg"; Image2.ImageUrl = "HomeGallery/image2.jpg"; Image3.ImageUrl = "HomeGallery/image3.jpg"; CurrentEmailLabel.Text = WebConfigurationManager.AppSettings["mailAccount"]; CurrentAlbumURL.HRef = WebConfigurationManager.AppSettings["albumURL"]; }
public async Task LocalSetup() { var serviceProvider = new ServiceCollection().AddLogging().BuildServiceProvider(); var logger = serviceProvider.GetService <ILoggerFactory>().CreateLogger <UserManager <ApplicationUser> >(); UserStore <ApplicationUser> store = new UserStore <ApplicationUser>(_dbContext); _userManager = new UserManager <ApplicationUser>(store, null, new PasswordHasher <ApplicationUser>(), null, null, null, null, null, logger); _securityService = new SecurityService(_dbContext, _userManager, _roleManager); _securityController = new SecurityController(_securityService); SetUser(_securityController, _createdUser2.Entity.Id); _crew = _dbContext.Crews.Find(1); CrewService crewService = new CrewService(_dbContext, _mainEventProvider); CrewController crewController = new CrewController(crewService); await crewController.AddCrewLeaderAsync(_crew.Id, _createdUser2.Entity.Id); await _securityController.SetPoliciesAsync( new List <CrewPermissionsVm> { new CrewPermissionsVm { Name = "CheckInAdmin", Value = 0, CrewHasPermission = true }, new CrewPermissionsVm { Name = "CrewAdmin", Value = 1, CrewHasPermission = true } }, _crew.Id ); }
protected void SetClinicGroupTitles() { /* set name of clinic group: ie "Dr. Doe's Clinic" * if(Session[SessionKey.CurrentListType] != null && Session[SessionKey.CurrentListType].ToString() == "Clinic") * { * string docClinicName = Session[SessionKey.CurrentListCrit].ToString(); * * // displays just doc last name * //int commaIndex = docClinicName.IndexOf(","); * //docClinicName = docClinicName.Remove(commaIndex, docClinicName.Length - commaIndex); * * ClinicTitle.Text = "Dr. " + docClinicName + "'s Clinic"; * }*/ // get user name UserDa da = new UserDa(); SecurityController sc = new SecurityController(); DataSet ds = da.GetByUserName(sc.GetUserName()); if (ds.Tables[0].Rows.Count == 1) { CurrentClinicUser.Text = ds.Tables[0].Rows[0]["UserFirstName"].ToString() + " " + ds.Tables[0].Rows[0]["UserLastName"].ToString(); } }
public void UpdateTherapist(MassageTherapists person) { MyTherapistEncryption.SecurityController dataEncryptionAlgo = new SecurityController(); bool newrecord = false; Therapist therapistRecord = null; try { var therapistQuery = from therapist in therapistDatabaseContext.Therapists where therapist.Id == person.Id select therapist; therapistRecord = therapistQuery.Single <Therapist>(); therapistRecord.Name = dataEncryptionAlgo.EncryptData(person.Name); therapistRecord.Password = dataEncryptionAlgo.EncryptData(person.Password); } catch (Exception ex) { newrecord = true; } if (newrecord) { therapistRecord = new Therapist(); therapistRecord.Id = Guid.NewGuid(); therapistRecord.Name = dataEncryptionAlgo.EncryptData(person.Name); therapistRecord.Password = dataEncryptionAlgo.EncryptData(person.Password); therapistDatabaseContext.Therapists.InsertOnSubmit(therapistRecord); } therapistDatabaseContext.SubmitChanges(); }
/// <summary> /// Returns a list of user datasets /// </summary> /// <returns></returns> public DataSet GetUserDatasets() { SecurityController sc = new SecurityController(); DataSetDa da = new DataSetDa(); return(da.GetByUser(sc.GetUserName())); }
public override CommandState QueryState(CommandContext context) { CommandState currentState = CommandState.Enabled; SecurityController security = new SecurityController(); Logger.Info("ReviewAndUnlock starting"); if (!security.IsAuthorized()) { Logger.Info("ReviewAndUnlock stopping - not authorized"); currentState = CommandState.Disabled; } else if (context.Items.Length > 0) { Item item = context.Items[0]; if (!security.IsUnlockable(item)) { Logger.Info("ReviewAndUnlock stopping - unlockable"); currentState = CommandState.Disabled; } } else { currentState = base.QueryState(context); } return(currentState); }
/// <summary> /// Handles the CheckedChanged event of the CheckBoxUserInRole control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> protected void CheckBoxUserInRole_CheckedChanged(object sender, EventArgs e) { try { //save any changes to the user as it is checked/unchecked CheckBox checkBoxUserInRole = (CheckBox)sender; string roleName = LiteralRoleName.Text; string userName = GridViewUsers.DataKeys[((GridViewRow)(checkBoxUserInRole).NamingContainer).RowIndex].Value.ToString(); if (checkBoxUserInRole.Checked) { if (!SecurityController.IsUserInRole(userName, roleName)) { //relate the user to the role if they are not already SecurityController.AddUsersToRole(roleName, new string[] { userName }); } } else { //unrelate the user from the role SecurityController.RemoveUsersFromRole(roleName, new string[] { userName }); } } catch (Exception ex) { if (ExceptionPolicy.HandleException(ex, "User Interface")) { DisplayMessage(ex); } } }
/// <summary> /// Handles the Click event of the LinkButtonAddNew control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> protected void LinkButtonAddNew_Click(object sender, EventArgs e) { //create a new role BusinessObjects.Role role = new BusinessObjects.Role(TextBoxRoleName.Text); bool show; try { //save the role SecurityController.CreateRole(role); //refresh the screen //Response.Redirect(Request.Path, true); GridView1.DataBind(); TextBoxRoleName.Text = ""; LiteralRoleName.Text = role.Name; GridViewUsers.DataBind(); show = true; } catch (Exception ex) { //handle error if (ExceptionPolicy.HandleException(ex, "User Interface")) { DisplayMessage(ex); } show = false; } ShowUserGrid(show); }
public bool VerifyUserAccessToDataset(int datasetId) { SecurityController sc = new SecurityController(); string userName = sc.GetUserName(); return(VerifyUserAccessToDataset(datasetId, userName)); }
/// <summary> /// Inicializa: /// IAuthorizationProvider cargandole las reglas por medio de un servicio.- /// IndentityUserInfo (servicio) /// Genera el Principal (local) <see>GetGenericPrincipal</see> /// </summary> /// <param name="msgError">Mensage de error en caso de que se produzca alguno</param> public static void InitAuthorizationFactory(out string pMsgError) { pMsgError = string.Empty; // Inicializo Fwk Authorization provider y catching security provider // ASP.NET Membership y Profile providers no se inicializan de esta manera. try { if (FormBase.RuleProvider == null) { FwkAuthorizationRuleList wFwkAuthorizationRuleList = SecurityController.SearchAllRules(); FormBase.RuleProvider = new FwkAuthorizationRuleProvider(wFwkAuthorizationRuleList); } FormBase.IdentityName = FormBase.IndentityUserInfo.UserName; if (FormBase.Principal == null) { GenericIdentity genericIdentity = new GenericIdentity(FormBase.IdentityName, "Database"); FormBase.Principal = new GenericPrincipal(genericIdentity, FormBase.IndentityUserInfo.Roles); } #region Este codigo se usaba cuando la aplicacion obtenia RuleProvider e IndentityUserInfo de manera local y sin servicios de fwk //if (FRM_FormBase.RuleProvider == null) // FRM_FormBase.RuleProvider = AuthorizationFactory.GetAuthorizationProvider("RuleProvider_Fwk"); //if (FRM_FormBase.IndentityUserInfo == null) // FRM_FormBase.IndentityUserInfo = GetUserInfo(FRM_FormBase.IdentityName); #endregion } catch (Exception ex) { Fwk.Exceptions.TechnicalException wTechEx = new Fwk.Exceptions.TechnicalException("No se configuró correctamente el proveedor de autorización", ex); wTechEx.UserName = FormBase.IdentityName; throw wTechEx; } }
public async Task PasswordUpdate_Method_Returns_BadRequest_On_NotExistingUser() { var securityServiceMock = new Mock <ISecurityService>(); securityServiceMock .Setup(x => x.PasswordUpdateAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .Returns(Task.FromResult(new PasswordUpdateDto { Errors = new[] { "This user does not exist anymore" }, CriticalError = true, Success = false })); var controller = new SecurityController(securityServiceMock.Object); var result = await controller.UpdatePassword(new PasswordUpdateRequest { UserId = "520901e0-fe4e-4a06-9195-9f35ba05e094", Password = "******", Token = "CfDJ8JgR+bdQlp9AiexmNdwmv6Fo38Zi6LS1gfO/Ze2YXmV8QAWJos0oKWZ7FIrr+C2hKWVLgkMQ2Wr+zAiwk/z+Ow9f3rdThOSATiWIC8KVSraZvt7ZP2UR6dWPAZgZYZayPWGnGC6q2nc5NMPQQmIUFoiH+R9bMOnuM3bsML/sb7yAmXJILCLlcnH3qktSg9PauMExiY6eOnYzHIlm6een0aMHboXZ6lA1YtqtKQXd8RUB" }); var badRequestObjectResult = Assert.IsType <BadRequestObjectResult>(result); var statusCode = Assert.IsAssignableFrom <int>(badRequestObjectResult.StatusCode); var passwordUpdateFailedResponse = Assert.IsAssignableFrom <PasswordUpdateResponse>(badRequestObjectResult.Value); Assert.Equal(400, statusCode); Assert.Contains("This user does not exist anymore", passwordUpdateFailedResponse.Errors); Assert.True(passwordUpdateFailedResponse.CriticalError); }
public void GetTokenTest() { var v = ""; var models = new GetTokenModel.Input(); models.OpMid = "aaaa1bbbb2cccc3dddd4eeee5ffff6ee"; models.CardNo = "7413159981000227"; models.CallTime = DateTime.Now.ToString("yyyyMMddhhmmss"); models.MachineID = "Machine0001"; models.Mask = models.GetInMask(); v = JsonConvert.SerializeObject(models); var controller = new SecurityController(); var result = controller.GetToken(AesUtility.Encrypt(v)); result = result.AesDecrypt(); var resultObj = result.FromJson <ApiResult>(); if (resultObj.ErrorCode == "000") { Assert.IsTrue(true, "errorCode為000"); } Assert.IsFalse(true, resultObj.ErrorMessage); }
public async Task PasswordResetRequest_Method_Returns_BadRequest_On_UserWithNotConfirmedEmail() { var securityServiceMock = new Mock <ISecurityService>(); securityServiceMock .Setup(x => x.PasswordResetRequestAsync(It.IsAny <string>())) .Returns(Task.FromResult(new PasswordUpdateDto { Errors = new[] { "User email is not confirmed, sorry, we can't help you with this" }, CriticalError = false, Success = false })); var controller = new SecurityController(securityServiceMock.Object); var result = await controller.PasswordResetRequest(new PasswordResetRequest { Email = "*****@*****.**" }); var badRequestResult = Assert.IsType <BadRequestObjectResult>(result); var statusCode = Assert.IsAssignableFrom <int>(badRequestResult.StatusCode); var passwordUpdateResponse = Assert.IsAssignableFrom <PasswordUpdateResponse>(badRequestResult.Value); Assert.Equal(400, statusCode); Assert.False(passwordUpdateResponse.CriticalError); Assert.Contains("User email is not confirmed, sorry, we can't help you with this", passwordUpdateResponse.Errors); }
private void Save_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(NewPassword.Password) || string.IsNullOrEmpty(NewPassword1.Password)) { MessageBox.Show("Поля обязательны к заполнению", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (!string.IsNullOrEmpty(validations[0])) { MessageBox.Show( "Пароль не соответствует требованиям!\r\nНеобходимо использовать:\r\n" + validations[0], "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (!string.IsNullOrEmpty(validations[1]) && string.IsNullOrEmpty(validations[0])) { MessageBox.Show(validations[1], "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (currentUser != null) { currentUser.Password = SecurityController.Encrypt(NewPassword.Password); currentUser.IsNeedChangePassword = false; EntityController.UpdateUser(currentUser); Close(); } }
public JsonResult UpdatePassword(string password) // Call web api to update password and return result { try { string encPassword = SecurityController.Encrypt(password); // encrypt password (code written in Encrypt function of inside SecurityController class. This controller is written inside utility_class folder ) long userId = GlobalSettings.oUserData.ID; // get user session id (code written in GlobalSetting page inside inside utility_class folder) var result = DBOperations <ChangePassword> .GetSpecific(new ChangePassword() { UserPassword = encPassword, ID = userId }, Constant.usp_Password); // Call a store procedure ‘ChangePassword’ and pass parameters if (result != null) { return(Json(new { Success = 1, Message = "Password updated successfully" }, JsonRequestBehavior.AllowGet)); } else { throw new Exception("Something went wrong.Please try again"); } } catch (Exception ex) { return(Json(new { Success = default(int), Message = ex.Message }, JsonRequestBehavior.AllowGet)); } }
private void LoadCollection() { SpecimenCollection collection = new SpecimenCollection(); collection.Get(colId); CICHelper.SetFieldValues(Page.Controls, collection); this.CollectionName.Text = collection[SpecimenCollection.CollectionName].ToString(); this.CollectionAssignDate.Text = collection[SpecimenCollection.CollectionAssignDate].ToString(); this.CollectionAssignDate.Text = GetValidDisplayDate(this.CollectionAssignDate.Text); this.CollectionType.Text = collection[SpecimenCollection.CollectionType].ToString(); this.CollectionStatus.Text = collection[SpecimenCollection.CollectionStatus].ToString(); this.CollectionProjectCode.Text = collection[SpecimenCollection.CollectionProjectCode].ToString(); this.CollectionAssignNotes.Text = collection[SpecimenCollection.CollectionAssignNotes].ToString(); this.pageTitle.Text = collection[SpecimenCollection.CollectionName].ToString(); SecurityController sc = new SecurityController(); string user = sc.GetUserName(); this.printedBy.Text = user; this.printedDate.Text = DateTime.Now.ToString(); BindSpecimensGrid(); }
private void Authenticate() { SecurityController s = HttpContext.Current.User as SecurityController; if (s != null) { MembershipLevelController mlc = new MembershipLevelController(); List <MembershipLevel> mls = mlc.SelectMembershipLevels(); bool ok = false; foreach (MembershipLevel m in mls) { if (s.IsInRole(m.Description)) { ok = true; } } if (!ok) { FormsAuthentication.SignOut(); Response.Redirect("login.aspx"); } } else { FormsAuthentication.SignOut(); Response.Redirect("login.aspx"); } }
protected void Page_Load(object sender, EventArgs e) { SecurityController s = HttpContext.Current.User as SecurityController; if (s != null) { UserController users = new UserController(); User u = users.GetUser(HttpContext.Current.User.Identity.Name); LoggedInUser.Text = HttpContext.Current.User.Identity.Name; Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~"); string url = webConfigApp.AppSettings.Settings["albumURL"].Value; if (s.IsInRole("Parent") || s.IsInRole("Admin")) { PhotoAlbumLink.Attributes.Add("href", url); form1.Controls.Remove(LoginLink); } else if (!s.IsInRole("Admin") && !s.IsInRole("Parent")) { PhotoAlbumLink.Attributes.Remove("href"); PhotoAlbumLink.Attributes.Add("href", url); form1.Controls.Remove(PhotoAlbumLink); form1.Controls.Remove(LogoutLink); } } else { form1.Controls.Remove(ParentHandbookLink); form1.Controls.Remove(PhotoAlbumLink); form1.Controls.Remove(EventsLink); form1.Controls.Remove(LoggedInUser); form1.Controls.Remove(LogoutLink); } }
protected void ProductGridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) { MessageUserControl.TryRun(() => { GridViewRow row = ProductGridView.Rows[e.NewSelectedIndex]; int partId = int.Parse((row.FindControl("PartID") as HiddenField).Value); var qutity = int.Parse((row.FindControl("Qutity") as TextBox).Text); if (qutity > 0) { var securityController = new SecurityController(); var employeeId = securityController.GetCurrentUserEmployeeId(User.Identity.Name); if (employeeId != null || User.IsInRole("Administrators")) { throw new Exception("Employee or Administrators can't shopping"); } else { var controller = new SalesController(); controller.AddToCart(User.Identity.Name, partId, qutity); //Item.QuantityInCart != 0?Item.QuantityInCart.ToString():"" ProductGridView.DataBind(); CategoryGridView.DataBind(); } } else { throw new Exception("Quantities should geater than 0"); } }, "Successful", "you added a part"); }
public async Task EmailConfirmationRequest_Method_Returns_BadRequest_On_ProblemWitSendingLinkToTheEmail() { var securityServiceMock = new Mock <ISecurityService>(); securityServiceMock .Setup(x => x.SendEmailConfirmationRequestAsync(It.IsAny <string>())) .Returns(Task.FromResult(new EmailConfirmationDto { Errors = new[] { "Something went wrong, please try again or contact support" }, CriticalError = false, Success = false })); var controller = new SecurityController(securityServiceMock.Object); var result = await controller.EmailConfirmationRequest(new EmailConfirmationRequest { Email = "*****@*****.**" }); var badRequestResult = Assert.IsType <BadRequestObjectResult>(result); var statusCode = Assert.IsAssignableFrom <int>(badRequestResult.StatusCode); var emailConfirmationResponse = Assert.IsAssignableFrom <ConfirmationEmailResponse>(badRequestResult.Value); Assert.Equal(400, statusCode); Assert.False(emailConfirmationResponse.CriticalError); Assert.Contains("Something went wrong, please try again or contact support", emailConfirmationResponse.Errors); }
public void Services_Controller_AddPortalAlias_WhenAliasExists_AddIsNotInvoked() { // arrange var controllerMock = new Mock <Components.SecurityController>(); var portalAliasControllerMock = new Mock <IPortalAliasController>(); var portalAliasInfo = new PortalAliasInfo { HTTPAlias = SomeAlias, PortalID = PortalId, }; portalAliasControllerMock .Setup(c => c.GetPortalAlias(SomeAlias, PortalId)) .Returns(() => portalAliasInfo); var sut = new SecurityController(controllerMock.Object, portalAliasControllerMock.Object); // act sut.AddPortalAlias(SslUrl, PortalId); // assert portalAliasControllerMock.Verify( c => c.AddPortalAlias(It.Is <PortalAliasInfo>(match => match.HTTPAlias == SomeAlias && match.PortalID == PortalId)), Times.Never); }
public SecurityControllerTests() { _loginService = new Mock <ILoginService>(); var logger = new Mock <ILogger <SecurityController> >(); _controller = new SecurityController(_loginService.Object, logger.Object); }
public async Task ConfirmEmail_Method_Returns_BadRequest_On_ExpiredToken() { var securityServiceMock = new Mock <ISecurityService>(); securityServiceMock .Setup(x => x.ConfirmEmailAsync(It.IsAny <string>(), It.IsAny <string>())) .Returns(Task.FromResult(new EmailConfirmationDto { Errors = new[] { "Expired link, please make another request" }, CriticalError = false, Success = false })); var controller = new SecurityController(securityServiceMock.Object); var result = await controller.ConfirmEmail(new ConfirmEmailRequest { UserId = "520901e0-fe4e-4a06-9195-9f35ba05e094", Token = "CfDJ8JgR+bdQlp9AiexmNdwmv6Fo38Zi6LS1gfO/Ze2YXmV8QAWJos0oKWZ7FIrr+C2hKWVLgkMQ2Wr+zAiwk/z+Ow9f3rdThOSATiWIC8KVSraZvt7ZP2UR6dWPAZgZYZayPWGnGC6q2nc5NMPQQmIUFoiH+R9bMOnuM3bsML/sb7yAmXJILCLlcnH3qktSg9PauMExiY6eOnYzHIlm6een0aMHboXZ6lA1YtqtKQXd8RUB" }); var badRequestObjectResult = Assert.IsType <BadRequestObjectResult>(result); var statusCode = Assert.IsAssignableFrom <int>(badRequestObjectResult.StatusCode); var confirmEmailFailedRedResponse = Assert.IsAssignableFrom <ConfirmationEmailResponse>(badRequestObjectResult.Value); Assert.Equal(400, statusCode); Assert.Contains("Expired link, please make another request", confirmEmailFailedRedResponse.Errors); Assert.False(confirmEmailFailedRedResponse.CriticalError); }
private void btnResetPwd_Click(object sender, EventArgs e) { this.MessageViewer.MessageBoxButtons = MessageBoxButtons.YesNo; this.MessageViewer.MessageBoxIcon = Fwk.UI.Common.MessageBoxIcon.Question; DialogResult r = this.MessageViewer.Show("Esta a punto de reestablacer la clave de inicio de sesión del usuario, esta seguro ?"); base.SetMessageViewInfoDefault(); if (r == DialogResult.Yes) { if (String.IsNullOrEmpty(txtPassword.Text)) { dxErrorProvider1.SetError(txtConfrirmPassword, "La clave de usuario no puede estar enblanco", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Critical); txtConfrirmPassword.SelectAll(); return; } if (!txtConfrirmPassword.Text.Equals(txtPassword.Text)) { dxErrorProvider1.SetError(txtConfrirmPassword, "La clave y confrirmacion de la misma deben ser iguales", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Critical); txtConfrirmPassword.SelectAll(); return; } try { SecurityController.UserResetPassword(this.profesionalBE.UserName, txtUsername.Text); } catch (Exception ex) { this.ExceptionViewer.Show(ex); } } }
override protected void Page_Load(object sender, System.EventArgs e) { string userName = new SecurityController().GetUserName(); UserDa uda = new UserDa(); DataSet uDs = uda.GetByUserName(userName); int userId = int.Parse(uDs.Tables[0].Rows[0]["UserId"].ToString()); string msgType = ""; if (Request.QueryString["msgStatus"] != null && Request.QueryString["msgStatus"].Length > 0) { msgType = "'" + Request.QueryString["msgStatus"] + "'"; } else { msgType = "'" + EformStatusManager.Status_DataEntryInProgress + "','" + EformStatusManager.Status_DataEntryComplete + "','" + EformStatusManager.Status_Narrated + "'"; } PopulateInbox(userId, msgType); }
public async Task PasswordUpdate_Method_Returns_OK_On_SuccessUpdate() { var securityServiceMock = new Mock <ISecurityService>(); securityServiceMock .Setup(x => x.PasswordUpdateAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .Returns(Task.FromResult(new PasswordUpdateDto { Success = true })); var controller = new SecurityController(securityServiceMock.Object); var result = await controller.UpdatePassword(new PasswordUpdateRequest { UserId = "520901e0-fe4e-4a06-9195-9f35ba05e094", Password = "******", Token = "CfDJ8JgR+bdQlp9AiexmNdwmv6Fo38Zi6LS1gfO/Ze2YXmV8QAWJos0oKWZ7FIrr+C2hKWVLgkMQ2Wr+zAiwk/z+Ow9f3rdThOSATiWIC8KVSraZvt7ZP2UR6dWPAZgZYZayPWGnGC6q2nc5NMPQQmIUFoiH+R9bMOnuM3bsML/sb7yAmXJILCLlcnH3qktSg9PauMExiY6eOnYzHIlm6een0aMHboXZ6lA1YtqtKQXd8RUB" }); var badRequestResult = Assert.IsType <NoContentResult>(result); var statusCode = Assert.IsAssignableFrom <int>(badRequestResult.StatusCode); Assert.Equal(204, statusCode); }
public void SystemCheck_WhenAlarm_IsOff() { _alarm.SwitchOff(); _sensors.Add(_smokeSensor); _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); Assert.IsFalse(_display.DisplayedItems.SystemReady); }
public void SystemCheck_WhenBatteryPoweredSensor_OnLowBattery() { var sensor = new BatteryPoweredSensorMock(true, true); _sensors.Add(sensor); _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); Assert.IsTrue(_display.DisplayedItems.LowBatterySensors.Count > 0); CollectionAssert.AllItemsAreUnique(_display.DisplayedItems.LowBatterySensors); CollectionAssert.Contains(_display.DisplayedItems.LowBatterySensors, sensor.Id); }
public WorldListEntry( [NotNull] WorldListEntry original ) { if( original == null ) throw new ArgumentNullException( "original" ); name = original.Name; Hidden = original.Hidden; Backup = original.Backup; BlockDBEnabled = original.BlockDBEnabled; blockDBIsPreloaded = original.blockDBIsPreloaded; blockDBLimit = original.blockDBLimit; blockDBTimeLimit = original.blockDBTimeLimit; accessSecurity = new SecurityController( original.accessSecurity ); buildSecurity = new SecurityController( original.buildSecurity ); LoadedBy = original.LoadedBy; LoadedOn = original.LoadedOn; MapChangedBy = original.MapChangedBy; MapChangedOn = original.MapChangedOn; environmentEl = original.environmentEl; }
public MainWindow() { InitializeComponent(); ICollection<ISensor> sensors = new List<ISensor>(); _smokeSensor = new SmokeSensor(1); _motionSensor = new MotionSensor(2); var comms = new CommunicationUnit(); _powerSupply = new PowerSupply(); _alarm = new SecurityAlarm(); sensors.Add(_smokeSensor); sensors.Add(_motionSensor); rbSmokeSensorOn.IsChecked = true; rbMotionSensorOn.IsChecked = true; rbAlarmOn.IsChecked = true; _controller = new SecurityController(sensors, comms, _powerSupply, _alarm, userDisplay); }
public void WhenMemoryCleared_TestClear_OnDisplay() { _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); _controller.ClearMemory(); Assert.IsTrue(string.IsNullOrEmpty(_display.DisplayedItems.ReportDetail)); Assert.IsFalse(_display.DisplayedItems.AlarmSound); Assert.IsFalse(_display.DisplayedItems.Armed); }
public void WhenArmStay_PerimeterSensorDetected_TestSendReport() { _sensors.Add(_smokeSensor); _sensors.Add(_motionSensor); _controller = new SecurityController(_sensors, _commsMock, _powerSupply, _alarm, _display); _controller.ArmStay(); _motionSensor.Trigger(); Report.Report report = SecurityController.DeserializeJson<Report.Report>(_commsMock.Details); Assert.AreEqual(_motionSensor.Id, report.SensorId); Assert.AreEqual(_motionSensor.Type, report.SensorType); Assert.AreEqual(ReportType.Intrusion, report.Type); Assert.AreEqual(_commsMock.Details, _display.DisplayedItems.ReportDetail); }
public void WhenNotArmed_SmokeSensorDetected() { _sensors.Add(_smokeSensor); _sensors.Add(_motionSensor); _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); _controller.Disarm(); _smokeSensor.Trigger(); Assert.IsTrue(_alarm.IsActive); }
public void WhenNotArmed_Display_StatesOfAllSensors() { _sensors.Add(_smokeSensor); _sensors.Add(_motionSensor); _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); _controller.Disarm(); CollectionAssert.Contains(_display.DisplayedItems.DetectedSensors, _smokeSensor.Id); CollectionAssert.Contains(_display.DisplayedItems.DetectedSensors, _motionSensor.Id); }
public void WhenPowerBlackOut_OperateOnBattery() { _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); _powerSupply.TriggerLowPower(); Assert.IsTrue(_display.DisplayedItems.PowerSupplyLowBattery); }
public void WhenPowerBlackOut_TestReport() { _controller = new SecurityController(_sensors, _commsMock, _powerSupply, _alarm, _display); _powerSupply.TriggerLowPower(); var report = SecurityController.DeserializeJson<Report.Report>(_commsMock.Details); Assert.AreEqual(ReportType.NoPower, report.Type); Assert.AreEqual(_commsMock.Details, _display.DisplayedItems.ReportDetail); }
public void SystemCheck_WhenPoweredSensor_IsOn() { _sensors.Add(_smokeSensor); _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); Assert.IsTrue(_display.DisplayedItems.SystemReady); }
public void WhenDisarmed_StopAlarm_ClearDisplay() { _sensors.Add(_smokeSensor); _sensors.Add(_motionSensor); _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); _controller.ArmStay(); _motionSensor.Trigger(); _controller.Disarm(); Assert.IsFalse(_alarm.IsActive); Assert.IsFalse(_display.DisplayedItems.Armed); Assert.IsFalse(_display.DisplayedItems.AlarmSound); }
public void WhenArmStay_NonPerimeterSensorDetected() { _sensors.Add(_smokeSensor); _sensors.Add(_motionSensor); _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); _controller.ArmStay(); _smokeSensor.Trigger(); Assert.IsFalse(_display.DisplayedItems.AlarmSound); }
public void WhenArmed_SensorsDetected_TestAlarm() { _sensors.Add(_smokeSensor); _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); _controller.Arm(); _smokeSensor.Trigger(); Assert.IsTrue(_alarm.IsActive); Assert.IsTrue(_display.DisplayedItems.AlarmSound); }
public void TestPeriodic_SystemCheck() { _sensors.Add(_smokeSensor); _sensors.Add(_motionSensor); var timer = new TimerMock(); bool elapsed = false; timer.Elapsed += (sender, e) => elapsed = true; timer.Enabled = true; _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display, timer); Assert.IsTrue(elapsed); Assert.IsTrue(_display.DisplayedItems.SystemReady); }
public void WhenArmed_And_NoSensorsDetected() { _sensors.Add(_smokeSensor); _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); _controller.Arm(); Assert.IsFalse(_display.DisplayedItems.AlarmSound); }
public void WhenArmeStay_TestDisplayStatus() { _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); _controller.ArmStay(); Assert.IsTrue(_display.DisplayedItems.Armed); Assert.IsTrue(_display.DisplayedItems.Stay); }
public WorldListEntry( [NotNull] XElement el ) { if( el == null ) throw new ArgumentNullException( "el" ); XAttribute temp; if( ( temp = el.Attribute( "name" ) ) == null ) { throw new FormatException( "WorldListEntity: Cannot parse XML: Unnamed worlds are not allowed." ); } if( !World.IsValidName( temp.Value ) ) { throw new FormatException( "WorldListEntity: Cannot parse XML: Invalid world name skipped \"" + temp.Value + "\"." ); } name = temp.Value; if( ( temp = el.Attribute( "hidden" ) ) != null && !String.IsNullOrEmpty( temp.Value ) ) { bool hidden; if( Boolean.TryParse( temp.Value, out hidden ) ) { Hidden = hidden; } else { throw new FormatException( "WorldListEntity: Cannot parse XML: Invalid value for \"hidden\" attribute." ); } } else { Hidden = false; } if( ( temp = el.Attribute( "backup" ) ) != null ) { TimeSpan realBackupTimer; if( DateTimeUtil.TryParseTimeSpan( temp.Value, out realBackupTimer ) ) { Backup = BackupNameFromValue( realBackupTimer ); } else { Logger.Log( LogType.Error, "WorldListEntity: Cannot parse backup settings for world \"{0}\". Assuming default.", name ); Backup = BackupEnumNames[0]; } } else { Backup = BackupEnumNames[0]; } XElement tempEl; if( ( tempEl = el.Element( WorldManager.AccessSecurityXmlTagName ) ) != null || ( tempEl = el.Element( "accessSecurity" ) ) != null ) { accessSecurity = new SecurityController( tempEl, false ); } if( ( tempEl = el.Element( WorldManager.BuildSecurityXmlTagName ) ) != null || ( tempEl = el.Element( "buildSecurity" ) ) != null ) { buildSecurity = new SecurityController( tempEl, false ); } XElement blockEl = el.Element( BlockDB.XmlRootName ); if( blockEl == null ) { BlockDBEnabled = YesNoAuto.Auto; } else { if( ( temp = blockEl.Attribute( "enabled" ) ) != null ) { YesNoAuto enabledStateTemp; if( EnumUtil.TryParse( temp.Value, out enabledStateTemp, true ) ) { BlockDBEnabled = enabledStateTemp; } else { Logger.Log( LogType.Warning, "WorldListEntity: Could not parse BlockDB \"enabled\" attribute of world \"{0}\", assuming \"Auto\".", name ); BlockDBEnabled = YesNoAuto.Auto; } } if( ( temp = blockEl.Attribute( "preload" ) ) != null ) { bool isPreloaded; if( Boolean.TryParse( temp.Value, out isPreloaded ) ) { blockDBIsPreloaded = isPreloaded; } else { Logger.Log( LogType.Warning, "WorldListEntity: Could not parse BlockDB \"preload\" attribute of world \"{0}\", assuming NOT preloaded.", name ); } } if( ( temp = blockEl.Attribute( "limit" ) ) != null ) { int limit; if( Int32.TryParse( temp.Value, out limit ) ) { blockDBLimit = limit; } else { Logger.Log( LogType.Warning, "WorldListEntity: Could not parse BlockDB \"limit\" attribute of world \"{0}\", assuming NO limit.", name ); } } if( ( temp = blockEl.Attribute( "timeLimit" ) ) != null ) { int timeLimitSeconds; if( Int32.TryParse( temp.Value, out timeLimitSeconds ) ) { blockDBTimeLimit = TimeSpan.FromSeconds( timeLimitSeconds ); } else { Logger.Log( LogType.Warning, "WorldListEntity: Could not parse BlockDB \"timeLimit\" attribute of world \"{0}\", assuming NO time limit.", name ); } } } if( ( tempEl = el.Element( "LoadedBy" ) ) != null ) { LoadedBy = tempEl.Value; } if( ( tempEl = el.Element( "MapChangedBy" ) ) != null ) { MapChangedBy = tempEl.Value; } if( ( tempEl = el.Element( "LoadedOn" ) ) != null ) { if( !DateTimeUtil.TryParseDateTime( tempEl.Value, ref LoadedOn ) ) { LoadedOn = DateTime.MinValue; } } if( ( tempEl = el.Element( "MapChangedOn" ) ) != null ) { if( !DateTimeUtil.TryParseDateTime( tempEl.Value, ref MapChangedOn ) ) { MapChangedOn = DateTime.MinValue; } } environmentEl = el.Element( WorldManager.EnvironmentXmlTagName ); rankMains = el.Elements( WorldManager.RankMainXmlTagName ).ToArray(); }
public void SystemCheck_WhenSensors_NotOnLowBattery() { _sensors.Add(_smokeSensor); _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); Assert.IsFalse(_display.DisplayedItems.LowBatterySensors.Count > 0); }
public void SystemCheck_WhenPowerSupply_OnLowBattery() { _sensors.Add(_smokeSensor); _controller = new SecurityController(_sensors, _comms, _lowBatteryPowerSupply, _alarm, _display); Assert.IsTrue(_display.DisplayedItems.PowerSupplyLowBattery); }
public void SystemCheck_WithNoSensors() { _controller = new SecurityController(_sensors, _comms, _powerSupply, _alarm, _display); Assert.IsTrue(_display.DisplayedItems.SystemReady); }