Exemplo n.º 1
0
		public void Can_send_ResponseStream_test_with_Custom_Header()
		{
			var mockResponse = new HttpResponseMock();

			var customText = "<h1>Custom Stream</h1>";
			var customTextBytes = customText.ToUtf8Bytes();
			var ms = new MemoryStream();
			ms.Write(customTextBytes, 0, customTextBytes.Length);


            var httpResult = new HttpResult(ms, MimeTypes.Html)
            {
				Headers =
				{
					{"X-Custom","Header"}
				}
			};

            var reponseWasAutoHandled = mockResponse.WriteToResponse(httpResult, MimeTypes.Html);

			Assert.That(reponseWasAutoHandled, Is.True);

			var writtenString = mockResponse.GetOutputStreamAsString();
			Assert.That(writtenString, Is.EqualTo(customText));
			Assert.That(mockResponse.Headers["X-Custom"], Is.EqualTo("Header"));
		}
 public object Any(PlainText request) 
 {
     string contentType = "text/plain";
     var response = new HttpResult(request.Text, contentType);
     if(request.SetContentTypeBrutally) {
         response.ContentType = contentType;
     }
     return response;
 }
        public object Get(PartialFromMemory request)
        {
            var customText = "123456789012345678901234567890";
            var customTextBytes = customText.ToUtf8Bytes();
            var ms = new MemoryStream();
            ms.Write(customTextBytes, 0, customTextBytes.Length);

            var httpResult = new HttpResult(ms, "audio/mpeg");
            return httpResult;
        }
Exemplo n.º 4
0
		public object Get(FileUpload request)
		{
			if (request.RelativePath.IsNullOrEmpty())
				throw new ArgumentNullException("RelativePath");

			var filePath = ("~/" + request.RelativePath).MapProjectPath();
			if (!File.Exists(filePath))
				throw new FileNotFoundException(request.RelativePath);

			var result = new HttpResult(new FileInfo(filePath));
			return result;
		}
Exemplo n.º 5
0
		public object Get(FileUpload request)
		{
			if (request.RelativePath.IsNullOrEmpty())
				throw new ArgumentNullException("RelativePath");

			var filePath = ("~/" + request.RelativePath).MapHostAbsolutePath();
			if (!File.Exists(filePath))
				throw new FilterInvalidBodyAccessException(request.RelativePath);

			var result = new HttpResult(new FileInfo(filePath));
			return result;
		}
Exemplo n.º 6
0
		public void Can_send_ResponseText_test_with_StatusDescription()
		{
            var mockRequest = new MockHttpRequest { ContentType = MimeTypes.Json };
			var mockRequestContext = new HttpRequestContext(mockRequest, null, new object());
			var mockResponse = new HttpResponseMock();

			var customStatus = "Custom Status Description";

			var httpResult = new HttpResult(System.Net.HttpStatusCode.Accepted, customStatus) {
				RequestContext = mockRequestContext
			};

            var reponseWasAutoHandled = mockResponse.WriteToResponse(httpResult, MimeTypes.Html);

			Assert.That(reponseWasAutoHandled, Is.True);

			var statusDesc = mockResponse.StatusDescription;
			Assert.That(mockResponse.StatusCode, Is.EqualTo((int)System.Net.HttpStatusCode.Accepted));
			Assert.That(statusDesc, Is.EqualTo(customStatus));
		}
Exemplo n.º 7
0
		public void Can_send_ResponseText_test_with_Custom_Header()
		{
			var mockResponse = new HttpResponseMock();

			var customText = "<h1>Custom Text</h1>";

            var httpResult = new HttpResult(customText, MimeTypes.Html)
            {
				Headers =
				{
					{"X-Custom","Header"}
				}
			};

            var reponseWasAutoHandled = mockResponse.WriteToResponse(httpResult, MimeTypes.Html);

			Assert.That(reponseWasAutoHandled, Is.True);

			var writtenString = mockResponse.GetOutputStreamAsString();
			Assert.That(writtenString, Is.EqualTo(customText));
			Assert.That(mockResponse.Headers["X-Custom"], Is.EqualTo("Header"));
		}
Exemplo n.º 8
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens = Init(authService, ref session, request);

            var httpReq = authService.RequestContext.Get<IHttpRequest>();
            var isOpenIdRequest = !httpReq.GetParam("openid.mode").IsNullOrEmpty();

            if (!isOpenIdRequest)
            {
                var openIdUrl = httpReq.GetParam("OpenIdUrl") ?? base.AuthRealm;
                if (openIdUrl.IsNullOrEmpty())
                    throw new ArgumentException("'OpenIdUrl' is required a required field");

                try
                {
                    using (var openid = CreateOpenIdRelyingParty(OpenIdApplicationStore))
                    {
                        var openIdRequest = openid.CreateRequest(openIdUrl);

                        AddAttributeExchangeExtensions(openIdRequest);

                        // This is where you would add any OpenID extensions you wanted
                        // to include in the authentication request.
                        openIdRequest.AddExtension(CreateClaimsRequest(httpReq));

                        // Send your visitor to their Provider for authentication.
                        var openIdResponse = openIdRequest.RedirectingResponse;
                        var contentType = openIdResponse.Headers[HttpHeaders.ContentType];
                        var httpResult = new HttpResult(openIdResponse.ResponseStream, contentType) {
                            StatusCode = openIdResponse.Status,
                            StatusDescription = "Moved Temporarily",
                        };
                        foreach (string header in openIdResponse.Headers)
                        {
                            httpResult.Headers[header] = openIdResponse.Headers[header];
                        }
                        // Save the current session to keep the ReferrerUrl available (similar to Facebook provider)
                        authService.SaveSession(session, SessionExpiry);
                        return httpResult;
                    }
                }
                catch (ProtocolException ex)
                {
                    Log.Error("Failed to login to {0}".Fmt(openIdUrl), ex);
                    return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"));
                }
            }

            if (isOpenIdRequest)
            {
                using (var openid = CreateOpenIdRelyingParty(OpenIdApplicationStore))
                {
                    var response = openid.GetResponse();
                    if (response != null)
                    {
                        switch (response.Status)
                        {
                            case AuthenticationStatus.Authenticated:

                                var authInfo = CreateAuthInfo(response);

                                // Use FormsAuthentication to tell ASP.NET that the user is now logged in,
                                // with the OpenID Claimed Identifier as their username.
                                session.IsAuthenticated = true;
                                authService.SaveSession(session, SessionExpiry);
                                OnAuthenticated(authService, session, tokens, authInfo);

                                //Haz access!
                                return authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1"));

                            case AuthenticationStatus.Canceled:
                                return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "ProviderCancelled"));

                            case AuthenticationStatus.Failed:
                                return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"));
                        }
                    }
                }
            }

            //Shouldn't get here
            return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"));
        }
 public object Get(PartialFromText request)
 {
     const string customText = "123456789012345678901234567890";
     var httpResult = new HttpResult(customText, "text/plain");
     return httpResult;
 }
        public void Can_use_fileStream()
        {
            byte[] fileBytes = uploadedTextFile.ReadFully();
            string fileText = Encoding.ASCII.GetString(fileBytes);

            "File content size {0}".Print(fileBytes.Length);
            "File content is {0}".Print(fileText);

            var mockRequest = new HttpRequestMock();
            var mockResponse = new HttpResponseMock();
            mockRequest.Headers.Add("Range", "bytes=6-8");

            var httpResult = new HttpResult(uploadedTextFile, "audio/mpeg");

            bool reponseWasAutoHandled = mockResponse.WriteToResponse(mockRequest, httpResult);
            Assert.That(reponseWasAutoHandled, Is.True);

            string writtenString = mockResponse.GetOutputStreamAsString();
            Assert.That(writtenString, Is.EqualTo(fileText.Substring(6, 3)));

            Assert.That(mockResponse.Headers["Content-Range"], Is.EqualTo("bytes 6-8/33"));
            Assert.That(mockResponse.Headers["Content-Length"], Is.EqualTo(writtenString.Length.ToString()));
            Assert.That(mockResponse.Headers["Accept-Ranges"], Is.EqualTo("bytes"));
            Assert.That(mockResponse.StatusCode, Is.EqualTo(206));
        }
        public void Can_seek_from_middle_to_middle()
        {
            var mockRequest = new HttpRequestMock();
            mockRequest.Headers.Add("Range", "bytes=3-5");
            var mockResponse = new HttpResponseMock();

            string customText = "1234567890";
            byte[] customTextBytes = customText.ToUtf8Bytes();
            var ms = new MemoryStream();
            ms.Write(customTextBytes, 0, customTextBytes.Length);


            var httpResult = new HttpResult(ms, "audio/mpeg");

            bool reponseWasAutoHandled = mockResponse.WriteToResponse(mockRequest, httpResult);
            Assert.That(reponseWasAutoHandled, Is.True);

            string writtenString = mockResponse.GetOutputStreamAsString();
            Assert.That(writtenString, Is.EqualTo("456"));

            Assert.That(mockResponse.Headers["Content-Range"], Is.EqualTo("bytes 3-5/10"));
            Assert.That(mockResponse.Headers["Content-Length"], Is.EqualTo(writtenString.Length.ToString()));
            Assert.That(mockResponse.Headers["Accept-Ranges"], Is.EqualTo("bytes"));
            Assert.That(mockResponse.StatusCode, Is.EqualTo(206));
        }
        public void Can_respond_to_non_range_requests_with_200_OK_response()
        {
            var mockRequest = new HttpRequestMock();
            var mockResponse = new HttpResponseMock();

            string customText = "1234567890";
            byte[] customTextBytes = customText.ToUtf8Bytes();
            var ms = new MemoryStream();
            ms.Write(customTextBytes, 0, customTextBytes.Length);

            var httpResult = new HttpResult(ms, "audio/mpeg");            

            bool reponseWasAutoHandled = mockResponse.WriteToResponse(mockRequest, httpResult);
            Assert.That(reponseWasAutoHandled, Is.True);

            string writtenString = mockResponse.GetOutputStreamAsString();
            Assert.That(writtenString, Is.EqualTo(customText));

            Assert.That(mockResponse.Headers["Content-Range"], Is.Null);
            Assert.That(mockResponse.Headers["Accept-Ranges"], Is.EqualTo("bytes"));
            Assert.That(mockResponse.StatusCode, Is.EqualTo(200));
        }
Exemplo n.º 13
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens = this.Init(authService, ref session, request);

            var authServer = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri(this.AuthorizeUrl), TokenEndpoint = new Uri(this.AccessTokenUrl) };
            var authClient = new WebServerClient(authServer, this.ConsumerKey) {
                ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(this.ConsumerSecret),
            };

            var authState = ProcessUserAuthorization(authClient, authServer, authService);
            if (authState == null)
            {
                try
                {
                    var authReq = authClient.PrepareRequestUserAuthorization(this.Scopes, new Uri(this.CallbackUrl));
                    var authContentType = authReq.Headers[HttpHeaders.ContentType];
                    var httpResult = new HttpResult(authReq.ResponseStream, authContentType) { StatusCode = authReq.Status, StatusDescription = "Moved Temporarily" };
                    foreach (string header in authReq.Headers)
                    {
                        httpResult.Headers[header] = authReq.Headers[header];
                    }

                    foreach (string name in authReq.Cookies)
                    {
                        var cookie = authReq.Cookies[name];

                        if (cookie != null)
                        {
                            httpResult.SetSessionCookie(name, cookie.Value, cookie.Path);
                        }
                    }

                    authService.SaveSession(session, this.SessionExpiry);
                    return httpResult;
                }
                catch (ProtocolException ex)
                {
                    Log.Error("Failed to login to {0}".Fmt(this.Provider), ex);
                    return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"));
                }
            }

            var accessToken = authState.AccessToken;
            if (accessToken != null)
            {
                try
                {
                    tokens.AccessToken = accessToken;
                    tokens.RefreshToken = authState.RefreshToken;
                    tokens.RefreshTokenExpiry = authState.AccessTokenExpirationUtc;
                    session.IsAuthenticated = true;
                    var authInfo = this.CreateAuthInfo(accessToken);
                    this.OnAuthenticated(authService, session, tokens, authInfo);
                    return authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1"));
                }
                catch (WebException we)
                {
                    var statusCode = ((HttpWebResponse)we.Response).StatusCode;
                    if (statusCode == HttpStatusCode.BadRequest)
                    {
                        return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed"));
                    }
                }
            }

            return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "RequestTokenFailed"));
        }
Exemplo n.º 14
0
		public void Can_handle_null_HttpResult_StatusDescription()
		{
			var mockResponse = new HttpResponseMock();

			var httpResult = new HttpResult();
			httpResult.StatusDescription = null;

            mockResponse.WriteToResponse(httpResult, MimeTypes.Html);

			Assert.IsNotNull(mockResponse.StatusDescription);
		}
        public void Can_seek_from_beginning_to_end()
        {
            var mockRequest = new MockHttpRequest();
            var mockResponse = new MockHttpResponse();

            mockRequest.Headers[HttpHeaders.Range] = "bytes=0";

            string customText = "1234567890";
            byte[] customTextBytes = customText.ToUtf8Bytes();
            var ms = new MemoryStream();
            ms.Write(customTextBytes, 0, customTextBytes.Length);

            var httpResult = new HttpResult(ms, "audio/mpeg");

            bool reponseWasAutoHandled = mockResponse.WriteToResponse(mockRequest, httpResult);
            Assert.That(reponseWasAutoHandled, Is.True);

            string writtenString = mockResponse.ReadAsString();
            Assert.That(writtenString, Is.EqualTo(customText));

            Assert.That(mockResponse.Headers["Content-Range"], Is.EqualTo("bytes 0-9/10"));
            Assert.That(mockResponse.Headers["Content-Length"], Is.EqualTo(writtenString.Length.ToString()));
            Assert.That(mockResponse.Headers["Accept-Ranges"], Is.EqualTo("bytes"));
            Assert.That(mockResponse.StatusCode, Is.EqualTo(206));
        }