public override async Task Invoke(IOwinContext context)
        {
            Func<IDictionary<string, object>, object> func;
            if (_config.TryGetValue(context.Request.Path, out func))
            {
                try
                {
                    var result = func(context.Request.ToDatabag()) ?? new { };
                    context.Response.Write(result.ToJsonString());

                    await Next.Invoke(context);
                }
                catch (Exception e)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    var jsonString = new { exception = e.ToString() }.ToJsonString();
                    context.Response.Write(jsonString);
                }
            }
            else
            {
                // Returns 404
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            }
        }
Example #2
0
		private static async Task UpgradeToWebSockets(RavenDBOptions options, IOwinContext context, Func<Task> next)
		{
			var accept = context.Get<Action<IDictionary<string, object>, Func<IDictionary<string, object>, Task>>>("websocket.Accept");
			if (accept == null)
			{
				// Not a websocket request
				await next();
				return;
			}

			WebSocketsTransport webSocketsTrasport = WebSocketTransportFactory.CreateWebSocketTransport(options, context);

			if (webSocketsTrasport != null)
			{
				if (await webSocketsTrasport.TrySetupRequest())
				{
					accept(new Dictionary<string, object>()
					{
						{"websocket.ReceiveBufferSize", 256},
						{"websocket.Buffer", webSocketsTrasport.PreAllocatedBuffer},
						{"websocket.KeepAliveInterval", WebSocket.DefaultKeepAliveInterval}
					}, webSocketsTrasport.Run);
				}
			}
		}
 public AuthenticationController(
     OwinEnvironmentService owin,
     IViewService viewService, 
     IUserService userService, 
     IdentityServerOptions idSvrOptions, 
     IClientStore clientStore, 
     IEventService eventService,
     ILocalizationService localizationService,
     SessionCookie sessionCookie, 
     MessageCookie<SignInMessage> signInMessageCookie,
     MessageCookie<SignOutMessage> signOutMessageCookie,
     LastUserNameCookie lastUsernameCookie,
     AntiForgeryToken antiForgeryToken)
 {
     this.context = new OwinContext(owin.Environment);
     this.viewService = viewService;
     this.userService = userService;
     this.options = idSvrOptions;
     this.clientStore = clientStore;
     this.eventService = eventService;
     this.localizationService = localizationService;
     this.sessionCookie = sessionCookie;
     this.signInMessageCookie = signInMessageCookie;
     this.signOutMessageCookie = signOutMessageCookie;
     this.lastUsernameCookie = lastUsernameCookie;
     this.antiForgeryToken = antiForgeryToken;
 }
 private Task SignInAsAlice(IOwinContext context)
 {
     context.Authentication.SignIn(
         new AuthenticationProperties(),
         new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")));
     return Task.FromResult<object>(null);
 }
        public override Task Invoke(IOwinContext context)
        {
            string header;
            switch (_xFrameOptions)
            {
                case XFrameOptions.Deny:
                    header = XFrameOptionsConstants.Deny;
                    break;

                case XFrameOptions.Sameorigin:
                    header = XFrameOptionsConstants.Sameorigin;
                    break;

                case XFrameOptions.AllowFrom:
                    header = string.Format(XFrameOptionsConstants.AllowFrom, _uri);
                    break;

                default:
                    header = XFrameOptionsConstants.Sameorigin;
                    break;
            }

            var headers = context.Response.Headers;
            if (headers.ContainsKey(XFrameOptionsConstants.Header))
            {
                headers[XFrameOptionsConstants.Header] = header;
            }
            else
            {
                headers.Append(XFrameOptionsConstants.Header, header);
            }

            return Next.Invoke(context);
        }
 /// <summary>
 /// Initializes a <see cref="DoYouBuzzAuthenticatedContext"/>
 /// </summary>
 /// <param name="context">The OWIN environment</param>
 /// <param name="userId">DoYouBuzz user ID</param>
 /// <param name="accessToken">DoYouBuzz access token</param>
 /// <param name="accessTokenSecret">DoYouBuzz access token secret</param>
 public DoYouBuzzAuthenticatedContext(IOwinContext context, string userId, string accessToken, string accessTokenSecret)
     : base(context)
 {
     UserId = userId;
     AccessToken = accessToken;
     AccessTokenSecret = accessTokenSecret;
 }
        /// <summary>
        /// Adopts protocol terms into owin environment.
        /// </summary>
        private void PopulateEnvironment()
        {
            var headers = _protocolStream.Headers;
            _owinContext = new OwinContext();
            _responseHeaders = _owinContext.Response.Headers;

            var headersAsDict = headers.ToDictionary(header => header.Key, header => new[] { header.Value }, StringComparer.OrdinalIgnoreCase);
            _owinContext.Environment[CommonOwinKeys.RequestHeaders] = headersAsDict;

            var owinRequest = _owinContext.Request;
            var owinResponse = _owinContext.Response;

            owinRequest.Method = headers.GetValue(CommonHeaders.Method);

            var path = headers.GetValue(CommonHeaders.Path);
            owinRequest.Path = path.StartsWith(@"/") ? new PathString(path) : new PathString(@"/" + path);

            owinRequest.CallCancelled = CancellationToken.None;

            owinRequest.Host = new HostString(headers.GetValue(CommonHeaders.Authority));
            owinRequest.PathBase = PathString.Empty;
            owinRequest.QueryString = QueryString.Empty;
            owinRequest.Body = Stream.Null;
            owinRequest.Protocol = Protocols.Http2;
            owinRequest.Scheme = headers.GetValue(CommonHeaders.Scheme) == Uri.UriSchemeHttp ? Uri.UriSchemeHttp : Uri.UriSchemeHttps;

            owinResponse.Body = new ResponseStream(_protocolStream, StartResponse);
        }
Example #8
0
		private async Task GetRoleDetails(IOwinContext context)
		{
			var key = new RoleKey(context.GetRouteValue("key"));
			var role = _collectionsReadModel.Roles.Single(r => r.Key == key);

			await context.WriteJson(role, _settings);
		}
Example #9
0
 private async Task InvokeNext(IOwinContext context)
 {
     if (Next != null)
     {
         await Next.Invoke(context);
     }
 }
 public static async Task RankingsAsync(IOwinContext context, NuGetSearcherManager searcherManager, ResponseWriter responseWriter)
 {
     await responseWriter.WriteResponseAsync(
         context,
         HttpStatusCode.OK,
         jsonWriter => ServiceInfoImpl.Rankings(jsonWriter, searcherManager));
 }
Example #11
0
        public override Task Invoke(IOwinContext context)
        {
            var dispatcher = _routes.FindDispatcher(context.Request.Path.Value);
            
            if (dispatcher == null)
            {
                return Next.Invoke(context);
            }

            foreach (var filter in _authorizationFilters)
            {
                if (!filter.Authorize(context.Environment))
                {
                    context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
                    return Task.FromResult(false);
                }
            }

            var dispatcherContext = new RequestDispatcherContext(
                _appPath,
                _storage,
                context.Environment,
                dispatcher.Item2);

            return dispatcher.Item1.Dispatch(dispatcherContext);
        }
Example #12
0
        public static async Task WriteResponseAsync(IOwinContext context, HttpStatusCode statusCode, Action<JsonWriter> writeContent)
        {
            /*
             * If an exception is thrown when building the response body, the exception must be handled before returning
             * a 200 OK (and presumably return a 500 Internal Server Error). If this approach becomes a memory problem,
             * we can write directly to the response stream. However, we must be sure to a) have proper validation to
             * avoid service exceptions (which is never a sure thing) or b) be okay with returning 200 OK on service
             * exceptions. Another approach could also separate "do business logic" with "build response body". Since
             * most exceptions will likely happen during the "do business logic" step, this would reduce the change of
             * a 200 OK on service exception. However, this means that the whole result of the business logic is in
             * memory.
             */
            var content = new MemoryStream();
            WriteToStream(content, writeContent);
            content.Position = 0;

            // write the response
            context.Response.StatusCode = (int)statusCode;
            context.Response.Headers.Add("Pragma", new[] { "no-cache" });
            context.Response.Headers.Add("Cache-Control", new[] { "no-cache" });
            context.Response.Headers.Add("Expires", new[] { "0" });
            var callback = context.Request.Query["callback"];
            if (string.IsNullOrEmpty(callback))
            {
                context.Response.ContentType = "application/json";
                await content.CopyToAsync(context.Response.Body);
            }
            else
            {
                context.Response.ContentType = "application/javascript";
                await context.Response.WriteAsync($"{callback}(");
                await content.CopyToAsync(context.Response.Body);
                await context.Response.WriteAsync(")");
            }
        }
 public async override Task Invoke(IOwinContext context)
 {
     context.Set(OriginalStreamKey, context.Response.Body);
     context.Response.Body = new StreamWrapper(context.Response.Body, InspectStatusCode, context);
     await Next.Invoke(context);
     
     StatusCodeAction action;
     string link;
     int statusCode = context.Response.StatusCode;
     bool? replace = context.Get<bool?>(ReplacementKey);
     if (!replace.HasValue)
     {
         // Never evaluated, no response sent yet.
         if (options.StatusCodeActions.TryGetValue(statusCode, out action)
             && links.TryGetValue(statusCode, out link)
             && action != StatusCodeAction.Ignore)
         {
             await SendKitten(context, link);
         }
     }
     else if (replace.Value == true)
     {
         if (links.TryGetValue(statusCode, out link))
         {
             await SendKitten(context, link);
         }
     }
 }
Example #14
0
 private void PrintCurrentIntegratedPipelineStage(IOwinContext context, string msg)
 {
     var currentIntegratedpipelineStage = HttpContext.Current.CurrentNotification;
     context.Get<TextWriter>("host.TraceOutput").WriteLine(
         "Current IIS event: " + currentIntegratedpipelineStage
         + " Msg: " + msg);
 }
        public static void Apply(this CommandResult commandResult, IOwinContext context)
        {
            if (commandResult == null)
            {
                throw new ArgumentNullException("commandResult");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.Response.ContentType = commandResult.ContentType;
            context.Response.StatusCode = (int)commandResult.HttpStatusCode;

            if (commandResult.Location != null)
            {
                context.Response.Headers["Location"] = commandResult.Location.OriginalString;
            }

            if (commandResult.Content != null)
            {
                using (var writer = new StreamWriter(context.Response.Body, Encoding.UTF8, 1024, true))
                {
                    writer.Write(commandResult.Content);
                }
            }
        }
        public override Task Invoke(IOwinContext context)
        {
            Trace.WriteLine("Invoke GetReceivePackMiddleware");

            var service = context.Request.Query["service"] ?? String.Empty;
            if (context.Request.Path.Value.EndsWith("/info/refs") && service.Equals("git-receive-pack"))
            {
                context.Response.Headers.Add("Expires", new[] { DateTime.Now.ToString("R") });
                context.Response.Headers.Add("Pragma", new[] { "no-cache" });
                context.Response.Headers.Add("Cache-Control", new[] { "no-cache, max-age=0, must-revalidate" });
                context.Response.Headers.Add("Content-Type", new[] { "application/x-git-receive-pack-advertisement" });

                //var process = Process.Start("git", string.Format("receive-pack --stateless-rpc --advertise-refs {0}repo", _options.BasePath));
                //process.WaitForExit(1000);
                //var output = process.StandardOutput;

                //var body = output.ReadToEnd();

                //var packet = "# service=git-receive-pack\n";
                //var length = packet.Length + 4;
                //var hex = "0123456789abcdef";
                //var prefix = hex[hex.Length - 1 >> 12] & 0xf;
                //prefix = prefix + hex[length - 1 >> 8] & 0xf;
                //prefix = prefix + hex[length - 1 >> 4] & 0xf;
                //prefix = prefix + hex[length - 1] & 0xf;
                //var body = string.Format("#{0}#{1}}}0000", prefix, packet);

                var body = "00900000000000000000000000000000000000000000 capabilities^{}  report-status delete-refs side-band-64k quiet ofs-delta agent=git/1.8.0.msysgit.00000";
                context.Response.Write(body);

                return Globals.CompletedTask;
            }

            return Next.Invoke(context);
        }
        public override Task Invoke(IOwinContext context)
        {
            var rep = context.Response;
            rep.StatusCode = 404;

            //判断调用次数,避免无限递归
            var invokeTimes = context.Get<Int32>(INVOKE_TIMES);
            invokeTimes++;
            if (invokeTimes > 1 || String.IsNullOrEmpty(RewritePath))
            {
                String msg = "404 Not Found";
                rep.ContentLength = msg.Length;
                return rep.WriteAsync(msg);
            }
            context.Set(INVOKE_TIMES, invokeTimes);

            context.Set<String>("owin.RequestPath", RewritePath);
            OwinMiddleware first = server.GetFirstMiddlewareInstance();
            if (first == null)
                throw new ArgumentException($"Middleware '{this.GetType().FullName};{this.GetType().Assembly.GetName().Name}' must not be the first middleware,and recommand to be set to the last one.");

            //清理OwinContext
            foreach (var cleaner in server.GetMiddlewares<IOwinContextCleaner>())
                cleaner.Clean(context);

            return first.Invoke(context);
        }
 public override async Task Invoke(IOwinContext context)
 {
     if (context.Request.Method == "POST" && context.Request.Path.Value.ToLower().EndsWith("/account/login"))
     {
         var form = await context.Request.ReadFormAsync();
         var userName = form["username"];
         var password = form["password"];
         if (!string.IsNullOrWhiteSpace(userName))
         {
             var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationType);
             identity.AddClaim(new Claim(ClaimTypes.Name, userName));
             if (userName == "admin")
                 identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
             context.Authentication.SignIn(identity);
             context.Response.StatusCode = 200;
             context.Response.ReasonPhrase = "Authorized";
         }
         else
         {
             context.Authentication.SignOut();
             context.Response.StatusCode = 401;
             context.Response.ReasonPhrase = "Unauthorized";
         }
         return;
     }
     await Next.Invoke(context);
 }
        public static void Apply(this CommandResult commandResult, IOwinContext context)
        {
            if (commandResult == null)
            {
                throw new ArgumentNullException("commandResult");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.Response.ContentType = commandResult.ContentType;
            context.Response.StatusCode = (int)commandResult.HttpStatusCode;

            if (commandResult.Location != null)
            {
                context.Response.Headers["Location"] = commandResult.Location.OriginalString;
            }

            if (commandResult.Content != null)
            {
                context.Response.Write(commandResult.Content);
            }
        }
        public async override Task Invoke(IOwinContext context)
        {
            var _requset = context.Request;
            var _gzipStream = new MemoryStream();

            Byte[] _unzip;
            Byte[] _zip;

            //如果再 Http Header 條件符合下列項目才進行解壓縮作業
            if (_requset.Headers["Content-Type"] == "application/gzip")
            {
                await _requset.Body.CopyToAsync(_gzipStream);
                _gzipStream.Position = 0;

                //如果包含壓縮內容,進行解壓縮
                _zip = _gzipStream.ToArray();
                _unzip = this.GZipUncompress(_zip);

                //將解壓縮的 Byte 陣列匯入到 HttpRequest 內文
                _requset.Body = new MemoryStream(_unzip);
                _requset.Body.Position = 0;

                //修改 Content-Type 為 application/json
                _requset.Headers.Remove("Content-Type");
                _requset.Headers.Add("Content-Type", new String[] { @"application/json" });
            }

            await Next.Invoke(context);
        }
        public static CategoryManager Create(IdentityFactoryOptions<CategoryManager> options, IOwinContext context)
        {
            ICategoryDataAccess categoryData = context.Get<SqlConnection>().As<ICategoryDataAccess>();
            CategoryManager manager = new CategoryManager(categoryData);

            return manager;
        }
 internal OpenIdConnectValidateClientRedirectUriContext(
     IOwinContext context,
     OpenIdConnectServerOptions options,
     OpenIdConnectMessage authorizationRequest)
     : base(context, options, authorizationRequest)
 {
 }
        async Task InvokeGET(IOwinContext context)
        {
            switch (context.Request.Path.Value)
            {
                case "/":
                    {
                        context.Response.Write("OK");
                        context.Response.StatusCode = (int)HttpStatusCode.OK;
                        break;
                    }
                case "/claims":
                    {
                        JArray result = new JArray();
                        foreach (Claim claim in ClaimsPrincipal.Current.Claims)
                        {
                            JObject obj = new JObject();
                            obj.Add("type", claim.Type);
                            obj.Add("value", claim.Value);
                            result.Add(obj);
                        }

                        await context.Response.WriteAsync(result.ToString());
                        context.Response.ContentType = "application/json";
                        context.Response.StatusCode = (int)HttpStatusCode.OK;
                        break;
                    }
                default:
                    {
                        await context.Response.WriteAsync("NotFound");
                        context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                        break;
                    }
            }
        }
		/// <summary>
		/// Processes the HTTP request for controllers.
		/// </summary>
		/// <param name="containerProvider">The DI container provider.</param>
		/// <param name="context">The context.</param>
		/// <returns></returns>
		public Task ProcessRequest(IDIContainerProvider containerProvider, IOwinContext context)
		{
			var result = _controllersProcessor.ProcessControllers(containerProvider, context);

			switch (result)
			{
				case ControllersProcessorResult.Ok:
					return _pageProcessor.ProcessPage(containerProvider, context);

				case ControllersProcessorResult.Http401:
					context.Response.StatusCode = 401;
					_redirector.SetLoginReturnUrlFromCurrentUri();
					break;

				case ControllersProcessorResult.Http403:
					context.Response.StatusCode = 403;
					break;

				case ControllersProcessorResult.Http404:
					context.Response.StatusCode = 404;
					break;
			}

			return Task.Delay(0);
		}
        async Task Invoke(IOwinContext context)
        {
            string error = null;

            try
            {
                switch (context.Request.Method)
                {
                    case "GET":
                        await InvokeGET(context);
                        break;
                    case "POST":
                        await InvokePOST(context);
                        break;
                    default:
                        await context.Response.WriteAsync("NotFound");
                        context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                        break;
                }
            }
            catch (Exception e)
            {
                error = e.Message;
            }

            if (error != null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            }
        }
        public Task Invoke(IOwinContext context, Func<Task> next)
        {
            var content = new StringBuilder();
            content.Append("The Urchin Server failed to initialize correctly on ");
            content.Append(Environment.MachineName);
            content.Append(".\n");
            content.Append("There is a configuration error in Urchin, or a failure in something that Urchin depends on.\n\n");
            content.Append("Check the error log for more detailed information.\n\n");
            if (_exception != null)
            {
                content.Append("The exception that was caught was ");
                content.Append(_exception.GetType().FullName);
                content.Append("\n");
                content.Append(_exception.Message);
                content.Append("\n");
                if (_exception.StackTrace != null)
                {
                    content.Append(_exception.StackTrace);
                    content.Append("\n");
                }
                var inner = _exception.InnerException;
                while (inner != null)
                {
                    content.Append("The inner exception was ");
                    content.Append(inner.GetType().FullName);
                    content.Append("\n");
                    content.Append(inner.Message);
                    content.Append("\n");
                    inner = inner.InnerException;
                }
            }

            context.Response.ContentType = "text/plain";
            return context.Response.WriteAsync(content.ToString());
        }
 void IOwinContextCleaner.Clean(IOwinContext context)
 {
     if (context.Environment.ContainsKey(QOMVC_PLUGIN_KEY))
         context.Environment.Remove(QOMVC_PLUGIN_KEY);
     if (context.Environment.ContainsKey(QOMVC_PATH_KEY))
         context.Environment.Remove(QOMVC_PATH_KEY);
 }
        public override async Task Invoke(IOwinContext context)
        {
            var handler = _handlerSet.FindOrDefault(context.Request.Path.ToString());
            if (handler != null)
            {
                try
                {
                    var result = handler.Handler(context.Request.ToThermometerQuestion()) ?? new { };
                    context.Response.WriteAsJson(result);

                    await Next.Invoke(context);
                }
                catch (Exception e)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    var result = new { exception = e.ToString() };
                    context.Response.WriteAsJson(result);
                }
            }
            else
            {
                // Returns 404
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            }
        }
        private async Task<bool> CheckToken(IOwinContext context)
        {
            if (!_options.RequireBearerToken)
            {
                return true;
            }

            if (!string.IsNullOrWhiteSpace(_options.BearerTokenValue))
            {
                const string bearerTypeToken = "Bearer";

                var authorizationHeaders = context.Request.Headers.GetValues("Authorization");
                if (authorizationHeaders != null && authorizationHeaders.Count > 0)
                {
                    var header = authorizationHeaders[0].Trim();
                    if (header.StartsWith(bearerTypeToken))
                    {
                        var value = header.Substring(bearerTypeToken.Length).Trim();
                        if (!value.Equals(_options.BearerTokenValue))
                        {
                            context.Response.ContentType = "text/plain";
                            context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                            await context.Response.WriteAsync("Forbidden");
                            return false;
                        }
                        return true;
                    }
                }
            }
            context.Response.ContentType = "text/plain";
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            await context.Response.WriteAsync("Unauthorized");
            return false;
        }
Example #30
0
        public override async Task Invoke(IOwinContext context)
        {
            Exception exception = null;
            var stopWatch = Stopwatch.StartNew();

            try
            {
                await Next.Invoke(context).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                exception = e;
            }
            finally
            {
                stopWatch.Stop();

                if (exception == null)
                {
                    _logger.Verbose($"API {context.Request.Method} {stopWatch.Elapsed.TotalSeconds:0.00} sec {(HttpStatusCode)context.Response.StatusCode} {context.Request.Uri.GetLeftPart(UriPartial.Path)}");
                }
                else
                {
                    _logger.Error(exception, $"API {context.Request.Method} {stopWatch.Elapsed.TotalSeconds:0.00} sec {(HttpStatusCode) context.Response.StatusCode} {context.Request.Uri.GetLeftPart(UriPartial.Path)}");
                }
            }

            if (exception != null)
            {
                throw exception;
            }
        }
Example #31
0
        /// <summary>
        /// Generates an HTML view for a directory.
        /// </summary>
        public virtual Task GenerateContentAsync(IOwinContext context, IEnumerable <IFileInfo> contents)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (contents == null)
            {
                throw new ArgumentNullException("contents");
            }

            context.Response.ContentType = Constants.TextHtmlUtf8;

            if (Helpers.IsHeadMethod(context.Request.Method))
            {
                // HEAD, no response body
                return(Constants.CompletedTask);
            }

            PathString requestPath = context.Request.PathBase + context.Request.Path;

            var builder = new StringBuilder();

            builder.AppendFormat(
                @"<!DOCTYPE html>
<html lang=""{0}"">", CultureInfo.CurrentUICulture.TwoLetterISOLanguageName);

            builder.AppendFormat(@"
<head>
  <title>{0} {1}</title>", HtmlEncode(Resources.HtmlDir_IndexOf), HtmlEncode(requestPath.Value));

            builder.Append(@"
  <style>
    body {
        font-family: ""Segoe UI"", ""Segoe WP"", ""Helvetica Neue"", 'RobotoRegular', sans-serif;
        font-size: 14px;}
    header h1 {
        font-family: ""Segoe UI Light"", ""Helvetica Neue"", 'RobotoLight', ""Segoe UI"", ""Segoe WP"", sans-serif;
        font-size: 28px;
        font-weight: 100;
        margin-top: 5px;
        margin-bottom: 0px;}
    #index {
        border-collapse: separate; 
        border-spacing: 0; 
        margin: 0 0 20px; }
    #index th {
        vertical-align: bottom;
        padding: 10px 5px 5px 5px;
        font-weight: 400;
        color: #a0a0a0;
        text-align: center; }
    #index td { padding: 3px 10px; }
    #index th, #index td {
        border-right: 1px #ddd solid;
        border-bottom: 1px #ddd solid;
        border-left: 1px transparent solid;
        border-top: 1px transparent solid;
        box-sizing: border-box; }
    #index th:last-child, #index td:last-child {
        border-right: 1px transparent solid; }
    #index td.length, td.modified { text-align:right; }
    a { color:#1ba1e2;text-decoration:none; }
    a:hover { color:#13709e;text-decoration:underline; }
  </style>
</head>
<body>
  <section id=""main"">");
            builder.AppendFormat(@"
    <header><h1>{0} <a href=""/"">/</a>", HtmlEncode(Resources.HtmlDir_IndexOf));

            string cumulativePath = "/";

            foreach (var segment in requestPath.Value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries))
            {
                cumulativePath = cumulativePath + segment + "/";
                builder.AppendFormat(@"<a href=""{0}"">{1}/</a>",
                                     HtmlEncode(cumulativePath), HtmlEncode(segment));
            }

            builder.AppendFormat(CultureInfo.CurrentUICulture,
                                 @"</h1></header>
    <table id=""index"" summary=""{0}"">
    <thead>
      <tr><th abbr=""{1}"">{1}</th><th abbr=""{2}"">{2}</th><th abbr=""{3}"">{4}</th></tr>
    </thead>
    <tbody>",
                                 HtmlEncode(Resources.HtmlDir_TableSummary),
                                 HtmlEncode(Resources.HtmlDir_Name),
                                 HtmlEncode(Resources.HtmlDir_Size),
                                 HtmlEncode(Resources.HtmlDir_Modified),
                                 HtmlEncode(Resources.HtmlDir_LastModified));

            foreach (var subdir in contents.Where(info => info.IsDirectory))
            {
                builder.AppendFormat(@"
      <tr class=""directory"">
        <td class=""name""><a href=""{0}/"">{0}/</a></td>
        <td></td>
        <td class=""modified"">{1}</td>
      </tr>",
                                     HtmlEncode(subdir.Name),
                                     HtmlEncode(subdir.LastModified.ToString(CultureInfo.CurrentCulture)));
            }

            foreach (var file in contents.Where(info => !info.IsDirectory))
            {
                builder.AppendFormat(@"
      <tr class=""file"">
        <td class=""name""><a href=""{0}"">{0}</a></td>
        <td class=""length"">{1}</td>
        <td class=""modified"">{2}</td>
      </tr>",
                                     HtmlEncode(file.Name),
                                     HtmlEncode(file.Length.ToString("n0", CultureInfo.CurrentCulture)),
                                     HtmlEncode(file.LastModified.ToString(CultureInfo.CurrentCulture)));
            }

            builder.Append(@"
    </tbody>
    </table>
  </section>
</body>
</html>");
            string data = builder.ToString();

            byte[] bytes = Encoding.UTF8.GetBytes(data);
            context.Response.ContentLength = bytes.Length;
            return(context.Response.WriteAsync(bytes));
        }
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));

            // Konfiguruj logikę weryfikacji nazw użytkowników
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Konfiguruj logikę weryfikacji haseł
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Konfiguruj ustawienia domyślne blokady użytkownika
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Zarejestruj dostawców uwierzytelniania dwuetapowego. W przypadku tej aplikacji kod weryfikujący użytkownika jest uzyskiwany przez telefon i pocztą e-mail
            // Możesz zapisać własnego dostawcę i dołączyć go tutaj.
            manager.RegisterTwoFactorProvider("Kod — telefon", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Twój kod zabezpieczający: {0}"
            });
            manager.RegisterTwoFactorProvider("Kod — e-mail", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Kod zabezpieczeń",
                BodyFormat = "Twój kod zabezpieczający: {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
Example #33
0
 public static ApplicationRoleManager Create(IdentityFactoryOptions <ApplicationRoleManager> options, IOwinContext context)
 {
     return(new ApplicationRoleManager(new RoleStore <IdentityRole>(context.Get <ApplicationDbContext>())));
 }
Example #34
0
 public static ApplicationSignInManager Create(IdentityFactoryOptions <ApplicationSignInManager> options,
                                               IOwinContext context)
 {
     return(new ApplicationSignInManager(context.GetUserManager <ApplicationUserManager>(),
                                         context.Authentication));
 }
Example #35
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {0}"
            });

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
Example #36
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };
            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
 public DiscoveryEndpointController(IdentityServerOptions options, IScopeStore scopes, IOwinContext context, ISigningKeyService keyService, CustomGrantValidator customGrants)
 {
     _options      = options;
     _scopes       = scopes;
     _context      = context;
     _keyService   = keyService;
     _customGrants = customGrants;
 }
Example #38
0
        //創建使用者 帳號與密碼驗證規則
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            #region
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));
            // 設定使用者名稱的驗證邏輯
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false, //允許使用者名稱只有數字
                RequireUniqueEmail             = true   //mail須唯一
            };

            // 設定密碼的驗證邏輯
            manager.PasswordValidator = new PasswordValidator {
                RequiredLength          = 6,     //密碼最小長度
                RequireNonLetterOrDigit = true,  //必須包含特殊字元
                RequireDigit            = true,  //必須包含數字
                RequireLowercase        = true,  //必須包含小寫
                RequireUppercase        = false, //必須包含大寫 true
            };

            // 設定使用者鎖定詳細資料
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // 註冊雙因素驗證提供者。此應用程式使用手機和電子郵件接收驗證碼以驗證使用者
            // 您可以撰寫專屬提供者,並將它外掛到這裡。
            manager.RegisterTwoFactorProvider("電話代碼", new PhoneNumberTokenProvider <ApplicationUser> {
                MessageFormat = "您的安全碼為 {0}"
            });
            manager.RegisterTwoFactorProvider("電子郵件代碼", new EmailTokenProvider <ApplicationUser> {
                Subject    = "安全碼",
                BodyFormat = "您的安全碼為 {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);

            #endregion
        }
Example #39
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));

            // Configure la lógica de validación de nombres de usuario
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Configure la lógica de validación de contraseñas
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Configurar valores predeterminados para bloqueo de usuario
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Registre proveedores de autenticación en dos fases. Esta aplicación usa los pasos Teléfono y Correo electrónico para recibir un código para comprobar el usuario
            // Puede escribir su propio proveedor y conectarlo aquí.
            manager.RegisterTwoFactorProvider("Código telefónico", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Su código de seguridad es {0}"
            });
            manager.RegisterTwoFactorProvider("Código de correo electrónico", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Código de seguridad",
                BodyFormat = "Su código de seguridad es {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
Example #40
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));

            // 配置用户名的验证逻辑
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // 配置密码的验证逻辑
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // 配置用户锁定默认值
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // 注册双重身份验证提供程序。此应用程序使用手机和电子邮件作为接收用于验证用户的代码的一个步骤
            // 你可以编写自己的提供程序并将其插入到此处。
            manager.RegisterTwoFactorProvider("电话代码", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "你的安全代码是 {0}"
            });
            manager.RegisterTwoFactorProvider("电子邮件代码", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "安全代码",
                BodyFormat = "你的安全代码是 {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
Example #41
0
        public static UserAppManager Create(IdentityFactoryOptions <UserAppManager> options, IOwinContext context)
        {
            var appcontext = context.Get <Context>();

            var usuarioManager = new UserAppManager(new UserStore <Usuario>(appcontext));

            return(usuarioManager);
        }
Example #42
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }

            //var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
            //IdentityResult result = null;
            //if (!roleManager.RoleExists("Admin"))
            //    result = roleManager.Create(new IdentityRole("Admin"));
            //if (!roleManager.RoleExists("Page Editor"))
            //    result = roleManager.Create(new IdentityRole("Page Editor"));

            //ApplicationUser user = manager.FindByName("*****@*****.**");
            //if (!manager.IsInRole(user.Id, "Admin"))
            //    result = manager.AddToRole(user.Id, "Admin");
            //if (!manager.IsInRole(user.Id, "Page Editor"))
            //    result = manager.AddToRole(user.Id, "Page Editor");
            //user.Mailbox = "123456789";
            //result = manager.Update(user);

            //user = manager.FindByName("*****@*****.**");
            //if (!manager.IsInRole(user.Id, "Admin"))
            //    roleResult = manager.AddToRole(user.Id, "Admin");
            //if (!manager.IsInRole(user.Id, "Page Editor"))
            //    roleResult = manager.AddToRole(user.Id, "Page Editor");

            //var user = manager.FindByName("*****@*****.**");
            //if (!manager.IsInRole(user.Id, "Admin"))
            //    manager.AddToRole(user.Id, "Admin");
            //if (!manager.IsInRole(user.Id, "Page Editor"))
            //    manager.AddToRole(user.Id, "Page Editor");

            return(manager);
        }
Example #43
0
 public static FlightRoleManager Create(IdentityFactoryOptions<FlightRoleManager> options, IOwinContext context)
 {
     return new FlightRoleManager(new
     RoleStore<FlightRole>(context.Get<FlightIdentityDbContext>()));
 }
Example #44
0
 public CallContext(IOwinRequest request, IOwinContext httpContext, EndpointConfiguration endpoint)
 {
     _httpContext = httpContext;
     _endpoint    = endpoint;
 }
Example #45
0
        private static UserManager <ApplicationUser> CreateManager(IdentityFactoryOptions <UserManager <ApplicationUser> > options, IOwinContext context)
        {
            var userStore   = new UserStore <ApplicationUser>(context.Get <MinhvhDbContext>());
            var owinManager = new UserManager <ApplicationUser>(userStore);

            return(owinManager);
        }
 public override Task Invoke(IOwinContext context)
 {
     throw new InvalidOperationException();
 }
Example #47
0
        public static MyUserManager Create(IdentityFactoryOptions <MyUserManager> options, IOwinContext context)
        {
#if DEBUG
            Debug.WriteLine("MyUserManager Create");
#endif

            var manager = new MyUserManager(new MyUserStore(context.Get <MyDbContext>()));

#if DEBUG
            if (manager != null)
            {
                Debug.WriteLine("manager is not null!");
            }
            else
            {
                Debug.WriteLine("manager is NOT null");
            }
#endif

            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = Convert.ToInt32(ConfigurationManager.AppSettings["RequiredLength"]),
                RequireNonLetterOrDigit = Convert.ToBoolean(ConfigurationManager.AppSettings["RequireNonLetterOrDigit"]),
                RequireDigit            = Convert.ToBoolean(ConfigurationManager.AppSettings["RequireDigit"]),
                RequireLowercase        = Convert.ToBoolean(ConfigurationManager.AppSettings["RequireLowercase"]),
                RequireUppercase        = Convert.ToBoolean(ConfigurationManager.AppSettings["RequireUppercase"])
            };

            // Если истино, учётка блокируется по умолчанию после созданаия
            manager.UserLockoutEnabledByDefault = Convert.ToBoolean(ConfigurationManager.AppSettings["UserLockoutEnabledByDefault"]);
            // Максимальное число попыток ввода пароля, после чего учётка блокируется
            manager.MaxFailedAccessAttemptsBeforeLockout = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFailedAccessAttemptsBeforeLockout"]);
            // Количество времени в минутах, когда учётка остаётся блокированной
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"]));
            // Признак будет ли блокирована учётка
            manager.LockoutEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings["LockoutEnabled"]);
            // Максимальный период времени, после которого надо менять пароль
            manager.MaxPeriodForChangePassword = Convert.ToInt32(ConfigurationManager.AppSettings["MaxPeriodForChangePassword"]);
            // Максимальный период времени (в днях), когда учётка будет блокированной, если не было входа в систему
            manager.MaxPeriodSignin = Convert.ToInt32(ConfigurationManager.AppSettings["MaxPeriodSignin"]);
            //Проверка на использование старый паролей, при вводе нового пароля
            manager.CheckUsedPasswordEnabled =
                Convert.ToBoolean(ConfigurationManager.AppSettings["CheckUsedPasswordEnabled"]);
            // Глубина проверки старых паролей
            manager.MaxUsedPassword = Convert.ToInt32(ConfigurationManager.AppSettings["MaxUsedPassword"]);

            return(manager);
        }
Example #48
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));

            // Настройка логики проверки имен пользователей
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Настройка логики проверки паролей
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Настройка параметров блокировки по умолчанию
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Регистрация поставщиков двухфакторной проверки подлинности. Для получения кода проверки пользователя в данном приложении используется телефон и сообщения электронной почты
            // Здесь можно указать собственный поставщик и подключить его.
            manager.RegisterTwoFactorProvider("Код, полученный по телефону", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Ваш код безопасности: {0}"
            });
            manager.RegisterTwoFactorProvider("Код из сообщения", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Код безопасности",
                BodyFormat = "Ваш код безопасности: {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
Example #49
0
        public override async Task Invoke(IOwinContext context)
        {
            throw new NotImplementedException("TBD");

            await this.Next.Invoke(context);
        }
Example #50
0
        private (bool responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason, bool responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason, bool responseIsOk) GetResponseStatus(IOwinContext context)
        {
            string statusCode = context.Response.StatusCode.ToString(CultureInfo.InvariantCulture);
            bool   responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason = statusCode.StartsWith("5", StringComparison.InvariantCultureIgnoreCase);
            bool   responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason = statusCode.StartsWith("4", StringComparison.InvariantCultureIgnoreCase);

            return(responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason, responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason, responseIsOk : !responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason && !responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason);
        }
Example #51
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));

            // Configurer la logique de validation pour les noms d'utilisateur
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Configurer la logique de validation pour les mots de passe
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Configurer les valeurs par défaut du verrouillage de l'utilisateur
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Inscrire les fournisseurs d'authentification à 2 facteurs. Cette application utilise le téléphone et les e-mails comme procédure de réception de code pour confirmer l'utilisateur
            // Vous pouvez écrire votre propre fournisseur et le connecter ici.
            manager.RegisterTwoFactorProvider("Code téléphonique ", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Votre code de sécurité est {0}"
            });
            manager.RegisterTwoFactorProvider("Code d'e-mail", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Code de sécurité",
                BodyFormat = "Votre code de sécurité est {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
        {
            var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<MedicalInstitutionsContext>()));
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };

            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromSeconds(30);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            manager.RegisterTwoFactorProvider("Code from message", new EmailTokenProvider<ApplicationUser>
            {
                Subject = "Security code",
                BodyFormat = "Your security code: {0}"
			});
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = 
                    new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
Example #53
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IScopeStatusManager scopeStatusManager = dependencyResolver.Resolve <IScopeStatusManager>();

            ILogger logger = dependencyResolver.Resolve <ILogger>();

            try
            {
                context.Response.OnSendingHeaders((state) =>
                {
                    // Create a backup header for reason phrase + enhance its value if possible.
                    // We're able to modify reason phrase and other headers in this callback and in catch part of this class only.
                    // We may not change response headers after await Next.Invoke(context); Codes after Next.Invoke gets invoked after OnSendingHeaders.
                    string reasonPhrase = context.Response.ReasonPhrase;
                    // It can gets filled by
                    // 1- WebApi's routing, when no routing gets matched with value "Not Found".
                    // 2- In catch part of this class with either "KnownError" & "UnknownError" values.
                    // 3- In ExceptionHandlerFilterAttribute class with either "KnownError" & "UnknownError" values.
                    // 4- Other codes! It might be empty too!

                    bool responseIsOk = GetResponseStatus(context).responseIsOk;

                    if (!responseIsOk)
                    {
                        if (string.IsNullOrEmpty(reasonPhrase))
                        {
                            reasonPhrase = BitMetadataBuilder.UnknownError;
                        }
                        else if (!string.Equals(reasonPhrase, BitMetadataBuilder.KnownError, StringComparison.CurrentCultureIgnoreCase) && !string.Equals(reasonPhrase, BitMetadataBuilder.UnknownError, StringComparison.CurrentCultureIgnoreCase))
                        {
                            reasonPhrase = $"{BitMetadataBuilder.UnknownError}:{reasonPhrase}";
                        }
                    }
                    if (!responseIsOk)
                    {
                        context.Response.ReasonPhrase = reasonPhrase;
                        if (!context.Response.Headers.ContainsKey("Reason-Phrase"))
                        {
                            context.Response.Headers.Add("Reason-Phrase", new[] { reasonPhrase });
                        }
                    }
                }, state: null);

                await Next.Invoke(context);

                var status = GetResponseStatus(context);
                if (status.responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason ||
                    status.responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason)
                {
                    string reasonPhrase = context.Response.ReasonPhrase;

                    scopeStatusManager.MarkAsFailed(reasonPhrase);

                    logger.AddLogData("ResponseStatusCode", context.Response.StatusCode);
                    logger.AddLogData("ResponseReasonPhrase", reasonPhrase);

                    if (status.responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason || reasonPhrase == BitMetadataBuilder.KnownError)
                    {
                        await logger.LogWarningAsync("Response has failed status code because of some client side reason");
                    }
                    else if (status.responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason)
                    {
                        await logger.LogFatalAsync("Response has failed status code because of some server side reason");
                    }
                }
                else if (!scopeStatusManager.WasSucceeded())
                {
                    await logger.LogFatalAsync($"Scope was failed: {scopeStatusManager.FailureReason}");
                }
                else
                {
                    scopeStatusManager.MarkAsSucceeded();

                    if (logger.Policy == LogPolicy.Always)
                    {
                        await logger.LogInformationAsync("Response succeded.");
                    }
                }
            }
            catch (Exception exp)
            {
                if (scopeStatusManager.WasSucceeded())
                {
                    scopeStatusManager.MarkAsFailed(exp.Message);
                }
                await logger.LogExceptionAsync(exp, "Request-Execution-Exception");

                string statusCode = context.Response.StatusCode.ToString(CultureInfo.InvariantCulture);
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason = statusCode.StartsWith("5", StringComparison.InvariantCultureIgnoreCase);
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason = statusCode.StartsWith("4", StringComparison.InvariantCultureIgnoreCase);
                if (responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason == false && responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason == false)
                {
                    IExceptionToHttpErrorMapper exceptionToHttpErrorMapper = dependencyResolver.Resolve <IExceptionToHttpErrorMapper>();
                    context.Response.StatusCode   = Convert.ToInt32(exceptionToHttpErrorMapper.GetStatusCode(exp), CultureInfo.InvariantCulture);
                    context.Response.ReasonPhrase = exceptionToHttpErrorMapper.GetReasonPhrase(exp);
                    await context.Response.WriteAsync(exceptionToHttpErrorMapper.GetMessage(exp), context.Request.CallCancelled);
                }
                throw;
            }
        }
Example #54
0
 public static bool MapDomain(this IOwinContext ctx, string hostname)
 {
     return(ctx?.Request.Headers.Get("Host").Equals(hostname) ?? false);
 }
Example #55
0
 public override Task Invoke(IOwinContext context)
 {
     LifetimeScope = context.GetAutofacLifetimeScope();
     return(Next.Invoke(context));
 }
Example #56
0
 public static bool MapFolder(this IOwinContext ctx, string folder)
 {
     return(ctx?.Request.Uri.LocalPath.StartsWith(folder) ?? false);
 }
Example #57
0
        public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
        {
            ///It is based on the same context as the ApplicationUserManager
            var appRoleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<SleepWellContext>()));

            return appRoleManager;
        }