Esempio n. 1
0
 public bool HandlesStatusCode(Nancy.HttpStatusCode statusCode,
                               Nancy.NancyContext context)
 {
     return(statusCode == Nancy.HttpStatusCode.NotFound ||
            statusCode == Nancy.HttpStatusCode.BadRequest ||
            statusCode == Nancy.HttpStatusCode.InternalServerError);
 }
Esempio n. 2
0
        public void Handle(Nancy.HttpStatusCode statusCode, Nancy.NancyContext context)
        {
            var response = RenderView(context, "CustomErrorPage");

            response.StatusCode = statusCode;
            context.Response    = response;
        }
Esempio n. 3
0
 public bool HandlesStatusCode(Nancy.HttpStatusCode statusCode, Nancy.NancyContext context)
 {
     if (statusCode == Nancy.HttpStatusCode.InternalServerError)
     {
         return(false);
     }
     return(false);
 }
Esempio n. 4
0
        public Nancy.Security.IUserIdentity GetUserFromIdentifier(Guid identifier, Nancy.NancyContext context)
        {
            var userRecord = users.Where(u => u.Item3 == identifier).FirstOrDefault();

            return(userRecord == null
                       ? null
                       : new QuoteUserIdentity {
                UserName = userRecord.Item1
            });
        }
Esempio n. 5
0
        public void Handle(Nancy.HttpStatusCode statusCode,
                           Nancy.NancyContext context)
        {
            dynamic model = new ExpandoObject();

            model.IsAuthenticated = context.CurrentUser.IsAuthenticated();
            model.JournalUser     = (JournalUserIdentity)context.CurrentUser;
            var response = RenderView(context, "Error/" + (int)statusCode, model);

            response.StatusCode = statusCode;
            context.Response    = response;
        }
        public static string session_deviceType_Get(Nancy.NancyContext ctx, string session_id)
        {
            string device_type = device_Default;

            dicSession_DeviceType.TryGetValue(session_id, out device_type);
            if (string.IsNullOrEmpty(device_type))
            {
                if (ctx.Request.Cookies.ContainsKey("device_type") == true)
                {
                    device_type = ctx.Request.Cookies["device_type"];
                    session_deviceType_Set(session_id, device_type);
                }
            }
            return(device_type);
        }
        /// <summary>
        /// Get user from the database
        /// </summary>
        public Nancy.Security.IUserIdentity GetUserFromIdentifier(Guid identifier, Nancy.NancyContext context)
        {
            var person = _people.People.FirstOrDefault(p => p.Id == identifier);

            if (person == null)
            {
                return(null);
            }

            var user = new FloreamIdentity
            {
                UserName = person.AdUser
            };

            return(user);
        }
        public Nancy.Security.IUserIdentity GetUserFromIdentifier(Guid identifier, Nancy.NancyContext context)
        {
            RemoveExpiredIdentities();

            if (_cachedIdentities.ContainsKey(identifier))
            {
                return(_cachedIdentities[identifier].Identity);
            }

            //todo: build from database with claims
            var identity = new UserIdentity("Mathieu");

            _cachedIdentities.Add(identifier, new UserIdentityContainer(identity, DateTime.Now.AddSeconds(10)));

            return(identity);
        }
        public IUserIdentity GetUserFromIdentifier(Guid identifier, Nancy.NancyContext context)
        {
            var transaction = GetTransaction();

            var sql = "select * from users where id=:id;";

            var user = transaction.Connection
                       .Query <JournalUserIdentity>(
                sql,
                new { id = identifier },
                transaction.Instance).
                       FirstOrDefault();

            if (user != null)
            {
                transaction.SetUserId(identifier);
            }

            return(user);
        }
Esempio n. 10
0
        HttpClient CreateProxyClient(Nancy.NancyContext context)
        {
            var handler = new HttpClientHandler();

            handler.AllowAutoRedirect = false;
            var client = new HttpClient(handler);

            foreach (var header in Context.Request.Headers)
            {
                Log.Debug("{key}: {value}", header.Key, header.Value);
                if (_skipHeaders.Contains(header.Key, StringComparer.OrdinalIgnoreCase)) // host header causes 400 invalid host error
                {
                    continue;
                }
                client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            // client.DefaultRequestHeaders.Add("X-Forwarded-For", <UserHostAddress>); // TODO: see RequestLogEnricher.GetUserIPAddress()
            client.DefaultRequestHeaders.Add("X-Compute-Id", Context.Items["RequestId"] as string);
            client.DefaultRequestHeaders.Add("X-Compute-Host", Context.Items["Hostname"] as string);
            return(client);
        }
Esempio n. 11
0
        static Nancy.Response CheckApiKey(Nancy.NancyContext context)
        {
            if (context.Request.Method == "GET" || context.Request.Method == "OPTIONS")
            {
                return(null); // GET and OPTIONS requests are free
            }
            var requestIds = new List <string>(context.Request.Headers["RhinoComputeKey"]);

            if (requestIds.Count != 1)
            {
                return(NoKeyResponse());
            }
            var key_in_header = requestIds[0];

            if (string.Equals(key_in_header, _apiKey, StringComparison.Ordinal))
            {
                return(null);
            }

            return(NoKeyResponse());
        }
Esempio n. 12
0
        Nancy.Response CreateProxyResponse(HttpResponseMessage backendResponse, Nancy.NancyContext context)
        {
            string responseBody = backendResponse.Content.ReadAsStringAsync().Result;
            var    response     = (Nancy.Response)responseBody;

            response.StatusCode = (Nancy.HttpStatusCode)backendResponse.StatusCode;
            foreach (var header in backendResponse.Headers)
            {
                foreach (var value in header.Value)
                {
                    response.Headers.Add(header.Key, value);
                }
            }
            foreach (var header in backendResponse.Content.Headers)
            {
                foreach (var value in header.Value)
                {
                    response.Headers.Add(header.Key, value);
                }
            }
            return(response);
        }
Esempio n. 13
0
        HttpClient CreateProxyClient(Nancy.NancyContext context)
        {
            var handler = new HttpClientHandler();

            handler.AllowAutoRedirect = false;
            var client = new HttpClient(handler);

            foreach (var header in Context.Request.Headers)
            {
                if (header.Key == "Content-Length")
                {
                    continue;
                }
                if (header.Key == "Content-Type")
                {
                    continue;
                }
                client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            client.DefaultRequestHeaders.Add("X-Compute-Id", (string)Context.Items["RequestId"]);
            client.DefaultRequestHeaders.Add("X-Compute-Host", (string)Context.Items["Hostname"]);
            return(client);
        }
Esempio n. 14
0
        public static AuthCheckInternalResponse CheckAuthHeader(Nancy.NancyContext context)
        {
            var auth_header = context.Request.Headers.Authorization;

            if (auth_header == null)
            {
                return(new AuthCheckInternalResponse()
                {
                    authed = false,
                    err = AsErrorObject(Nancy.HttpStatusCode.BadRequest, new
                    {
                        success = false,
                        type = "INVALID_CREDS",
                        message = "No valid authorization header."
                    })
                });
            }
            var auth_header_split = auth_header.Split(' ');

            if (auth_header_split.Length != 2 || auth_header_split[0].ToLower() != "bearer")
            {
                return(new AuthCheckInternalResponse()
                {
                    authed = false,
                    err = AsErrorObject(Nancy.HttpStatusCode.BadRequest, new
                    {
                        success = false,
                        type = "INVALID_CREDS",
                        message = "Invalid authorization header."
                    })
                });
            }
            var auth_token = auth_header_split[1];

            foreach (KeyValuePair <string, AccessTokenInfo> access_token_pair in Program.config_handler.config.access_tokens)
            {
                if (access_token_pair.Key == auth_token)
                {
                    if ((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds > access_token_pair.Value.active_until)
                    {
                        return(new AuthCheckInternalResponse()
                        {
                            authed = false,
                            err = AsErrorObject(Nancy.HttpStatusCode.Forbidden, new
                            {
                                success = false,
                                type = "TOKEN_EXPIRED",
                                message = "Token has expired."
                            })
                        });
                    }
                    return(new AuthCheckInternalResponse()
                    {
                        authed = true,
                        access_token_pair = access_token_pair
                    });
                }
            }
            return(new AuthCheckInternalResponse()
            {
                authed = false,
                err = AsErrorObject(Nancy.HttpStatusCode.Forbidden, new
                {
                    success = false,
                    type = "INVALID_CREDS",
                    message = "Invalid token."
                })
            });
        }
Esempio n. 15
0
        protected override void RequestStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, Nancy.NancyContext context)
        {
            base.RequestStartup(container, pipelines, context);

            var formsAuthConfiguration = new FormsAuthenticationConfiguration
            {
                RedirectUrl     = "~/login",
                UserMapper      = new UserMapper(),
                RequiresSSL     = true,
                DisableRedirect = (context.Request.Headers.Keys.Contains("Client") && context.Request.Headers["Client"].Contains("RichClient")) || context.Request.Url.Path.Contains("/login")
            };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
        }
Esempio n. 16
0
 public IUserIdentity GetUserFromIdentifier(Guid identifier, Nancy.NancyContext context)
 {
     return(new UserIdentity());
 }
Esempio n. 17
0
 protected override void RequestStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, Nancy.NancyContext context)
 {
     base.RequestStartup(container, pipelines, context);
     pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) =>
     {
         ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*");
         ctx.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET");
         ctx.Response.Headers.Add("Access-Control-Allow-Headers", "Accept, Origin, Content-type");
     });
 }
Esempio n. 18
0
        /// <summary>
        /// Sends the email
        /// </summary>
        /// <param name="site"></param>
        /// <param name="to"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        public static void SendEmail(string to, string subject, string body, bool queue = true, Nancy.NancyContext ctx = null)
        {
            if (_Outbox == null)
            {
                _Outbox = new ConcurrentQueue <MailMessage>();
            }

            if (string.IsNullOrEmpty(to))
            {
                System.Diagnostics.Debugger.Break();
                return;
            }

            MailMessage mail = new MailMessage();

            mail.To.Add(to);
            mail.Subject    = subject;
            mail.Body       = body;
            mail.IsBodyHtml = true;

            _Outbox.Enqueue(mail);

            if (queue == false)
            {
                if (ctx == null)
                {
                    throw new InvalidOperationException("Context is required");
                }

                MailSenderModule.ProcessQueue(ctx);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Immediately Send out email
        /// </summary>
        public static void ProcessQueue(Nancy.NancyContext ctx)
        {
            if (_Outbox == null)
            {
                return;
            }

            if (ctx.Items.ContainsKey("SiteSettings") == false)
            {
                return;
            }

            lock (BaseModule.GetLockObject("MailSenderModule.ProcessQueue"))
            {
                if (_Outbox == null)
                {
                    return;
                }

                var toSend = _Outbox.ToList();
                _Outbox = null;

                var site = ctx.Items["SiteSettings"] as JObject;

                Task.Run(() =>
                {
                    Func <SmtpSettings, SmtpClient> getClient = (s) =>
                    {
                        SmtpClient client  = new SmtpClient(s.server);
                        client.Port        = s.port;
                        client.Credentials = new System.Net.NetworkCredential(s.username, s.password);
                        client.EnableSsl   = s.useSSL;
                        client.Timeout     = 30000;

                        return(client);
                    };

                    var db            = NancyBlackDatabase.GetSiteDatabase(BootStrapper.RootPath);
                    var settings      = site.Property("smtp").Value.ToObject <SmtpSettings>();
                    var count         = 0;
                    SmtpClient sender = getClient(settings);

                    foreach (var mail in toSend)
                    {
                        if (count % 100 == 0)
                        {
                            sender.Dispose();
                            count = 0;

                            sender = getClient(settings);
                        }

                        var log         = new NcbMailSenderLog();
                        log.Body        = mail.Body;
                        log.To          = string.Join(",", from m in mail.To select m.Address);
                        log.Subject     = mail.Subject;
                        log.MessageHash = (log.Body + log.To + log.Subject).GetHashCode();
                        log.Settings    = settings;
                        log.__createdAt = DateTime.Now;
                        log.__updatedAt = DateTime.Now;

                        var today   = DateTime.Now.Date;
                        var lastLog = db.Query <NcbMailSenderLog>().Where(l => l.MessageHash == log.MessageHash).FirstOrDefault();
                        if (lastLog != null)
                        {
                            if (DateTime.Now.Subtract(lastLog.__createdAt).TotalHours < 12)
                            {
                                log.IsSkipped = true;
                            }
                        }

                        if (log.IsSkipped == false)
                        {
                            try
                            {
                                log.IsAttempted = true;

                                mail.From = new MailAddress(settings.fromEmail);
                                sender.Send(mail);

                                log.IsSent = true;
                            }
                            catch (Exception e)
                            {
                                log.Exception = e;
                            }
                        }

                        db.UpsertRecord(log);
                        count++;
                    }

                    db.Dispose();
                });
            }
        }
Esempio n. 20
0
 protected override IKernel CreateRequestContainer(Nancy.NancyContext context)
 {
     return(kernel);
 }
Esempio n. 21
0
 public static bool UsesCustomHeader(this Nancy.NancyContext ctx)
 {
     return(ctx.Request.Headers.Any(x => x.Key.StartsWith("X", StringComparison.InvariantCultureIgnoreCase)));
 }