PageRenderTime 1766ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/Solution/Core/SocialAuthHttpModule.cs

http://socialauth-net.googlecode.com/
C# | 198 lines | 87 code | 26 blank | 85 comment | 35 complexity | c643cad73d078f8b3f215af786fd0596 MD5 | raw file
  1. /*
  2. ===========================================================================
  3. Copyright (c) 2010 BrickRed Technologies Limited
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ===========================================================================
  20. */
  21. using System;
  22. using System.Collections.Generic;
  23. using System.Linq;
  24. using System.Text;
  25. using System.Web;
  26. using System.Web.Security;
  27. using System.Web.SessionState;
  28. using System.Security.Principal;
  29. using Brickred.SocialAuth.NET.Core.BusinessObjects;
  30. using System.Text.RegularExpressions;
  31. namespace Brickred.SocialAuth.NET.Core
  32. {
  33. class SocialAuthHttpModule : IHttpModule, IReadOnlySessionState
  34. {
  35. public void Dispose()
  36. {
  37. //throw new NotImplementedException();
  38. }
  39. //Hook our module to httprequest pipeline
  40. public void Init(HttpApplication context)
  41. {
  42. context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
  43. context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
  44. }
  45. private void context_AuthenticateRequest(object sender, EventArgs e)
  46. {
  47. ///*************************
  48. // * If Request is of type .sauth OR any type as specified in Config, allow and skip.
  49. // * If Request is of LoginURL, skip
  50. // * OTHERWISE:::::::::::::::::::::
  51. // * <<<<IF USER IS NOT LOGGED IN>>>
  52. // * If AuthenticationOption = SocialAuth
  53. // * Redirect in Priority - ConfigurationLoginURL, "LoginForm.sauth"
  54. // * If AuthenticationOption = FormsAuthentication
  55. // * Don't do anything. Let .NET handle it as per user's setting in Web.Config
  56. // * If AuthenticationOption = Everything Custom
  57. // * Don't do anything. User will put checking code on every page himself.
  58. // * **********************/
  59. //AUTHENTICATION_OPTION option = Utility.GetAuthenticationOption();
  60. //if (option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_CUSTOM_SCREEN || option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_SOCIALAUTH_SCREEN)
  61. //{
  62. // //block any .aspx page. Rest all is allowed.
  63. // //TODO: Better Implementation of this
  64. // if (VirtualPathUtility.GetExtension(HttpContext.Current.Request.RawUrl) != ".aspx")
  65. // return;
  66. // //If requested page is login URL only, allow it
  67. // string currentUrl = HttpContext.Current.Request.Url.AbsolutePath;
  68. // string loginurl = Utility.GetSocialAuthConfiguration().Authentication.LoginUrl;
  69. // loginurl = string.IsNullOrEmpty(loginurl) ? "socialauth/loginform.sauth" : loginurl;
  70. // if (currentUrl.EndsWith(loginurl))
  71. // return;
  72. // //If Url is pointing to a .aspx page, authorize it!
  73. // HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
  74. // HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
  75. // if (cookie != null)
  76. // {
  77. // HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(FormsAuthentication.Decrypt(cookie.Value)), null);
  78. // }
  79. // else
  80. // {
  81. // //User is not logged in
  82. // SocialAuthUser.RedirectToLoginPage();
  83. // }
  84. //}
  85. }
  86. protected void context_PreRequestHandlerExecute(object sender, EventArgs e)
  87. {
  88. /*************************
  89. * If Request is of type .sauth OR any type as specified in Config, allow and skip.
  90. * If Request is of LoginURL, skip
  91. * OTHERWISE:::::::::::::::::::::
  92. * <<<<IF USER IS NOT LOGGED IN>>>
  93. * If AuthenticationOption = SocialAuth
  94. * Redirect in Priority - ConfigurationLoginURL, "LoginForm.sauth"
  95. * If AuthenticationOption = FormsAuthentication
  96. * Don't do anything. Let .NET handle it as per user's setting in Web.Config
  97. * If AuthenticationOption = Everything Custom
  98. * Don't do anything. User will put checking code on every page himself.
  99. * **********************/
  100. AUTHENTICATION_OPTION option = Utility.GetAuthenticationOption();
  101. if (option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_CUSTOM_SCREEN || option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_SOCIALAUTH_SCREEN)
  102. {
  103. //block any .aspx page. Rest all is allowed.
  104. //TODO: Better Implementation of this
  105. string requestUrlExtension = VirtualPathUtility.GetExtension(HttpContext.Current.Request.RawUrl);
  106. string urlWithoutParameters = (new Uri(HttpContext.Current.Request.Url.ToString()).GetLeftPart(UriPartial.Path)).ToLower();
  107. string host = (new Uri(HttpContext.Current.Request.GetBaseURL())).ToString().ToLower();
  108. if (requestUrlExtension != ".aspx" && !string.IsNullOrEmpty(requestUrlExtension))
  109. return;
  110. //Check for excludes
  111. //Allowed Folders
  112. if (!string.IsNullOrEmpty(Utility.GetSocialAuthConfiguration().Allow.Folders))
  113. {
  114. string[] foldersToExclude = Utility.GetSocialAuthConfiguration().Allow.Folders.Split(new char[] { '|' });
  115. foreach (string folderName in foldersToExclude)
  116. if (urlWithoutParameters.Contains(host + (host.EndsWith("/") ? "" : "/") + folderName))
  117. return;
  118. }
  119. //Allowed Files
  120. if (!string.IsNullOrEmpty(Utility.GetSocialAuthConfiguration().Allow.Files))
  121. {
  122. string[] filesToExclude = Utility.GetSocialAuthConfiguration().Allow.Files.Split(new char[] { '|' });
  123. foreach (string fileName in filesToExclude)
  124. if (Regex.IsMatch(urlWithoutParameters, "/" + fileName.ToLower() + "$"))
  125. return;
  126. }
  127. //If requested page is login URL only, allow it
  128. string currentUrl = HttpContext.Current.Request.Url.AbsolutePath;
  129. string loginurl = Utility.GetSocialAuthConfiguration().Authentication.LoginUrl;
  130. loginurl = string.IsNullOrEmpty(loginurl) ? "socialauth/loginform.sauth" : loginurl;
  131. if (currentUrl.ToLower().EndsWith(loginurl.ToLower()))
  132. return;
  133. //If Url is pointing to a .aspx page, authorize it!
  134. HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
  135. HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
  136. if (cookie != null)
  137. {
  138. HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(FormsAuthentication.Decrypt(cookie.Value)), null);
  139. }
  140. else
  141. {
  142. //User is not logged in
  143. SocialAuthUser.RedirectToLoginPage();
  144. }
  145. if (HttpContext.Current.Session != null)
  146. if (SocialAuthUser.IsLoggedIn() && HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] == null)
  147. {
  148. FormsAuthenticationTicket ticket =
  149. new FormsAuthenticationTicket(SessionManager.GetUserSessionGUID().ToString(), false, HttpContext.Current.Session.Timeout);
  150. string EncryptedTicket = FormsAuthentication.Encrypt(ticket);
  151. cookie = new HttpCookie(FormsAuthentication.FormsCookieName, EncryptedTicket);
  152. HttpContext.Current.Response.Cookies.Add(cookie);
  153. }
  154. }
  155. //Often, Forms Cookie persist even where there is no connection. To avoid that!!
  156. if (HttpContext.Current.Session != null)
  157. if (SessionManager.ConnectionsCount == 0)
  158. if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null && Utility.GetAuthenticationOption() != AUTHENTICATION_OPTION.FORMS_AUTHENTICATION)
  159. if (SessionManager.GetUserSessionGUID().ToString() != FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name)
  160. SocialAuthUser.Disconnect();
  161. if (HttpContext.Current.ApplicationInstance.IsSTSaware())
  162. if (HttpContext.Current.Session != null)
  163. if (SocialAuthUser.IsLoggedIn())
  164. if (SocialAuthUser.GetCurrentUser().GetProfile() != null)
  165. SocialAuthUser.SetClaims();
  166. }
  167. }
  168. }