protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { // ¿Ya está logeado? if (IsLoggedIn) { //Redireccionar a la seleccion de efector en caso que tenga mas de uno SSOHelper.RedirectToURL(); } else { // Utiliza protocolo seguro if (!Page.Request.IsSecureConnection) { string url = Page.Request.Url.ToString(); if (url.StartsWith("http:")) { url = "https:" + url.Substring(5); } btnIniciarSesion.PostBackUrl = url; } } } RefreshUI(); }
public void ChangeMessageState(int idMessage, int idState, string rememberOn) { using (Data.DataContext dataContext = SSOHelper.GetDataContext()) { // Controla permisos var query = from r in dataContext.SSO_Messages join t in dataContext.SSO_Messages_Targets on r.id equals t.idMessage where r.id == idMessage && ((t.targetType == (int)SSOMessageTarget.User && t.target == SSOHelper.CurrentIdentity.Id) || (t.targetType == (int)SSOMessageTarget.Role && dataContext.SSO_UserInRole(SSOHelper.CurrentIdentity.Id, t.target) > 0)) select r; if (query.Count() > 0) { Data.SSO_Messages_States state = (from r in dataContext.SSO_Messages_States where r.idMessage == idMessage && r.idUser == SSOHelper.CurrentIdentity.Id select r).SingleOrDefault(); if (state == null) { state = new Data.SSO_Messages_States(); state.idMessage = idMessage; state.idUser = SSOHelper.CurrentIdentity.Id; dataContext.SSO_Messages_States.InsertOnSubmit(state); } state.idState = idState; state.updatedOn = DateTime.Now; state.rememberOn = String.IsNullOrEmpty(rememberOn) ? null : (DateTime?)DateTime.ParseExact(rememberOn, "yyyy/MM/dd", null).Date; dataContext.SubmitChanges(); } } }
private void OnConnectionStateChange(object sender, StateChangeEventArgs e) { if (e.CurrentState == ConnectionState.Open && e.OriginalState == ConnectionState.Closed) { SSOHelper.InitDBAuditData(this.Connection, this.Transaction, false); } }
protected void Page_Init(object sender, EventArgs e) { if (!Page.Request.IsSecureConnection) { SSOHelper.RedirectToSecure(); } }
protected void Page_Load(object sender, EventArgs e) { if (!base.IsLoggedIn) { SSOHelper.RedirectToErrorPage(403, 0, null); } }
protected void btnContinuar_Click(object sender, EventArgs e) { bool doReturn = false; if (SSOHelper.CurrentIdentity != null) { if (!String.IsNullOrEmpty(ddlEfector.Text)) { string[] efector = new string[3]; string[] valores = ddlEfector.SelectedValue.Split(';'); efector[0] = valores[0]; //idEfectorRol -- lo usamos para armar los menues efector[1] = ddlEfector.SelectedItem.Text; //descripcion efector[2] = valores[1]; //idEfector del SysEfector Session["idefector"] = efector; SSOHelper.MembershipProvider.RegistarEfector((int.Parse(((string[])Session["idefector"])[2])), (int.Parse(((string[])Session["idefector"])[0]))); // Redirige a la URL original SSOHelper.RedirectToURL(); } else { //pnlWarningBox.Visible = false; } } else { doReturn = true; } if (doReturn) { // Si está en un popup ... if (!String.IsNullOrEmpty(Request.QueryString["inside"])) { // 10/08/2011 | jgabriel | Como se ejecuta bajo HTTPS las función javascript cross-iframe no funciona, entonces hago una redirección // ¿Hubo cambio de protocolo HTTP -> HTTPS? Si se cambió, hace una redirección. if (String.IsNullOrEmpty(Request.QueryString["RedirectToSecure"])) { ClosePopup(true); } else { string url = Page.Request.Url.ToString(); if (url.StartsWith("https:")) { url = "http:" + url.Substring(6); } Response.Redirect(String.Format("{0}&closePopUp=1", url)); } } else { SSOHelper.RedirectToURL(); } } }
protected void btnContinuar_Click(object sender, EventArgs e) { bool doReturn = false; if (SSOHelper.CurrentIdentity != null && SSOHelper.CurrentIdentity.State == SSOIdentitySessionState.Locked) { if (!String.IsNullOrEmpty(tbPassword.Text)) { int userId; if (SSOHelper.MembershipProvider.TestPassword(SSOHelper.CurrentIdentity.Username, tbPassword.Text, out userId)) { SSOHelper.MembershipProvider.ChangeLockStatus(SSOHelper.CurrentIdentity, false); doReturn = true; } else { pnlErrorBox.Visible = true; pnlWarningBox.Visible = false; } } else { pnlErrorBox.Visible = true; pnlWarningBox.Visible = false; } } else { doReturn = true; } if (doReturn) { // Si está en un popup ... if (!String.IsNullOrEmpty(Request.QueryString["inside"])) { // 10/08/2011 | jgabriel | Como se ejecuta bajo HTTPS las función javascript cross-iframe no funciona, entonces hago una redirección // ¿Hubo cambio de protocolo HTTP -> HTTPS? Si se cambió, hace una redirección. if (String.IsNullOrEmpty(Request.QueryString["RedirectToSecure"])) { ClosePopup(true); } else { string url = Page.Request.Url.ToString(); if (url.StartsWith("https:")) { url = "http:" + url.Substring(6); } Response.Redirect(String.Format("{0}&closePopUp=1", url)); } } else { SSOHelper.RedirectToURL(); } } }
private void accederAlSistema() { string[] efector = new string[3]; string[] valores = ddlEfector.SelectedValue.Split(';'); efector[0] = valores[0]; efector[1] = ddlEfector.Text; efector[2] = valores[1]; Session["idefector"] = efector; SSOHelper.MembershipProvider.RegistarEfector((int.Parse(((string[])Session["idefector"])[2])), (int.Parse(((string[])Session["idefector"])[0]))); SSOHelper.RedirectToURL(); }
protected void Page_Init(object sender, EventArgs e) { if (!IsLoggedIn) { SSOHelper.RedirectToSSOPage("Login.aspx", null); } else { if (!Page.Request.IsSecureConnection) { SSOHelper.RedirectToSecure(); } } }
protected void Page_Init(object sender, EventArgs e) { if (!IsLoggedIn) { SSOHelper.RedirectToSSOPage("Login.aspx", null); } else { if (!Page.Request.IsSecureConnection && String.IsNullOrEmpty(Request.QueryString["closePopUp"])) { SSOHelper.RedirectToSecure(); } } }
public List <Classes.SSOMessage> GetMessages(int fromIndex, int maxRecords) { if (SSOHelper.CurrentIdentity != null) { using (Data.DataContext dataContext = SSOHelper.GetDataContext()) { List <Classes.SSOMessage> messages; DateTime?timeStamp = dataContext.hsp_Common_LastUpdated("SSO_Messages_States"); /* Consulta esta tabla porque cambia más frecuentemente que SSO_Messages */ if (HttpContext.Current.Cache[String.Format("SSO_Messages_Timestamp_{0}", SSOHelper.CurrentIdentity.Id)] as DateTime? != timeStamp) { messages = (from r in dataContext.SSO_Messages join t in dataContext.SSO_Messages_Targets on r.id equals t.idMessage where (!r.expiresOn.HasValue || (r.expiresOn.HasValue && r.expiresOn >= DateTime.Now.Date)) && r.SSO_Messages_Notifications.Count(n => n.notificationType == (int)SSOMessageNotification.Intranet) > 0 && ((t.targetType == (int)SSOMessageTarget.User && t.target == SSOHelper.CurrentIdentity.Id) || (t.targetType == (int)SSOMessageTarget.Role && dataContext.SSO_UserInRole(SSOHelper.CurrentIdentity.Id, t.target) > 0)) && ((from s in dataContext.SSO_Messages_States where s.idMessage == r.id && s.idUser == SSOHelper.CurrentIdentity.Id && s.idState == (int)SSOMessageState.Sent || (s.idState == (int)SSOMessageState.RememberOn && s.rememberOn <= DateTime.Now) select s).Count() > 0) orderby r.date descending select new Classes.SSOMessage { id = r.id, message = r.message, type = r.type, date = r.date }).Distinct().Take(2).ToList(); /* Guarda en caché sólo 10. Este número debe ser siempre >= al número esperado de mensajes 'maxRecords'. */ HttpContext.Current.Cache[String.Format("SSO_Messages_List_{0}", SSOHelper.CurrentIdentity.Id)] = messages; HttpContext.Current.Cache[String.Format("SSO_Messages_Timestamp_{0}", SSOHelper.CurrentIdentity.Id)] = timeStamp; } else { messages = HttpContext.Current.Cache[String.Format("SSO_Messages_List_{0}", SSOHelper.CurrentIdentity.Id)] as List <Classes.SSOMessage>; } if (maxRecords == 0) { return(messages.Where(m => m.id > fromIndex).ToList()); } else { return(messages.Where(m => m.id > fromIndex).Take(maxRecords).ToList()); } //return (from m in messages where m.id > fromIndex select m).Take(maxRecords); } } else { return(null); } }
/// <summary> /// Devuelve el URL a la página que muestra el log de acceso de una aplicación. /// </summary> /// <param name="application">Aplicación</param> /// <param name="accessKeyFilters">[Opcional] Indica que claves buscar en los registros.</param> /// <returns></returns> public static Uri GetLogAccessURL(int applicationId, SSOLogAccessKeys accessKeyFilters) { if (accessKeyFilters != null && accessKeyFilters.Count > 1) { throw new NotImplementedException("Por el momento sólo se puede consultar un accessKey por vez"); } else { if (accessKeyFilters == null || accessKeyFilters.Count == 0) { return(SSOHelper.GetLogAccessURL(applicationId, null, null)); } else { return(SSOHelper.GetLogAccessURL(applicationId, accessKeyFilters[0].name, accessKeyFilters[0].value)); } } }
/// <summary> /// Verifica que el usuario tenga permisos al módulo indicado /// </summary> /// <returns></returns> //public static bool TestPermission(SSOModule module) //{ // if (!module.IsProtected) // return true; // else // { // if (SSOHelper.CurrentIdentity.IsGlobalAdministrator || SSOHelper.CurrentIdentity.IsApplicationAdministrator) // return true; // else // return SSOHelper.GetUserPermissions().Contains(module.Id); // } //} public static bool TestPermissionByEfector(SSOModule module) { if (!module.IsProtected) { return(true); } else { if (SSOHelper.CurrentIdentity.IsGlobalAdministrator || SSOHelper.CurrentIdentity.IsApplicationAdministrator) { return(true); } else { return(SSOHelper.GetUserPermissionsByEfector().Contains(module.Id)); } } }
private bool RequireAccess(SSOModule module) { if (!module.IsProtected) { return(true); } else { if (SSOHelper.TestPermissionByEfector(module)) { SSOHelper.CurrentIdentity.BeginAccess(module); return(true); } else { return(false); } } }
protected void Page_Load(object sender, EventArgs e) { if (IsLoggedIn) { SSOHelper.RedirectToSecure(); if (!Page.IsPostBack) { //if (!String.IsNullOrEmpty(Request.QueryString["url"])) asi solo devuelve null ... Gustavo Saraceni //string url = HttpContext.Current.Request.QueryString["url"]; //if (string.IsNullOrEmpty(url)) // url = SSOHelper.Configuration["StartPage"] as string; //btnVolver.OnClientClick = String.Format("window.location='{0}'", Request.QueryString["url" + "/sips"]); RefreshUI(); } } else { SSOHelper.RedirectToSSOPage("Login.aspx", Request.Url.ToString()); } }
protected void Page_Init(object sender, EventArgs e) { if (IsLoggedIn) { // Logout SSOHelper.MembershipProvider.Logout(SSOHelper.CurrentIdentity.SessionId); // Clear cookie Response.Cookies.Add(new HttpCookie(SSOHelper.MembershipProvider.CookieName, null) { Path = "/", Domain = SSOHelper.Configuration["Domain"].ToString(), Expires = DateTime.Now }); } // Redirect if (Request.QueryString["relogin"] == "1") { SSOHelper.RedirectToSSOPage("Login.aspx", Request.QueryString["url"]); } else { SSOHelper.RedirectToURL(); } }
public void SendSMS(int recipientType, string recipient, int?carrier, string text) { text = text.Trim(); if (text.Length < 2) { throw new Exception("Mensaje muy corto"); } else { using (Data.DataContext DataContext = new Data.DataContext(System.Configuration.ConfigurationManager.ConnectionStrings["SMSServiceConnectionString"].ConnectionString)) { switch (recipientType) { case 2: /* Usuario */ var user = (from r in DataContext.SSO_Users where r.id == int.Parse(recipient) && r.mobile != null && r.idCarrier != null select new { r.name, r.surname, r.mobile, r.idCarrier }).SingleOrDefault(); if (user != null) { recipient = user.mobile; carrier = user.idCarrier; } else { recipient = null; } break; case 3: /* Paciente */ throw new NotImplementedException(); } if (!String.IsNullOrEmpty(recipient) && carrier.HasValue) { SSOHelper.SendSMS(recipient, carrier.Value, text); } } } }
private void Application_AuthenticateRequest(object sender, EventArgs e) { SSOHelper.Authenticate(); if (!((SSOHelper.MembershipProvider.AllowAnonymousAccessToImages && IsImage()) || (SSOHelper.MembershipProvider.AllowAnonymousAccessToScripts && IsScript()))) { SSOModule module = SSOModule.FindByURL(HttpContext.Current.Request.Url); if (module == null) { if (SSOHelper.MembershipProvider.AlwaysAuthenticate && (SSOHelper.CurrentIdentity == null || SSOHelper.CurrentIdentity.State == SSOIdentitySessionState.Inexistent)) { SSOHelper.RedirectToSSOPage("Login.aspx", HttpContext.Current.Request.Url.ToString()); } else { if (SSOHelper.CurrentIdentity == null || SSOHelper.CurrentIdentity.State == SSOIdentitySessionState.Inexistent) { HttpContext.Current.User = null; } else if (!IsWebMethod() || SSOHelper.MembershipProvider.UpdateTimeoutOnWebMethod) { SSOHelper.MembershipProvider.UpdateTimeout(SSOHelper.CurrentIdentity); } } } else { // Check if it needs to authenticate if (SSOHelper.MembershipProvider.AlwaysAuthenticate || module.IsProtected) { if (SSOHelper.CurrentIdentity == null) { SSOHelper.RedirectToSSOPage("Login.aspx", HttpContext.Current.Request.Url.ToString()); } else { switch (SSOHelper.CurrentIdentity.State) { case SSOIdentitySessionState.Ok: if (RequireAccess(module)) { // Access allowed --> Update timeout if (!IsWebMethod() || SSOHelper.MembershipProvider.UpdateTimeoutOnWebMethod) { SSOHelper.MembershipProvider.UpdateTimeout(SSOHelper.CurrentIdentity); } } else { SSOHelper.RedirectToErrorPage(403, 0, null); } break; case SSOIdentitySessionState.Locked: SSOHelper.RedirectToSSOPage("LockSession.aspx", HttpContext.Current.Request.Url.ToString()); break; case SSOIdentitySessionState.Inexistent: SSOHelper.RedirectToSSOPage("Login.aspx?timeout=1", HttpContext.Current.Request.Url.ToString()); break; case SSOIdentitySessionState.SecurityError: SSOHelper.RedirectToErrorPage(403, 4, null); break; } } } else { // Access allowed --> Update timeout if (SSOHelper.CurrentIdentity != null && SSOHelper.CurrentIdentity.State == SSOIdentitySessionState.Ok && (!IsWebMethod() || SSOHelper.MembershipProvider.UpdateTimeoutOnWebMethod)) { SSOHelper.MembershipProvider.UpdateTimeout(SSOHelper.CurrentIdentity); } } } } }
protected void btnRegresar_Click(object sender, EventArgs e) { SSOHelper.RedirectToSSOPage("Login.aspx", null); }
private void Application_Error(object sender, EventArgs e) { if (SSOHelper.CurrentIdentity != null) { SSOHelper.CurrentIdentity.FinalizeAccess(); } // Envía un mail con la excepción //string mailServer; string debugHosts; //try //{ // mailServer = (string)SSOHelper.Configuration["Email_Server"]; //} //catch (Exception) //{ // mailServer = "exchange2010.hospitalneuquen.org.ar"; //} try { debugHosts = ((string)SSOHelper.Configuration["Debug_Hosts"]).ToUpper(); } catch (Exception) { debugHosts = "HOST1,HOST2,HOST352"; } Exception exception = HttpContext.Current.Server.GetLastError(); HttpException httpException = exception as HttpException; // Define que tipo de excepciones enviará por mail if ((httpException == null || (httpException != null && httpException.GetHttpCode() != 404)) && !exception.Message.ToLower().StartsWith("the client disconnected") && (String.IsNullOrEmpty(debugHosts) || !debugHosts.Contains(HttpContext.Current.Server.MachineName.ToUpper()))) { // Construye el mensaje con la mayor cantidad de datos StringBuilder sb = new StringBuilder(); try { sb.Append(String.Format("Servidor: <b>{0}</b><br/>", HttpContext.Current.Server.MachineName)); } catch (Exception) { }; try { sb.Append(String.Format("URL: <b>{0}</b><br/>", HttpContext.Current.Request.Url.ToString())); } catch (Exception) { }; try { sb.Append(String.Format("Host: <b>{0}</b><br/>", HttpContext.Current.Request.UserHostName)); } catch (Exception) { }; try { sb.Append(String.Format("IP: <b>{0}</b><br/>", HttpContext.Current.Request.UserHostAddress)); } catch (Exception) { }; try { sb.Append(String.Format("Usuario: <b>{0}</b> ({1})<br/>", SSOHelper.CurrentIdentity.Fullname, SSOHelper.CurrentIdentity.Username)); } catch (Exception) { }; try { sb.Append(String.Format("¿Es Postback?: <b>{0}</b><br/>", ((Page)HttpContext.Current.Handler).IsPostBack)); } catch (Exception) { }; try { sb.Append(String.Format("¿Es Ajax?: <b>{0}</b><br/>", ScriptManager.GetCurrent((Page)HttpContext.Current.Handler).IsInAsyncPostBack)); } catch (Exception) { }; sb.Append("<br/><b>Source:</b> "); sb.Append(exception.Source.Replace("\n", "<br/>")); sb.Append("<br/><br/><b>Message:</b> "); sb.Append(exception.Message.Replace("\n", "<br/>")); sb.Append("<br/><br/><b>Stack Trace:</b> "); sb.Append(exception.StackTrace.Replace("\n", "<br/>")); sb.Append("<br/><br/><b>Otra información:</b> "); sb.Append(exception.ToString().Replace("\n", "<br/>")); //System.Net.Mail.SmtpClient SmtpClient = new System.Net.Mail.SmtpClient(mailServer); //System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("*****@*****.**", "[email protected],[email protected],[email protected]"); //message.Subject = String.Format("[Intranet] Servidor {0} | Error {1}", HttpContext.Current.Server.MachineName, (httpException == null ? "desconocido" : httpException.GetHttpCode().ToString())); //message.IsBodyHtml = true; //message.Body = sb.ToString(); //SmtpClient.Send(message); // Redirige sólo si no es ajax o un WebService bool redirect; try { //redirect = !(((Page)HttpContext.Current.Handler).IsPostBack && ScriptManager.GetCurrent((Page)HttpContext.Current.Handler).IsInAsyncPostBack) && !((Page)HttpContext.Current.Handler).Request.Path.ToLower().EndsWith(".asmx"); redirect = !(((Page)HttpContext.Current.Handler).IsPostBack && ScriptManager.GetCurrent((Page)HttpContext.Current.Handler).IsInAsyncPostBack); } catch (Exception) { redirect = true; } if (redirect) { try { SSOHelper.RedirectToErrorPage(500, 0, null); } catch (Exception) { throw HttpContext.Current.Server.GetLastError(); } } else { throw HttpContext.Current.Server.GetLastError(); } } }
internal static SSOModule FindByURL(Uri url) { /* Here's the basic pattern: * - Check the cache for the value, return if its available * - If the value is not in the cache, then implement a lock * - Inside the lock, check the cache again, you might have been blocked * - Perform the value look up and cache it * - Release the lock */ string urlString = url.ToString(); SortedDictionary <string, SSOModule> urls = SSOHelper.MembershipProvider.UseCache ? HttpContext.Current.Cache["Salud.Security.SSO.URLs"] as SortedDictionary <string, SSOModule> : null; if (urls != null && urls.ContainsKey(urlString)) { return(urls[urlString]); } else { lock (cacheLock) { // Busca de nuevo (ver explicación más arriba) urls = SSOHelper.MembershipProvider.UseCache ? HttpContext.Current.Cache["Salud.Security.SSO.URLs"] as SortedDictionary <string, SSOModule> : null; if (urls != null && urls.ContainsKey(urlString)) { return(urls[urlString]); } else { // Busca en el caché de módulos List <SSOModule> modules = SSOHelper.MembershipProvider.UseCache ? HttpContext.Current.Cache["Salud.Security.SSO.Modules"] as List <SSOModule> : null; if (modules == null) { using (Data.DataContext DataContext = SSOHelper.GetDataContext()) { var query = from module in DataContext.SSO_Modules join pages in DataContext.SSO_ModulePages on module.id equals pages.moduleId into joined from page in joined.DefaultIfEmpty() where module.SSO_Applications.url != null && module.SSO_Applications.url.Length > 0 orderby module.SSO_Applications.url + "/" + ((page == null) ? "" : page.page) descending /* Este orden permite que primero haga el matching en las URLS XX/YY/ZZ, luego en XX/YY, luego en XX, ... */ select new SSOModule(module.SSO_Applications, module.id, module.module, module.SSO_Applications.url + "/" + ((page == null) ? "" : page.page), module.name, module.description, module.@protected, module.interfase_image, module.interfase_priority, module.interfase_visible, module.groupId); modules = query.ToList(); HttpContext.Current.Cache["Salud.Security.SSO.Modules"] = modules; } } var result = modules.FirstOrDefault(r => r.MatchURL(url)); if (result == null) { // Busca un nivel más arriba (XX/YY/ZZ --> XX/YY) string s = String.Format("{0}{1}{2}{3}", url.Scheme, Uri.SchemeDelimiter, url.Authority, url.AbsolutePath); if (s.EndsWith("/")) { s = s.Substring(0, s.Length - 1); } s = s.Substring(0, s.LastIndexOf('/')); if (Uri.IsWellFormedUriString(s, UriKind.Absolute)) { result = SSOModule.FindByURL(new Uri(s)); } } if (urls == null) { urls = new SortedDictionary <string, SSOModule>(); } urls.Add(urlString, result); HttpContext.Current.Cache["Salud.Security.SSO.URLs"] = urls; return(result); } } } }
public override void InitializeRequest(System.Web.HttpContext context) { SSOHelper.Authenticate(); }
/// <summary> /// Busca un módulo en la aplicación /// </summary> /// <param name="url">URL del módulo</param> /// <returns></returns> public SSOModule FindModule(string url) { Uri uri = new Uri(String.Format("{0}://{1}{2}/{3}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.ApplicationPath, url)); return(SSOHelper.FindModule(uri)); }
public object GetApplicationMenu() { return(SSOHelper.GetApplicationMenuByEfector()); //se puso el ByEfector }