Exemple #1
0
        protected override void ApplicationStartup(TinyIoCContainer _container, IPipelines _pipelines)
        {
            base.ApplicationStartup(_container, _pipelines);
            m_ApiToken = Config.GetSettingValue("ApiAccessKey", null);

            Trace.Listeners.Add(new LogglyTraceListener());

            _pipelines.BeforeRequest.AddItemToStartOfPipeline(_context =>
            {
                //Validate the API Token
                string apiToken = _context.Request.Headers["ApiAccessKey"].FirstOrDefault();

                if (apiToken != null &&
                    apiToken.Equals(m_ApiToken))
                {
                    return(null);
                }

                TraceFileHelper.Warning("Missing or invalid api access key");
                return(new Response()
                {
                    StatusCode = HttpStatusCode.BadRequest
                });
            });

            _pipelines.OnError.AddItemToStartOfPipeline((context, exception) =>
            {
                TraceFileHelper.Exception(exception);
                return(Response.NoBody);
            });
        }
Exemple #2
0
        static void Main(string[] args)
        {
            TraceFileHelper.SetupLogging();
            Trace.Listeners.Add(new ConsoleTraceListener());

            using (var host = new NancyHost(new Uri("http://localhost:8990")))
            {
                host.Start();
                TraceFileHelper.Info("Started webserver");

                if (Type.GetType("Mono.Runtime") != null)
                {
                    // on mono, processes will usually run as daemons - this allows you to listen
                    // for termination signals (ctrl+c, shutdown, etc) and finalize correctly
                    UnixSignal.WaitAny(new[] {
                        new UnixSignal(Signum.SIGINT),
                        new UnixSignal(Signum.SIGTERM),
                        new UnixSignal(Signum.SIGQUIT),
                        new UnixSignal(Signum.SIGHUP)
                    });
                }
                else
                {
                    Console.ReadKey();
                }

                TraceFileHelper.Info("Stopping webserver");
                host.Stop();
            }
        }
Exemple #3
0
        public void ParseOpenGISText(string _wellKnownText)
        {
            string wkt = _wellKnownText.Trim();

            if (wkt.StartsWith("Point", StringComparison.InvariantCultureIgnoreCase))
            {
                int start = wkt.IndexOf("(");
                int end   = wkt.IndexOf(")");

                string inner = wkt.Substring(start + 1, end - (start + 1));

                string[] parts = inner.Split(" ".ToCharArray());

                if (parts.Length == 2)
                {
                    X = Convert.ToDouble(parts[0]);
                    Y = Convert.ToDouble(parts[1]);
                }
                else
                {
                    TraceFileHelper.Warning(string.Format("Invalid Point Definition - {0}", wkt));
                    throw new Exception("Invalid Point definition");
                }
            }
            else
            {
                TraceFileHelper.Warning(string.Format("Not a point - {0}", wkt));
                throw new Exception("Not a point");
            }
        }
Exemple #4
0
        //Gets all tags
        public List <TagRow> GetTagRows(string _username, bool _activeOnly)
        {
            try
            {
                string startKey = null;

                return(GetTagRows(_username, _activeOnly, 0, ref startKey));
            }
            catch (Exception ex)
            {
                TraceFileHelper.Exception(ex);
            }

            return(null);
        }
Exemple #5
0
        public void Must_be_Create_If_File_Not_Exists()
        {
            File.Delete(FilePath);

            // ACT
            TraceFileHelper.PushToFile(FilePath, new TraceFileHelperTestContract {
                A = 488, B = "Aloha"
            });
            TraceFileHelper.PushToFile(FilePath, new TraceFileHelperTestContract {
                A = 488, B = "Aloha"
            });

            var contracts = TraceFileHelper.Read <TraceFileHelperTestContract>(FilePath).ToList();

            Assert.AreEqual(2, contracts.Count);
        }
Exemple #6
0
        public void ParseOpenGISText(string _wellKnownText)
        {
            string wkt = _wellKnownText.Trim();

            const string MP_REGEX    = @"MULTIPOINT \((?<Points>.+)\)";
            const string POINT_REGEX = @"(?<Point>\(.+?\))";
            const string XY_REGEX    = @"\((?<X>.+?) (?<Y>.+)\)";

            Match pointsMatch = Regex.Match(_wellKnownText, MP_REGEX);

            if (pointsMatch != null)
            {
                string points = pointsMatch.Groups["Points"].Value;

                MatchCollection mc = Regex.Matches(points, POINT_REGEX);

                if (mc != null &&
                    mc.Count > 0)
                {
                    foreach (Match pointMatch in mc)
                    {
                        string point = pointMatch.Groups[""].Value;

                        Match xyMatch = Regex.Match(point, XY_REGEX);

                        if (xyMatch != null)
                        {
                            double x = Convert.ToDouble(xyMatch.Groups["X"].Value);
                            double y = Convert.ToDouble(xyMatch.Groups["Y"].Value);

                            GeoPoint gp = new GeoPoint(x, y);
                            Add(gp);
                        }
                    }
                }
            }
            else
            {
                TraceFileHelper.Warning(string.Format("Not a point - {0}", wkt));
                throw new Exception("Not a point");
            }
        }
Exemple #7
0
        public static void CreateScaledImages(HydrantWikiManager _manager,
                                              Guid _originalGuid)
        {
            //Get the image from the originals folder from S3
            //Load the original
            byte[] data = _manager.GetOriginal(_originalGuid, ".jpg");

            try
            {
                using (Image full = ImageHelper.GetImage(data))
                {
                    //Standard sizes must fit in 800 x 800
                    SizeF thumbSize = ImageSizeHelper.SizeThatFits(full, 800);
                    using (Image reduced = ImageHelper.GetThumbnail(full,
                                                                    Convert.ToInt32(thumbSize.Height),
                                                                    Convert.ToInt32(thumbSize.Width)))
                    {
                        data = ImageHelper.GetBytes(reduced, ImageFormat.Jpeg);

                        _manager.PersistWebImage(_originalGuid, ".jpg", "image/jpg", data);
                    }


                    //Thumbnails must fit in 100 x 100
                    thumbSize = ImageSizeHelper.SizeThatFits(full, 100);
                    using (Image reduced = ImageHelper.GetThumbnail(full,
                                                                    Convert.ToInt32(thumbSize.Height),
                                                                    Convert.ToInt32(thumbSize.Width)))
                    {
                        data = ImageHelper.GetBytes(reduced, ImageFormat.Jpeg);

                        _manager.PersistThumbnailImage(_originalGuid, ".jpg", "image/jpg", data);
                    }
                }
            }
            catch (Exception ex)
            {
                //Bad Image
                TraceFileHelper.Exception(ex);
            }
        }
Exemple #8
0
        public void ParseOpenGISText(string _wellKnownText)
        {
            string wkt = _wellKnownText.Trim();

            if (wkt.StartsWith("LineString", StringComparison.InvariantCultureIgnoreCase))
            {
                int start = wkt.IndexOf("(");
                int end   = wkt.IndexOf(")");

                string inner = wkt.Substring(start + 1, end - (start + 1));

                string[] points = inner.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                foreach (string point in points)
                {
                    string[] parts = point.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                    if (parts.Length == 2)
                    {
                        GeoPoint gp = new GeoPoint
                        {
                            X = Convert.ToDouble(parts[0]),
                            Y = Convert.ToDouble(parts[1])
                        };

                        Points.Add(gp);
                    }
                    else
                    {
                        TraceFileHelper.Warning(string.Format("Invalid Point Definition - {0}", wkt));
                        throw new Exception("Invalid Line definition");
                    }
                }
            }
            else
            {
                TraceFileHelper.Warning(string.Format("Not a line - {0}", wkt));
                throw new Exception("Not a line");
            }
        }
Exemple #9
0
        private BaseResponse EmailInUse(DynamicDictionary _parameters)
        {
            HydrantWikiManager  hwm      = new HydrantWikiManager();
            IsAvailableResponse response = new IsAvailableResponse {
                Available = false, Success = true
            };

            string email = _parameters["email"];

            if (email != null)
            {
                User user = hwm.GetUserByEmail(UserSources.HydrantWiki, email);

                TraceFileHelper.Info("Check if email in use ({0})", email);

                if (user == null)
                {
                    response.Available = true;
                }
            }

            return(response);
        }
Exemple #10
0
        private BaseResponse IsAvailable(DynamicDictionary _parameters)
        {
            HydrantWikiManager  hwm      = new HydrantWikiManager();
            IsAvailableResponse response = new IsAvailableResponse {
                Available = false, Success = true
            };

            string username = _parameters["username"];

            if (username != null)
            {
                User user = hwm.GetUser(UserSources.HydrantWiki, username);

                TraceFileHelper.Info("Check if username exists ({0})", username);

                if (user == null)
                {
                    response.Available = true;
                }
            }

            return(response);
        }
        public bool SendCannedEmail(TGUser _tgUser,
                                    string _cannedEmailName,
                                    NameValueCollection _additionParameters)
        {
            try
            {
                CannedEmail cannedEmail = GetCannedEmail(_cannedEmailName);

                if (cannedEmail != null)
                {
                    SystemEmail email = new SystemEmail(cannedEmail.Guid);

                    TGSerializedObject tgso = _tgUser.GetTGSerializedObject();
                    foreach (string key in _additionParameters.Keys)
                    {
                        string value = _additionParameters.Get(key);
                        tgso.Add(key, value);
                    }

                    CannedEmailHelper.PopulateEmail(cannedEmail, email, tgso);

                    SESHelper.SendMessage(email);
                    Persist(email);

                    return(true);
                }

                TraceFileHelper.Warning("Canned email not found");
            }
            catch (Exception ex)
            {
                TraceFileHelper.Exception(ex);
            }

            return(false);
        }
Exemple #12
0
 public void LogInfo(Guid _userGuid, string _message)
 {
     TraceFileHelper.Info(_message + "|UserGuid - {0}", _userGuid);
 }
Exemple #13
0
        private BaseResponse HandleImagePost(DynamicDictionary _parameters)
        {
            HydrantWikiManager hwManager = new HydrantWikiManager();

            var response = new BaseResponse {
                Success = false
            };
            User user;

            if (AuthHelper.IsAuthorized(Request, out user))
            {
                try
                {
                    byte[] fileData = null;
                    string fileName = null;

                    if (Request.Files.Any())
                    {
                        HttpFile file = Request.Files.First();

                        long length = file.Value.Length;
                        fileData = new byte[(int)length];
                        file.Value.Read(fileData, 0, (int)length);
                        fileName = file.Name;
                    }

                    if (fileName != null)
                    {
                        string tempGuid = Path.GetFileNameWithoutExtension(fileName);
                        Guid   imageGuid;

                        if (Guid.TryParse(tempGuid, out imageGuid))
                        {
                            hwManager.PersistOriginal(imageGuid, ".jpg", "image/jpg", fileData);
                            hwManager.LogVerbose(user.Guid, "Tag Image Saved");

                            Image original = ImageHelper.GetImage(fileData);

                            fileData = ImageHelper.GetThumbnailBytesOfMaxSize(original, 800);
                            hwManager.PersistWebImage(imageGuid, ".jpg", "image/jpg", fileData);

                            fileData = ImageHelper.GetThumbnailBytesOfMaxSize(original, 100);
                            hwManager.PersistThumbnailImage(imageGuid, ".jpg", "image/jpg", fileData);

                            hwManager.LogInfo(user.Guid, string.Format("Saved Image ({0})", imageGuid));

                            response.Success = true;
                            return(response);
                        }
                    }
                }
                catch (Exception ex)
                {
                    TraceFileHelper.Error("Failure to post image");
                    hwManager.LogException(user.Guid, ex);
                }
            }
            else
            {
                LogUnauthorized(Request);
                response.Error   = "Unauthorized";
                response.Message = "Reauthenticate";
            }

            return(response);
        }
Exemple #14
0
        public BaseResponse ResetPassword(DynamicDictionary _parameters)
        {
            BaseResponse response = new BaseResponse();

            string json = Request.Body.ReadAsString();

            if (json != null)
            {
                ResetPassword rr = JsonConvert.DeserializeObject <ResetPassword>(json);
                if (rr.Email != null &&
                    rr.InstallId != null &&
                    rr.Code != null &&
                    rr.NewPassword != null)
                {
                    HydrantWikiManager manager = new HydrantWikiManager();
                    User user = manager.GetUserByEmail(UserSources.HydrantWiki, rr.Email);
                    if (user != null)
                    {
                        DateTime      now = DateTime.UtcNow;
                        PasswordReset pr  = manager.GetPasswordReset(user.Guid, rr.Code);

                        if (pr != null)
                        {
                            if (pr.CreationDateTime > now.AddHours(-2))
                            {
                                TGUserPassword userPassword = TGUserPassword.GetNew(
                                    user.Guid,
                                    user.Username,
                                    rr.NewPassword);
                                manager.Persist(userPassword);

                                pr.Active = false;
                                manager.Persist(pr);

                                manager.LogInfo(user.Guid, "Password successfully reset");

                                response.Success = true;
                                response.Message = "Password successfully reset.";
                            }
                            else
                            {
                                manager.LogWarning(user.Guid, "Password Reset request has expired");
                                response.Success = false;
                                response.Message = "Password Reset request has expired";
                            }
                        }
                        else
                        {
                            manager.LogWarning(user.Guid, "Invalid reset code");
                            response.Success = false;
                            response.Message = "Invalid reset code.";
                        }
                    }
                    else
                    {
                        TraceFileHelper.Warning("User not found ({0})", rr.Email);
                        response.Success = false;
                        response.Message = "User not found.";
                    }
                }
                else
                {
                    response.Message = "Invalid information supplied";
                }
            }
            else
            {
                response.Message = "Body not supplied";
            }

            return(response);
        }
Exemple #15
0
        private BaseResponse HandleTagPost(DynamicDictionary _parameters)
        {
            HydrantWikiManager hwManager = new HydrantWikiManager();

            var response = new TagPostResponse {
                Success = false
            };
            User user;

            if (AuthHelper.IsAuthorized(Request, out user))
            {
                try
                {
                    string json = Request.Body.ReadAsString();

                    Objects.Tag tag = JsonConvert.DeserializeObject <Objects.Tag>(json);

                    if (tag != null)
                    {
                        if (tag.Position != null)
                        {
                            if (tag.Position != null)
                            {
                                var dbTag = new HydrantWiki.Library.Objects.Tag
                                {
                                    Active               = true,
                                    DeviceDateTime       = tag.Position.DeviceDateTime,
                                    LastModifiedDateTime = DateTime.UtcNow,
                                    UserGuid             = user.Guid,
                                    VersionTimeStamp     = DateTime.UtcNow.ToString("u"),
                                    Position             = new GeoPoint(tag.Position.Longitude, tag.Position.Latitude),
                                    ImageGuid            = tag.ImageGuid,
                                    Status               = TagStatus.Pending
                                };

                                hwManager.Persist(dbTag);
                                hwManager.LogVerbose(user.Guid, "Tag Saved");

                                response.ImageUrl     = dbTag.GetUrl(false);
                                response.ThumbnailUrl = dbTag.GetUrl(true);

                                response.Success = true;
                                return(response);
                            }
                            else
                            {
                                //No position
                                hwManager.LogWarning(user.Guid, "No position");

                                response.Message = "No position";
                                return(response);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    TraceFileHelper.Error("Failure to post tag");
                    hwManager.LogException(user.Guid, ex);
                }
            }
            else
            {
                LogUnauthorized(Request);
                response.Error   = "Unauthorized";
                response.Message = "Reauthenticate";
            }

            return(response);
        }
Exemple #16
0
 public void LogException(Guid _userGuid, Exception _message)
 {
     TraceFileHelper.Exception(_message + "|UserGuid - {0}", _userGuid);
 }
Exemple #17
0
 public void LogVerbose(Guid _userGuid, string _message)
 {
     TraceFileHelper.Verbose(_message + "|UserGuid - {0}", _userGuid);
 }
Exemple #18
0
        public static LoginResult Authorize(OpenFormGraphManager _manager,
                                            string _username, string _password, out TGUser _user)
        {
            LoginResult result = new LoginResult();

            _user = _manager.GetUser(_username);

            if (_user != null)
            {
                if (_user.Active)
                {
                    if (_manager.ValidateUser(_user, _password))
                    {
                        string token = _manager.GetAuthorizationToken(_user.Guid, _password);

                        result.Result    = "Success";
                        result.AuthToken = token;
                        result.Username  = _username;

                        if (_manager.HasUserRole(_user.Guid, UserRoles.UserAdmin))
                        {
                            result.IsUserAdmin = true;
                        }
                        else
                        {
                            result.IsUserAdmin = false;
                        }

                        if (_manager.HasUserRole(_user.Guid, UserRoles.DataAdmin))
                        {
                            result.IsDataAdmin = true;
                        }
                        else
                        {
                            result.IsDataAdmin = false;
                        }
                    }
                    else
                    {
                        //Bad password or username
                        TraceFileHelper.Warning("User not found");
                        _user = null;

                        result.Result = "BadUserOrPassword";
                    }
                }
                else
                {
                    //user not active
                    //Todo - Log Something
                    TraceFileHelper.Warning("User Not Active");
                    _user = null;

                    result.Result = "NotActive";
                }
            }
            else
            {
                //User not found
                TraceFileHelper.Warning("User not found");
                result.Result = "BadUserOrPassword";
            }

            return(result);
        }
Exemple #19
0
        private void LogUnauthorized(Request _request)
        {
            string username = _request.Headers["Username"].First();

            TraceFileHelper.Warning("{0} - {1} ({2})", _request.UserHostAddress, _request.Url, username);
        }
Exemple #20
0
 public void LogWarning(Guid _userGuid, string _message)
 {
     TraceFileHelper.Warning(_message + "|UserGuid - {0}", _userGuid);
 }