Пример #1
0
        private async Task RespondGetSong(OwinResponse response, SongStorage storage, string name)
        {
            bool success = true;

            try
            {
                using (var entry = await storage.GetAsync(name, CancellationToken.None))
                {
                    response.SetHeader("Content-Type", "text/xml");
                    if (entry.LastModified.HasValue)
                    {
                        response.SetHeader("Last-Modified", entry.LastModified.Value.ToString("r"));
                    }
                    await entry.Stream.CopyToAsync(response.Body);
                }
            }
            catch (FileNotFoundException)
            {
                success = false;
            }
            catch (ArgumentException)
            {
                success = false;
            }

            if (!success)
            {
                await response.RespondNotFound();
            }
        }
        public void ApplyResponseHeaders()
        {
            if (!string.IsNullOrEmpty(_contentType))
            {
                _response.SetHeader(Constants.ContentType, _contentType);
            }

            _response.SetHeader("Last-Modified", _lastModifiedString);
            _response.SetHeader("ETag", _etag);
        }
Пример #3
0
 public static async Task RespondCompressedString(this OwinResponse response, string content, string contentType = "text/plain")
 {
     response.SetHeader("Content-Type", contentType + ";charset=utf-8");
     response.SetHeader("Content-Encoding", "gzip");
     using (var inStream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
     {
         using (GZipStream compressedStream = new GZipStream(response.Body, CompressionMode.Compress, true))
         {
             await inStream.CopyToAsync(compressedStream);
         }
     }
 }
Пример #4
0
        public Task Invoke(IDictionary <string, object> env)
        {
            var request  = new OwinRequest(env);
            var response = new OwinResponse(env);

            if (!request.Uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                var builder = new UriBuilder(request.Uri);
                builder.Scheme = "https";

                if (request.Uri.IsDefaultPort)
                {
                    builder.Port = -1;
                }

                response.SetHeader("Location", builder.ToString());
                response.StatusCode = 302;

                return(TaskAsyncHelper.Empty);
            }
            else
            {
                return(_next(env));
            }
        }
Пример #5
0
        public async Task Invoke(IDictionary <string, object> environment)
        {
            var request = new OwinRequest(environment);
            Uri uri     = request.Uri;

            // Create a stream for the host and port so we can send the request
            Stream stream = await _streamFactory.CreateStream(uri).ConfigureAwait(continueOnCapturedContext: false);

            var requestWriter = new StreamWriter(stream);

            // Request line
            requestWriter.WriteHttpLine("{0} {1} {2}", request.Method, uri.PathAndQuery, request.Protocol);

            // Write headers
            foreach (var header in request.Headers)
            {
                requestWriter.WriteHttpLine("{0}: {1}", header.Key, request.GetHeader(header.Key));
            }

            // End headers
            requestWriter.WriteHttpLine();

            if (request.Body == null)
            {
                // End request
                requestWriter.WriteHttpLine();
            }

            // Flush buffered content to the stream async
            await requestWriter.FlushAsync().ConfigureAwait(continueOnCapturedContext: false);

            if (request.Body != null)
            {
                // Copy the body to the request
                await request.Body.CopyToAsync(stream).ConfigureAwait(continueOnCapturedContext: false);
            }

            var response = new OwinResponse(environment);

            // Parse the response
            HttpParser.ParseResponse(stream, (protocol, statusCode, reasonPhrase) =>
            {
                response.Protocol     = protocol;
                response.StatusCode   = statusCode;
                response.ReasonPhrase = reasonPhrase;
            },
                                     (key, value) => response.SetHeader(key, value));

            // Set the body to the rest of the stream
            response.Body = stream;
        }
Пример #6
0
        public async Task Invoke(IDictionary <string, object> env)
        {
            object value;

            if (env.TryGetValue("server.User", out value))
            {
                var windowsPrincipal = value as WindowsPrincipal;
                if (windowsPrincipal != null && windowsPrincipal.Identity.IsAuthenticated)
                {
                    await _next(env);

                    var request  = new OwinRequest(env);
                    var response = new OwinResponse(env);

                    if (response.StatusCode == 401)
                    {
                        // We're going no add the identifier claim
                        var nameClaim = windowsPrincipal.FindFirst(ClaimTypes.Name);

                        // This is the domain name
                        string name = nameClaim.Value;

                        // If the name is something like DOMAIN\username then
                        // grab the name part
                        var parts = name.Split(new[] { '\\' }, 2);

                        string shortName = parts.Length == 1 ? parts[0] : parts[parts.Length - 1];

                        // REVIEW: Do we want to preserve the other claims?

                        // Normalize the claims here
                        var claims = new List <Claim>();
                        claims.Add(new Claim(ClaimTypes.NameIdentifier, name));
                        claims.Add(new Claim(ClaimTypes.Name, shortName));
                        claims.Add(new Claim(ClaimTypes.AuthenticationMethod, "Windows"));
                        var identity        = new ClaimsIdentity(claims, Constants.JabbRAuthType);
                        var claimsPrincipal = new ClaimsPrincipal(identity);

                        response.SignIn(claimsPrincipal);

                        response.StatusCode = 302;
                        response.SetHeader("Location", request.PathBase + request.Path);
                    }

                    return;
                }
            }

            await _next(env);
        }
Пример #7
0
        public async Task Invoke(IDictionary <string, object> env)
        {
            var httpRequest  = new Gate.Request(env);
            var httpResponse = new OwinResponse(env);

            string url;
            Uri    uri;

            if (!httpRequest.Query.TryGetValue("url", out url) ||
                String.IsNullOrEmpty(url) ||
                !Uri.TryCreate(url, UriKind.Absolute, out uri) ||
                !ImageContentProvider.IsValidImagePath(uri) ||
                !IsAuthenticated(env))
            {
                httpResponse.StatusCode = 404;
                return;
            }

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
                var response = (HttpWebResponse)await request.GetResponseAsync();

                if (!ImageContentProvider.IsValidContentType(response.ContentType) &&
                    response.ContentLength > _settings.ProxyImageMaxSizeBytes)
                {
                    httpResponse.StatusCode = 404;
                    return;
                }

                httpResponse.SetHeader("Content-Type", response.ContentType);
                httpResponse.StatusCode = (int)response.StatusCode;

                using (response)
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        await stream.CopyToAsync(httpResponse.Body);
                    }
                }
            }
            catch
            {
                httpResponse.StatusCode = 404;
            }
        }
Пример #8
0
        public async Task Invoke(IDictionary <string, object> env)
        {
            var httpRequest = new OwinRequest(env);

            if (!httpRequest.Path.StartsWith(_path))
            {
                await _next(env);

                return;
            }

            var httpResponse = new OwinResponse(env);

            var qs = new QueryStringCollection(httpRequest.QueryString);

            string url = qs["url"];

            Uri uri;

            if (String.IsNullOrEmpty(url) ||
                !ImageContentProvider.IsValidImagePath(url) ||
                !Uri.TryCreate(url, UriKind.Absolute, out uri))
            {
                httpResponse.StatusCode = 404;
                await TaskAsyncHelper.Empty;
                return;
            }

            var request = (HttpWebRequest)WebRequest.Create(url);

            request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
            var response = (HttpWebResponse)await request.GetResponseAsync();

            httpResponse.SetHeader("ContentType", response.ContentType);
            httpResponse.StatusCode = (int)response.StatusCode;

            using (response)
            {
                using (Stream stream = response.GetResponseStream())
                {
                    await stream.CopyToAsync(httpResponse.Body);
                }
            }
        }
Пример #9
0
 public static Task RespondString(this OwinResponse response, string content, string contentType = "text/plain")
 {
     response.SetHeader("Content-Type", contentType + ";charset=utf-8");
     return(response.WriteAsync(content));
 }
Пример #10
0
        public Task Invoke(IDictionary <string, object> env)
        {
            var request  = new OwinRequest(env);
            var response = new OwinResponse(env);

            var requestPath = Uri.UnescapeDataString(request.Path);

            var backgrounds = DataManager.ActualBackgroundStorage;

            if (requestPath.StartsWith("/backgrounds/"))
            {
                if (request.Method != "GET")
                {
                    return(response.RespondMethodNotAllowed());
                }

                var query = requestPath.Substring("/backgrounds".Length);

                if (query.EndsWith("/list"))
                {
                    string path = query.Substring(0, query.Length - "list".Length);
                    var    dir  = backgrounds.GetDirectory(path);

                    try
                    {
                        StringBuilder sb = new StringBuilder();
                        ListBackgroundEntries(dir, sb);

                        return(response.RespondString(sb.ToString()));
                    }
                    catch (FileNotFoundException)
                    {
                        return(response.RespondNotFound());
                    }
                }
                else if (query == "/listall")
                {
                    StringBuilder sb = new StringBuilder();
                    ListBackgroundEntries(backgrounds.Root, sb, true);
                    return(response.RespondString(sb.ToString()));
                }
                else
                {
                    bool preview = false;
                    if (query.EndsWith("/preview"))
                    {
                        preview = true;
                        query   = query.Substring(0, query.Length - "/preview".Length);
                    }

                    try
                    {
                        var file        = backgrounds.GetFile(query);
                        var contentType = file.MimeType;

                        if (!String.IsNullOrEmpty(contentType))
                        {
                            response.SetHeader("Content-Type", contentType);
                        }
                        return(response.RespondDownloaded(preview ? file.PreviewUri : file.Uri));
                    }
                    catch (FileNotFoundException)
                    {
                        return(response.RespondNotFound());
                    }
                }
            }
            else
            {
                return(next(env));
            }
        }
Пример #11
0
 public static void Redirect(this OwinResponse response, string location)
 {
     response.StatusCode = 302;
     response.SetHeader("Location", location);
 }