Example #1
0
        private static HttpResponse OnServeFiles(ITcpChannel channel, HttpRequest request)
        {
            //do not do anything, lib will handle it.
            if (request.Uri.AbsolutePath.StartsWith("/cqs"))
                return null;

            var response = request.CreateResponse();

            var uriWithoutTrailingSlash = request.Uri.AbsolutePath.TrimEnd('/');
            var path = Debugger.IsAttached
                ? Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\public\\", uriWithoutTrailingSlash))
                : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "public\\", uriWithoutTrailingSlash);
            if (path.EndsWith("\\"))
                path = Path.Combine(path, "index.html");

            if (!File.Exists(path))
            {
                response.StatusCode = 404;
                return response;
            }

            var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            var extension = Path.GetExtension(path).TrimStart('.');
            response.ContentType = ApacheMimeTypes.Apache.MimeTypes[extension];
            response.Body = stream;
            return response;
        }
        private bool AuthenticateUser(ITcpChannel channel, HttpRequest request)
        {
            if (channel.Data["Principal"] != null)
            {
                Thread.CurrentPrincipal = (IPrincipal) channel.Data["Principal"];
                return true;
            }

            try
            {
                var user = Authenticator.Authenticate(request);
                if (user == null)
                    return true;

                if (PrincipalFactory != null)
                {
                    var ctx = new PrincipalFactoryContext(request, user);
                    Thread.CurrentPrincipal = PrincipalFactory.Create(ctx);
                    channel.Data["Principal"] = Thread.CurrentPrincipal;
                    return true;
                }

                var roles = user as IUserWithRoles;
                if (roles == null)
                    throw new InvalidOperationException(
                        "You must specify a PrincipalFactory if you do not return a IUserWithRoles from your IAccountService.");

                Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(user.Username), roles.RoleNames);
                channel.Data["Principal"] = Thread.CurrentPrincipal;
            }
            catch (HttpException ex)
            {
                if (Logger != null)
                    Logger("Authentication failed.\r\nException:\r\n" + ex.ToString());
                var response = request.CreateResponse();
                response.StatusCode = ex.HttpCode;
                response.ReasonPhrase = FirstLine(ex.Message);
                channel.Send(response);
                return false;
            }

            return true;
        }