public object Schema(string id)
        {
            const string TSCH = "type-schemas";
            const string TSKU = "type-skus";

            if (id.IsNullOrWhiteSpace())
            {
                throw HTTPStatusException.BadRequest_400("No id");
            }

            IConfigSectionNode[] data = Data[TSCH][id].ConcatArray();
            if (!data[0].Exists)
            {
                data = Data[TSKU].Attributes
                       .Where(c => c.IsSameName(id) && c.Value.IsNotNullOrWhiteSpace())
                       .Select(c => Data[TSCH][c.Value])
                       .ToArray();
            }

            if (data.Length == 0)
            {
                return(new Http404NotFound());
            }

            if (WorkContext.RequestedJson)
            {
                return(data);
            }

            return(SchemaView(data));
        }
Exemple #2
0
        public object Schema(string id)
        {
            const string TSCH = "type-schemas";
            const string TSKU = "type-skus";

            if (id.IsNullOrWhiteSpace())
            {
                throw HTTPStatusException.BadRequest_400("No id");
            }

            IConfigSectionNode data = Data[TSCH][id];

            if (!data.Exists)
            {
                data = Data[TSKU].Attributes
                       .Where(c => c.IsSameName(id) && c.Value.IsNotNullOrWhiteSpace())
                       .Select(c => Data[TSCH][c.Value])
                       .FirstOrDefault();
            }

            if (data == null || !data.Exists)
            {
                return(new Http404NotFound());
            }

            if (WorkContext.RequestedJson)
            {
                return new { OK = true, data }
            }
            ;

            return(SchemaView(data));
        }
        protected override void DoFilterWork(WorkContext work, IList <WorkFilter> filters, int thisFilterIndex)
        {
            var original = ExecutionContext.CallFlow;

            try
            {
                var hdrName = DistributedCallFlowHeader;
                if (hdrName.IsNotNullOrWhiteSpace() && !(original is DistributedCallFlow))
                {
                    DistributedCallFlow flow = null;
                    var hdrJson = work.Request.Headers[hdrName];

                    if (hdrJson.IsNotNullOrWhiteSpace())
                    {
                        JsonDataMap existing;

                        try   { existing = (hdrJson.JsonToDataObject() as JsonDataMap).IsTrue(v => v != null && v.Count > 0, nameof(existing)); }
                        catch { throw HTTPStatusException.BadRequest_400("Bad distributed call flow header"); }

                        flow = DistributedCallFlow.Continue(App, existing);
                    }

                    if (flow == null)
                    {
                        flow = DistributedCallFlow.Start(App, App.Description);
                    }
                }

                this.InvokeNextWorker(work, filters, thisFilterIndex);
            }
            finally
            {
                ExecutionContext.__SetThreadLevelCallContext(original);
            }
        }
Exemple #4
0
        public void GetLogs()
        {
            var path = getLogDiskPath();

            if (path == null)
            {
                throw HTTPStatusException.BadRequest_400("Could not determine local log path");
            }

            var files = path.AllFileNames(false)
                        .Select(f => new FileInfo(f))
                        .Select(i => new { i.Name, i.Length, i.CreationTimeUtc, i.LastAccessTimeUtc, i.LastWriteTimeUtc });

            if (WorkContext.RequestedJson)
            {
                WorkContext.Response.WriteJSON(
                    new
                {
                    m_Log.LastWarning,
                    m_Log.LastError,
                    m_Log.LastCatastrophe,
                    files
                });
                return;
            }

            var html = new StringBuilder();

            html.AppendLine("<html>");
            html.AppendLine($"<head>");
            html.AppendLine("<style> body{ font-family: 'Courier New'} td{padding: 6px;} </style>");
            html.AppendLine($" <title>Log Files on `{Azos.Platform.Computer.HostName}` at {App.TimeSource.UTCNow} UTC </title>");
            html.AppendLine("</head>");
            html.AppendLine("<body>");
            html.AppendLine("<table>");
            foreach (var f in files)
            {
                html.AppendLine("<tr>");
                html.AppendLine($"<td><a href='/info/log-file?fn={Uri.EscapeUriString(f.Name)}'>{f.Name}</a></td>");
                html.AppendLine("<td>{0:n0}</td>".Args(f.Length));
                html.AppendLine($"<td>{f.Length}</td>");
                html.AppendLine($"<td>{f.CreationTimeUtc}</td>");
                html.AppendLine($"<td>{f.LastAccessTimeUtc}</td>");
                html.AppendLine($"<td>{f.LastWriteTimeUtc}</td>");
                html.AppendLine("</tr>");
            }

            html.AppendLine("</table>");
            html.AppendLine("</body>");
            html.AppendLine("</html>");

            WorkContext.Response.ContentType = Azos.Web.ContentType.HTML;
            WorkContext.Response.Write(html.ToString());
        }
Exemple #5
0
 private void checkRoute(Atom ns, Atom queue)
 {
     if (ns.IsZero || !ns.IsValid)
     {
         throw HTTPStatusException.BadRequest_400("invalid ns");
     }
     if (queue.IsZero || !queue.IsValid)
     {
         throw HTTPStatusException.BadRequest_400("invalid queue");
     }
 }
Exemple #6
0
        //We always make a new in-memory ephemeral session which gets collected right after this request
        protected override WaveSession MakeNewSessionInstance(WorkContext work)
        {
            const string BASIC  = WebConsts.AUTH_SCHEME_BASIC + " ";
            const string BEARER = WebConsts.AUTH_SCHEME_BEARER + " ";

            //Always create new session
            var session = base.MakeNewSessionInstance(work);

            //try to inject session.DataContextName
            var dch = DataContextHeader;

            if (dch.IsNotNullOrWhiteSpace())
            {
                var dcn = work.Request.Headers[dch];
                if (dcn.IsNotNullOrWhiteSpace())
                {
                    dcn = dcn.Trim().TakeFirstChars(1024);//hard limit safeguard
                    session.DataContextName = dcn;
                }
            }

            var hdr = work.Request.Headers[WebConsts.HTTP_HDR_AUTHORIZATION]?.TrimStart(' ');

            if (hdr.IsNullOrWhiteSpace())
            {
                return(session);                   //unauthorized
            }
            Credentials credentials = null;

            try
            {
                if (hdr.StartsWith(BASIC, StringComparison.OrdinalIgnoreCase))
                {
                    var basic = hdr.Substring(BASIC.Length).Trim();
                    credentials = IDPasswordCredentials.FromBasicAuth(basic);
                }
                else if (hdr.StartsWith(BEARER, StringComparison.OrdinalIgnoreCase))
                {
                    var bearer = hdr.Substring(BEARER.Length).Trim();
                    credentials = new BearerCredentials(bearer);
                }
            }
            catch { }

            if (credentials == null)
            {
                throw HTTPStatusException.BadRequest_400("Bad [Authorization] header");
            }

            session.User = App.SecurityManager.Authenticate(credentials);//authenticate the user
            work.SetAuthenticated(session.User.IsAuthenticated);
            return(session);
        }
Exemple #7
0
        public object GetLogFile(string fn, bool attach = false)
        {
            var path = getLogDiskPath();

            if (path == null)
            {
                throw HTTPStatusException.BadRequest_400("Could not determine local log path");
            }
            var fullPath = Path.Combine(path, fn.NonBlank(nameof(fn).Replace("..", string.Empty)));

            using (var fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (var rdr = new StreamReader(fs))
                    return(rdr.ReadToEnd());
        }
Exemple #8
0
        public void Feed(string portal, string ns, string block, Atom isolang, bool nocache = false, bool buffered = false)
        {
            ContentId id = default(ContentId);

            try
            {
                id = new ContentId(portal, ns, block);
            }
            catch (Exception error)
            {
                throw HTTPStatusException.BadRequest_400(error.Message);
            }

            var content = m_Cms.GetContentAsync(id, isolang, nocache.NoOrDefaultCache())
                          .GetAwaiter().GetResult();

            if (content == null)
            {
                throw HTTPStatusException.NotFound_404(id.ToString());
            }

            var compressionThreshold = App.ConfigRoot[SysConsts.CONFIG_WAVE_SECTION]
                                       .Of("cms-source-feeder-compressor-threshold-bytes").ValueAsInt(8000);

            var compress = (content.StringContent != null && content.StringContent.Length > compressionThreshold) ||
                           (content.BinaryContent != null && content.BinaryContent.Length > compressionThreshold);

            WorkContext.Response.Buffered          = buffered;
            WorkContext.Response.StatusCode        = 200;
            WorkContext.Response.StatusDescription = "Found CMS content";
            WorkContext.Response.ContentType       = compress ? CTP_COMPRESSED : CTP_UNCOMPRESSED;
            var httpStream = WorkContext.Response.GetDirectOutputStreamForWriting();

            if (compress)
            {
                using (var zipStream = new GZipStream(httpStream, CompressionLevel.Optimal))
                {
                    content.WriteToStream(zipStream);
                }
            }
            else
            {
                content.WriteToStream(httpStream);
            }
        }
Exemple #9
0
        //We always make a new in-memory ephemeral session which gets collected right after this request
        protected override WaveSession MakeNewSessionInstance(WorkContext work)
        {
            //Always create new session
            var session = base.MakeNewSessionInstance(work);

            //try to inject session.DataContextName
            var dch = DataContextHeader;

            if (dch.IsNotNullOrWhiteSpace())
            {
                var dcn = work.Request.Headers[dch];
                if (dcn.IsNotNullOrWhiteSpace())
                {
                    dcn = dcn.Trim().TakeFirstChars(1024);//hard limit safeguard
                    session.DataContextName = dcn;
                }
            }

            string hdr = null;

            var altHdrName = AltAuthorizationHeader;

            if (altHdrName.IsNotNullOrWhiteSpace())
            {
                hdr = work.Request.Headers[altHdrName]?.TrimStart(' ');
            }

            if (hdr.IsNullOrWhiteSpace())
            {
                //real AUTHORIZATION header
                hdr = work.Request.Headers[WebConsts.HTTP_HDR_AUTHORIZATION]?.TrimStart(' ');
                if (hdr.IsNullOrWhiteSpace())
                {
                    var mockHdrName = DefaultImpersonationAuthorizationHeaderValue;
                    if (mockHdrName.IsNotNullOrEmpty())
                    {
                        hdr = mockHdrName;
                    }
                    else
                    {
                        return(session);//unauthorized
                    }
                }
            }

            User user;

            if (EnableSystemTokens && hdr.StartsWith(SYSTOKEN, StringComparison.OrdinalIgnoreCase))
            {
                var sysTokenContent = hdr.Substring(SYSTOKEN.Length).Trim();

                if (sysTokenContent.IsNullOrWhiteSpace() || // empty or null tokens treated as empty
                    !SysAuthToken.TryParse(sysTokenContent, out var sysToken))
                {
                    throw HTTPStatusException.BadRequest_400("Bad [Authorization] header systoken");
                }

                user = App.SecurityManager.Authenticate(sysToken);//authenticate the user using Systoken
            }
            else//credentials
            {
                Credentials credentials = null;

                try
                {
                    if (hdr.StartsWith(BASIC, StringComparison.OrdinalIgnoreCase))
                    {
                        var basic = hdr.Substring(BASIC.Length).Trim();
                        credentials = IDPasswordCredentials.FromBasicAuth(basic);
                    }
                    else if (hdr.StartsWith(BEARER, StringComparison.OrdinalIgnoreCase))
                    {
                        var pfxBasic = BearerBasicPrefix;
                        var bearer   = hdr.Substring(BEARER.Length).Trim();
                        if (pfxBasic.IsNotNullOrWhiteSpace() && bearer.IsNotNullOrWhiteSpace() && bearer.StartsWith(pfxBasic))
                        {
                            var basicContent = bearer.Substring(pfxBasic.Length).Trim();
                            credentials = IDPasswordCredentials.FromBasicAuth(basicContent);
                        }
                        else
                        {
                            credentials = new BearerCredentials(bearer);
                        }
                    }
                }
                catch { }

                if (credentials == null)
                {
                    throw HTTPStatusException.BadRequest_400("Bad [Authorization] header");
                }

                user = App.SecurityManager.Authenticate(credentials);//authenticate the user
            }

            session.User = user;//<===========================================================I
            work.SetAuthenticated(user.IsAuthenticated);

            //gate bad traffic
            var gate = NetGate;

            if (!user.IsAuthenticated && gate != null && gate.Enabled)
            {
                var vname = GateBadAuthVar;
                if (vname.IsNotNullOrWhiteSpace())
                {
                    gate.IncreaseVariable(IO.Net.Gate.TrafficDirection.Incoming,
                                          work.EffectiveCallerIPEndPoint.Address.ToString(),
                                          vname,
                                          1);
                }
            }

            return(session);
        }