Inheritance: IHttpResult, IStreamWriter
        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, ContentType.Html)
            {
                Headers =
                {
                    {"X-Custom","Header"}
                }
            };

            var reponseWasAutoHandled = mockResponse.WriteToResponse(httpResult, ContentType.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;
        }
        public void Can_handle_null_HttpResult_StatusDescription()
        {
            var mockResponse = new HttpResponseMock();

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

            mockResponse.WriteToResponse(httpResult, ContentType.Html);

            Assert.IsNotNull(mockResponse.StatusDescription);
        }
		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;
		}
		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;
		}
        public void Can_send_ResponseText_test_with_StatusDescription()
        {
            var mockResponse = new HttpResponseMock();

            var customStatus = "Custom Status Description";

            var httpResult = new HttpResult(System.Net.HttpStatusCode.Accepted, customStatus);

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

            Assert.That(reponseWasAutoHandled, Is.True);

            var statusDesc = mockResponse.StatusDescription;
            Assert.That(mockResponse.StatusCode, Is.EqualTo(System.Net.HttpStatusCode.Accepted));
            Assert.That(statusDesc, Is.EqualTo(customStatus));
        }
		public object Get(DeployFileDto request)
		{
			if (!string.IsNullOrEmpty(request.Id))
			{
				var file = this._fileManager.GetFile(request.Id);
                if(request.RawData)
                {
                    var result = new HttpResult(_fileManager.GetFileDataStream(request.Id), "application/octet-stream");
                    result.Headers.Add("Content-Disposition", "attachment; filename=" + file.FileName);
                    return result;
                }
                else 
                {
				    return file;
                }
			}
			else
			{
				return this._fileManager.GetFileList();
			}
		}
        public void Can_send_ResponseText_test_with_Custom_Header()
        {
            var mockResponse = new HttpResponseMock();

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

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

            var reponseWasAutoHandled = mockResponse.WriteToResponse(httpResult, ContentType.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 HttpResult Post(CreateMessage request)
        {
            // POST does not support update
            //if (request.Id > 0)
            //    return new HttpResult(HttpStatusCode.NotFound, "POST does not support updating idividual messages.");

            //var id = request.Id;
            var ds = new DataStore();
            var id = ds.InsertMessage(request);

            var client = new EmailClient();
            var emailResult = client.Send(request);

            var response = new MessageResponse
            {
                Id = id,
                Success = true
            };

            if (emailResult.Success)
            {
                ds.InsertMessageStatus(id, 2);
            }
            else
            {
                ds.InsertMessageStatus(id, 3, emailResult.Message, emailResult.SmtpException);
                response.Result = emailResult.Message;
                response.Success = false;
            }

            var result = new HttpResult(response)
            {
                StatusCode = HttpStatusCode.Created,
                StatusDescription = RequestContext.AbsoluteUri.CombineWith(id)
            };

            return result;
        }
        public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
        {
            var tokens = Init(authService, ref session, request);

            var httpReq = authService.RequestContext.Get<IHttpRequest>();
            var httpMethod = httpReq.HttpMethod;
            if (httpMethod == HttpMethods.Post)
            {
                var openIdUrl = httpReq.GetParam("OpenIdUrl") ?? base.AuthRealm;
                if (openIdUrl.IsNullOrEmpty())
                    throw new ArgumentException("'OpenIdUrl' is required a required field");

                try
                {
                    using (var openid = new OpenIdRelyingParty())
                    {
                        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 (httpMethod == HttpMethods.Get)
            {
                using (var openid = new OpenIdRelyingParty())
                {
                    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"));
        }
Beispiel #12
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Auth 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.PostParameter(this.ConsumerSecret));
            IAuthorizationState authState;

            try
            {
                authState = authClient.ProcessUserAuthorization();
                //authState = authClient.ProcessUserAuthorization(new HttpRequestWrapper(HttpContext.Current.Request));
            }
            catch (ProtocolException ex)
            {
                Log.Error("Failed to login to {0}".Fmt(this.Provider), ex);
                return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "ProcessUserAuthorization"));
            }

            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"));
        }
 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));
        }
Beispiel #17
0
        public object Get(DownloadLicense downloadRequest)
        {
            var cacheKey = UrnId.Create<Model.License>("IssueToken", downloadRequest.Token.ToString());
            var license = cacheClient.Get<Portable.Licensing.License>(cacheKey);

            if (license == null)
                return new HttpResult(HttpStatusCode.NotFound);

            var responseStream = new MemoryStream();
            license.Save(responseStream);

            var response = new HttpResult(responseStream, "application/xml");
            response.Headers[HttpHeaders.ContentDisposition] = "attachment; filename=License.lic";

            return response;
        }
 public object Get(PlainTextRequest request)
 {
     var response = new HttpResult("Hello, World!", "text/plain");
     return response;
 }
        public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
        {
            var tokens = Init(authService, ref session, request);

            var httpMethod = authService.RequestContext.Get<IHttpRequest>().HttpMethod;
            if (httpMethod == HttpMethod.Post)
            {
                var openIdUrl = base.AuthRealm;
                try
                {
                    using (var openid = new OpenIdRelyingParty())
                    {
                        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(ClaimsRequest);

                        // 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];
                        }
                        return httpResult;
                    }
                }
                catch (ProtocolException ex)
                {
                    Log.Error("Falied to login to {0}".Fmt(openIdUrl), ex);
                    return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"));
                }
            }
            else if (httpMethod == HttpMethod.Get)
            {
                var openid = new OpenIdRelyingParty();
                var response = openid.GetResponse();
                if (response != null)
                {
                    switch (response.Status)
                    {
                        case AuthenticationStatus.Authenticated:
                            // This is where you would look for any OpenID extension responses included
                            // in the authentication assertion.
                            var claimsResponse = response.GetExtension<ClaimsResponse>();
                            var authInfo = claimsResponse.ToDictionary();

                            authInfo["user_id"] = response.ClaimedIdentifier; //a url

                            // Store off the "friendly" username to display -- NOT for username lookup
                            authInfo["openid_ref"] = response.FriendlyIdentifierForDisplay;

                            var provided = GetAttributeEx(response);
                            foreach (var entry in provided)
                            {
                                authInfo[entry.Key] = entry.Value;
                            }

                            // 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"));
        }