The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Global.asax.cs 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Web.Optimization;
  7. using System.Web.Routing;
  8. using Teknik.Models;
  9. using System.Data.Entity;
  10. using System.Web.Security;
  11. using Teknik.Areas.Users.Models;
  12. using Teknik.Areas.Error.Controllers;
  13. using System.Web.Helpers;
  14. using System.Diagnostics;
  15. using Teknik.Utilities;
  16. using System.Text;
  17. using Teknik.Areas.Users.Utility;
  18. namespace Teknik
  19. {
  20. public class MvcApplication : System.Web.HttpApplication
  21. {
  22. protected void Application_Start()
  23. {
  24. ViewEngines.Engines.Clear();
  25. ViewEngines.Engines.Add(new CustomRazorViewEngine());
  26. Database.SetInitializer(new MigrateDatabaseToLatestVersion<TeknikEntities, Migrations.Configuration>());
  27. AreaRegistration.RegisterAllAreas();
  28. AntiForgeryConfig.RequireSsl = true;
  29. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  30. RouteConfig.RegisterRoutes(RouteTable.Routes);
  31. BundleConfig.RegisterBundles(BundleTable.Bundles);
  32. }
  33. protected void Application_BeginRequest(object sender, EventArgs e)
  34. {
  35. // Start the generation time stopwatcher
  36. var stopwatch = new Stopwatch();
  37. HttpContext.Current.Items["Stopwatch"] = stopwatch;
  38. stopwatch.Start();
  39. }
  40. protected void Application_EndRequest(object sender, EventArgs e)
  41. {
  42. HttpContext context = HttpContext.Current;
  43. // Set the generation time in the header
  44. Stopwatch stopwatch = (Stopwatch)context.Items["Stopwatch"];
  45. stopwatch.Stop();
  46. TimeSpan ts = stopwatch.Elapsed;
  47. string elapsedTime = String.Format("{0} seconds", ts.TotalSeconds);
  48. context.Response.AppendHeader("GenerationTime", elapsedTime);
  49. // Allow this domain, or everything if local
  50. string origin = (Request.IsLocal) ? "*" : context.Request.Headers.Get("Origin");
  51. if (!string.IsNullOrEmpty(origin))
  52. {
  53. context.Response.AppendHeader("Access-Control-Allow-Origin", origin);
  54. }
  55. }
  56. protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
  57. {
  58. // We support both Auth Tokens and Cookie Authentication
  59. // Username and Roles for the current user
  60. string username = string.Empty;
  61. List<string> roles = new List<string>();
  62. bool hasAuthToken = false;
  63. if (Request != null)
  64. {
  65. if (Request.Headers.HasKeys())
  66. {
  67. string auth = Request.Headers["Authorization"];
  68. if (!string.IsNullOrEmpty(auth))
  69. {
  70. string[] parts = auth.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  71. string type = string.Empty;
  72. string value = string.Empty;
  73. if (parts.Length > 0)
  74. {
  75. type = parts[0].ToLower();
  76. }
  77. if (parts.Length > 1)
  78. {
  79. value = parts[1];
  80. }
  81. using (TeknikEntities entities = new TeknikEntities())
  82. {
  83. // Get the user information based on the auth type
  84. switch (type)
  85. {
  86. case "basic":
  87. KeyValuePair<string, string> authCreds = StringHelper.ParseBasicAuthHeader(value);
  88. bool tokenValid = UserHelper.UserTokenCorrect(entities, authCreds.Key, authCreds.Value);
  89. if (tokenValid)
  90. {
  91. // it's valid, so let's update it's Last Used date
  92. UserHelper.UpdateTokenLastUsed(entities, authCreds.Key, authCreds.Value, DateTime.Now);
  93. // Set the username
  94. username = authCreds.Key;
  95. }
  96. break;
  97. default:
  98. break;
  99. }
  100. }
  101. }
  102. }
  103. }
  104. if (FormsAuthentication.CookiesSupported == true && !hasAuthToken)
  105. {
  106. if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
  107. {
  108. //let us take out the username now
  109. username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
  110. }
  111. }
  112. // Create the new user if we found one from the supplied auth info
  113. if (!string.IsNullOrEmpty(username))
  114. {
  115. using (TeknikEntities entities = new TeknikEntities())
  116. {
  117. User user = UserHelper.GetUser(entities, username);
  118. // Grab all their roles
  119. foreach (Group grp in user.Groups)
  120. {
  121. foreach (Role role in grp.Roles)
  122. {
  123. if (!roles.Contains(role.Name))
  124. {
  125. roles.Add(role.Name);
  126. }
  127. }
  128. }
  129. }
  130. HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
  131. new System.Security.Principal.GenericIdentity(username, "Forms"), roles.ToArray());
  132. }
  133. }
  134. protected void Application_Error(object sender, EventArgs e)
  135. {
  136. // Get the last exception
  137. Exception exception = Server.GetLastError();
  138. // Clear the response
  139. Response.Clear();
  140. HttpException httpException = exception as HttpException;
  141. RouteData routeData = new RouteData();
  142. routeData.DataTokens.Add("namespaces", new[] { typeof(ErrorController).Namespace });
  143. routeData.DataTokens.Add("area", "Error");
  144. routeData.Values.Add("controller", "Error");
  145. if (httpException == null)
  146. {
  147. routeData.Values.Add("action", "Exception");
  148. }
  149. else //It's an Http Exception, Let's handle it.
  150. {
  151. switch (httpException.GetHttpCode())
  152. {
  153. case 401:
  154. // Unauthorized.
  155. routeData.Values.Add("action", "Http401");
  156. break;
  157. case 403:
  158. // Forbidden.
  159. routeData.Values.Add("action", "Http403");
  160. break;
  161. case 404:
  162. // Page not found.
  163. routeData.Values.Add("action", "Http404");
  164. break;
  165. case 500:
  166. // Server error.
  167. routeData.Values.Add("action", "Http500");
  168. break;
  169. // Here you can handle Views to other error codes.
  170. // I choose a General error template
  171. default:
  172. routeData.Values.Add("action", "General");
  173. break;
  174. }
  175. }
  176. // Pass exception details to the target error View.
  177. routeData.Values.Add("exception", exception);
  178. // Clear the error on server.
  179. Server.ClearError();
  180. // Avoid IIS7 getting in the middle
  181. Response.TrySkipIisCustomErrors = true;
  182. // If it is an Ajax request, we should respond with Json data, otherwise redirect
  183. if (new HttpRequestWrapper(Request).IsAjaxRequest())
  184. {
  185. string jsonResult = string.Empty;
  186. if (httpException == null)
  187. {
  188. jsonResult = Json.Encode(new { error = new { type = "Exception", message = exception.GetFullMessage(true) } });
  189. }
  190. else
  191. {
  192. jsonResult = Json.Encode(new { error = new { type = "Http", statuscode = httpException.GetHttpCode(), message = exception.GetFullMessage(true) } });
  193. }
  194. Response.Write(jsonResult);
  195. }
  196. else
  197. {
  198. // Call target Controller and pass the routeData.
  199. IController errorController = new ErrorController();
  200. errorController.Execute(new RequestContext(
  201. new HttpContextWrapper(Context), routeData));
  202. }
  203. }
  204. }
  205. }