public ExceptionCategorySettings(ExceptionManager parent, HostConfigurationSection categoryKey, string categoryName)
            {
                _parent                   = parent;
                this.CategoryName         = categoryName;
                this.DefaultCategoryState = RegistryToExceptionBreakpointState(categoryKey.GetValue("*"));
                Dictionary <string, ExceptionBreakpointState> exceptionSettings = new Dictionary <string, ExceptionBreakpointState>();

                foreach (string valueName in categoryKey.GetValueNames())
                {
                    if (string.IsNullOrEmpty(valueName) || valueName == "*" || !ExceptionManager.IsSupportedException(valueName))
                    {
                        continue;
                    }

                    ExceptionBreakpointState value = RegistryToExceptionBreakpointState(categoryKey.GetValue(valueName));
                    if (value == this.DefaultCategoryState)
                    {
                        Debug.Fail("Redundant exception trigger found in the registry.");
                        continue;
                    }

                    exceptionSettings.Add(valueName, value);
                }
                this.DefaultRules = new ReadOnlyDictionary <string, ExceptionBreakpointState>(exceptionSettings);
                _settingsUpdate   = new SettingsUpdates(this.DefaultCategoryState, this.DefaultRules);
            }
Exemple #2
0
        public DashboardView(Services services, HostConfigurationSection config, NancyContext context)
        {
            ServiceDirectoryUrl = config.Keyword(Keys.SERVICE_DIRECTORY__BASE_URI);
            Logins = services.AuthenticationProviders.Select(x => new PrimaryLogin
            {
                Name  = x.DisplayName,
                Url   = String.Format("/authentication/redirect/{0}", x.Name),
                Image = String.Format("/images/{0}-login-button.png", x.Name)
            }).ToList();

            User = context.CurrentUser as AuthUser;

            logger.Debug("Dashboard user is {0}", User == null ? "NULL" : User.UserName);

            // List the active OAuth credentials and registered microservices
            Auths = services.AuthenticationProviders.ToList();
            //MicroServices = services.MicroServices.ToList();

            var baseUrl = config.Keyword(Keys.NANCY__HOST_BASE_URI);

            if (User == null)
            {
                Permits = Enumerable.Empty <PermitBundle>().ToList();
            }
            else
            {
                Permits = services
                          .FindPermitBundles(User.ExtendedClaims["upp"] as string, config.Keyword(Keys.UPP__PERMIT_REPOSITORY_URL_TEMPLATE))
                          .Select(x => { x.RepositoryName = String.Format("{0}permits/{1}", baseUrl, x.PermitId); return(x); })
                          .ToList();
            }
        }
Exemple #3
0
        public Server(HostConfigurationSection config)
        {
            // Get the host URI to bind Nancy to
            var hostUri = config.Keyword(Keys.NANCY__BASE_URI);

            logger.Debug("Creating NancyHost");
            host = new NancyHost(hostConfig, new Uri(hostUri));
        }
Exemple #4
0
        public Frontend(Services services, AuthSettings authSettings, HostConfigurationSection config)
        {
            _authSettings = authSettings;

            Get["/"] = _ => View["Index", new DashboardView(services, config, Context)];
            Get["/dashboard.html"]        = _ => View["Index", new DashboardView(services, config, Context)];
            Get["/authentication/logout"] = _ => Logout(config.Keyword(Keys.NANCY__HOST_BASE_URI));
        }
Exemple #5
0
        public PermitApplication(Services services, HostConfigurationSection config)
        {
            this.RequiresAuthentication();
            this.RequiresClaims(new[] { Claims.HAULER });

            Get["/permit.html"]    = _ => View["Permit", new PermitView(services, Context)];
            Get["/permits/{guid}"] = _ => View["SinglePermit", new SinglePermitView(services, config, Context.CurrentUser as AuthUser, _.guid)];
        }
        public RegisterWithServiceDirectory(string hostIdentity, HostConfigurationSection config, TimeSpan retry, TimeSpan ping)
        {
            lastRequest  = DateTime.MinValue;
            lastCallback = DateTime.Now;

            this.hostIdentity = hostIdentity;
            this.config       = config;
            this.retry        = retry;
            this.ping         = ping;
        }
Exemple #7
0
        private Response UpdateConfiguration(HostConfigurationSection config)
        {
            // Bind the request to the configuration update record
            var record = this.Bind <ConfigurationUpdateRecord>();

            // Update the module configuration
            Configuration.Behavior = record.Behavior;

            // Redirect to the main page
            return(new Nancy.Responses.RedirectResponse("/"));
        }
Exemple #8
0
        public Server(HostConfigurationSection config)
        {
            // Get the host URI to bind Nancy to
            var hostUri = config.Keyword(Keys.NANCY__BASE_URI);

            logger.Debug("Creating NancyHost on {0}", hostUri);
            host = new NancyHost(hostConfig, new Uri(hostUri));

            logger.Debug("Creating data store instance");
            database = new Manager.Store.Services(config);
        }
Exemple #9
0
        public AdministrativeInterface(Services services, HostConfigurationSection config)
        {
            this.RequiresAuthentication();
            this.RequiresClaims(new[] { Claims.UPP_ADMIN });

            Get["/admin.html"]       = _ => View["Administration", new AdministrativeView {
                                                     Users = services.AllUsers()
                                                 }];
            Get["/users/{id}/edit"]  = _ => View["EditUser", services.AllUsers().FirstOrDefault(x => x.UserId == _.id)];
            Post["/users/{id}/edit"] = _ => UpdateUser(services, config.Keyword(Keys.NANCY__HOST_BASE_URI));
        }
Exemple #10
0
        public PermitModule(Database database, HostConfigurationSection config) : base("/api/v1/issue")
        {
            // Need a valid JWT to access
            //this.RequiresAuthentication();

            // Accept a new application from the user
            Post["/"] = _ => ProcessApplication(database, config);

            Get["/{id}"]  = _ => View["Permit", FetchPermit(database, config, Context.CurrentUser as AuthUser, int.Parse(_.id))];
            Post["/{id}"] = _ => UpdateApplication(database, config, Context.CurrentUser as AuthUser, _.id);
        }
Exemple #11
0
        private static void StartServer(HostConfigurationSection config)
        {
            var server = new Server(config);

            server.Start();

            Console.WriteLine("Press any key to stop the services");
            Console.Read();
            Console.WriteLine();

            server.Stop();
        }
Exemple #12
0
        private Response ProcessApplication(Database database, HostConfigurationSection config)
        {
            var identifier = config.Keyword(Keys.SELF__IDENTIFIER);
            var status     = EvaluatePermit(Context, database, config);

            return(Response.AsJson(new PermitApprovalRecord
            {
                Timestamp = DateTime.Now,
                Status = status,
                Authority = identifier
            }));
        }
Exemple #13
0
        public WebModule(Database database, HostConfigurationSection config)
        {
            // Need a valid JWT to access
            // this.RequiresAuthentication();

            // Provide a view for configuring the issuer's behavior
            Get["/"]  = _ => View["Index", new WebModuleViewModel {
                                      Configuration = config, ModuleConfiguration = Configuration
                                  }];
            Post["/"] = _ => UpdateConfiguration(config);

            Get["/permits"] = _ => View["Permits", new ActivePermitView(database, Context)];
        }
        public WebModule(HostConfigurationSection config, Database database)
        {
            // Need a valid JWT to access
            //this.RequiresAuthentication();
            //this.RequiresClaims(new[] { Claims.UPP_ADMIN });

            // Provide a view for configuring the issuer's behavior
            Get["/"]            = _ => View["Index", new MainViewModel {
                                                Configuration = config
                                            }];
            Get["/data/query"]  = _ => Response.AsJson(QueryDatabase(database));
            Get["/users/query"] = _ => Response.AsJson(QueryUsers(database));
        }
Exemple #15
0
        public SinglePermitView(Services services, HostConfigurationSection config, AuthUser user, string permitIdentifier)
        {
            var baseUri = config.Keyword(Keys.NANCY__HOST_BASE_URI);

            using (var context = new CurrentRepositoryContext(services, config, user, permitIdentifier))
            {
                var path = Path.Combine(context.Repository.Info.WorkingDirectory, "permit.json");
                var json = JObject.Parse(File.ReadAllText(path));

                // Extract the relevant information about the permit
                Email = (string)json["data"]["attributes"]["form-data"]["haulerInfo.email"];
                User  = user;

                // Get the attachments
                var info = new DirectoryInfo(Path.Combine(context.Repository.Info.WorkingDirectory, "attachments"));
                Attachments = info.GetFiles().ToDictionary(x => x.Name, x => String.Format("{0}api/permits/{1}/attachments/{2}", baseUri, permitIdentifier, x.Name));

                AttachmentPost = String.Format("{0}api/permits/{1}/attachments", baseUri, permitIdentifier);
                SoftCopyUrl    = String.Format("{0}api/permits/{1}/package", baseUri, permitIdentifier);
            }
        }
Exemple #16
0
        private Response UpdateApplication(Database database, HostConfigurationSection config, AuthUser user, int id)
        {
            // Configuration parameters
            var workspace       = config.Keyword(Keys.UPP__PERMIT_WORKSPACE);
            var repoUrlTemplate = config.Keyword(Keys.UPP__PERMIT_REPOSITORY_URL_TEMPLATE);
            var issuerId        = config.Keyword(Keys.SELF__IDENTIFIER);

            // Find the record
            var bundle = database.ApplicationById(id);

            // Generate the repository path
            var repoPath = Path.Combine(workspace, bundle.Application.Id);

            // If the repository does not already exists, clone it
            if (!Directory.Exists(repoPath))
            {
                Repository.Clone(bundle.Application.Links.Origin, repoPath);
            }

            JObject permit = null;
            string  path;

            using (var repo = new Repository(repoPath))
            {
                // Update the checkout
                var author      = new Signature(user.UserName, user.Email, DateTime.Now);
                var mergeResult = Commands.Pull(repo, author, new PullOptions());

                // Read the current permit file and return
                path   = Path.Combine(repo.Info.WorkingDirectory, "permit.json");
                permit = JObject.Parse(File.ReadAllText(path));
            }
            // Convert the form into a PermitApplicationRecord
            var permitForm = Context.ToPermitDataRecord();

            var authorities = permit.SelectToken("data.attributes.authorities");
            var mySection   = authorities.SelectToken(issuerId);
            var formSection = permit.SelectToken("data.attributes.form-data");

            if (mySection == null)
            {
                (permit.SelectToken("data.attributes.authorities") as JObject).Add(issuerId, new JObject());
                mySection = authorities.SelectToken(issuerId);
            }
            permit.SelectToken("data.attributes")["route"] = (JObject.Parse(permitForm.Route));
            mySection["route"]    = JObject.Parse(permitForm.Route);
            mySection["status"]   = PermitStatus.Text(int.Parse(permitForm.Status));
            mySection["reviewed"] = DateTime.Now;

            formSection["movementInfo.startDate"]                = permitForm.Movement.StartDate;
            formSection["movementInfo.endDate"]                  = permitForm.Movement.EndDate;
            formSection["movementInfo.haulingHours"]             = permitForm.Movement.HaulingHours;
            formSection["movementInfo.origin"]                   = permitForm.Movement.Origin;
            formSection["movementInfo.destination"]              = permitForm.Movement.Destination;
            formSection["movementInfo.routeDescription"]         = permitForm.Movement.RouteDescription;
            formSection["movementInfo.routeCountyNumbers"]       = permitForm.Movement.RouteCountyNumbers;
            formSection["movementInfo.milesOfCountyRoad"]        = permitForm.Movement.MilesOfCountyRoad;
            formSection["movementInfo.routeLength"]              = permitForm.Movement.RouteLength;
            formSection["movementInfo.stateHighwayPermitNumber"] = permitForm.Movement.StateHighwayPermitNumber;
            formSection["movementInfo.stateHighwayPermitIssued"] = permitForm.Movement.StateHighwayPermitIssued;

            // Serialize all of the information into a JSON string
            var json = permit.ToJson();

            // Serialize the json content back to the file
            File.WriteAllText(path, JsonConvert.SerializeObject(permit, Formatting.Indented));

            // Commit the changes
            using (var repo = new Repository(repoPath))
            {
                Commands.Stage(repo, path);

                var author    = new Signature(user.UserName, user.Email, DateTime.Now);
                var committer = author;

                // Commit the files to the and push to the origin
                var commit = repo.Commit("Update the permit form data", author, committer);

                var options = new PushOptions();
                repo.Network.Push(repo.Branches["master"], options);
            }
            // Add the permit to the database
            database.UpdateApplication(json, id, Context.Request.Form["status"]);

            return(new Nancy.Responses.RedirectResponse("../../../../permits/"));
        }
Exemple #17
0
 public UPPAuthenticationCallbackProvider(AuthSettings authSettings, Services services, HostConfigurationSection config)
 {
     _authSettings   = authSettings;
     _services       = services;
     _baseUrl        = config.Keyword(Keys.NANCY__HOST_BASE_URI) ?? "/";
     _administrators = config.Keyword(Keys.UPP__ADMINISTRATORS).Split(';').Select(x => x.Trim()).ToList();
 }
        public static Func <NancyContext, Response> GetPipelineHook(string hostIdentity, HostConfigurationSection config)
        {
            var handler = new RegisterWithServiceDirectory(hostIdentity, config);

            // Try to make an initial connection to the Service Registry
            handler.InitialRegistration();

            return(ctx =>
            {
                // Try to register
                handler.PipelineCallback();

                // Never terminate the pipeline
                return null;
            });
        }
 public RegisterWithServiceDirectory(string hostIdentity, HostConfigurationSection config)
     : this(hostIdentity, config, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(15))
 {
 }
Exemple #20
0
        private PermitApplication FetchPermit(Database services, HostConfigurationSection config, AuthUser user, int permitIdentifier)
        {
            // Configuration parameters
            var workspace       = config.Keyword(Keys.UPP__PERMIT_WORKSPACE);
            var repoUrlTemplate = config.Keyword(Keys.UPP__PERMIT_REPOSITORY_URL_TEMPLATE);

            // Find the record
            var bundle = services.ApplicationById(permitIdentifier); //.FetchPermitBundle(user.ExtendedClaims["upp"] as string, repoUrlTemplate, permitIdentifier);

            // Generate the repository path
            var repoPath = Path.Combine(workspace, bundle.Application.Id);

            // If the repository does not already exists, clone it
            if (!Directory.Exists(repoPath))
            {
                Repository.Clone(bundle.Application.Links.Origin, repoPath);
            }

            using (var repo = new Repository(repoPath))
            {
                // Update the checkout
                var author      = new Signature(user.UserName, user.Email, DateTime.Now);
                var mergeResult = Commands.Pull(repo, author, new PullOptions());

                // Read the current permit file and return
                var    permitPath = Path.Combine(repo.Info.WorkingDirectory, "permit.json");
                var    permit     = JObject.Parse(File.ReadAllText(permitPath));
                var    form       = permit.SelectToken("data.attributes.form-data");
                var    hauler     = form["haulerInfo.name"];
                string name       = hauler.Value <string>();
                bundle.PermitData                         = new PermitDataRecord();
                bundle.PermitData.Hauler.Name             = form["haulerInfo.name"].Value <string>();
                bundle.PermitData.Hauler.Date             = form["haulerInfo.date"].Value <DateTime>();
                bundle.PermitData.Hauler.Email            = form["haulerInfo.email"].Value <string>();
                bundle.PermitData.Hauler.Phone            = form["haulerInfo.phone"].Value <string>();
                bundle.PermitData.Hauler.Fax              = form["haulerInfo.fax"].Value <string>();
                bundle.PermitData.Company.Name            = form["companyInfo.name"].Value <string>();
                bundle.PermitData.Company.Address         = form["companyInfo.address"].Value <string>();
                bundle.PermitData.Company.Email           = form["companyInfo.email"].Value <string>();
                bundle.PermitData.Company.Contact         = form["companyInfo.contact"].Value <string>();
                bundle.PermitData.Company.Phone           = form["companyInfo.phone"].Value <string>();
                bundle.PermitData.Company.Fax             = form["companyInfo.fax"].Value <string>();
                bundle.PermitData.Insurance.Provider      = form["insuranceInfo.provider"].Value <string>();
                bundle.PermitData.Insurance.AgencyAddress = form["insuranceInfo.agencyAddress"].Value <string>();
                bundle.PermitData.Insurance.PolicyNumber  = form["insuranceInfo.policyNumber"].Value <string>();
                bundle.PermitData.Vehicle.Make            = form["vehicleInfo.make"].Value <string>();
                bundle.PermitData.Vehicle.Type            = form["vehicleInfo.type"].Value <string>();
                bundle.PermitData.Vehicle.License         = form["vehicleInfo.license"].Value <string>();
                bundle.PermitData.Vehicle.State           = form["vehicleInfo.state"].Value <string>();
                bundle.PermitData.Vehicle.SerialNumber    = form["vehicleInfo.serialNumber"].Value <string>();
                bundle.PermitData.Vehicle.USDOTNumber     = form["vehicleInfo.USDOTNumber"].Value <string>();
                //form["vehicleInfo.emptyWeight"].Value<string>();

                bundle.PermitData.Truck.GrossWeight          = form["truckInfo.grossWeight"].Value <decimal>();
                bundle.PermitData.Truck.DimensionSummary     = form["truckInfo.dimensionSummary"].Value <string>();
                bundle.PermitData.Truck.DimensionDescription = form["truckInfo.dimensionDescription"].Value <string>();
                bundle.PermitData.Truck.Height        = form["truckInfo.height"].Value <decimal>();
                bundle.PermitData.Truck.Width         = form["truckInfo.width"].Value <decimal>();
                bundle.PermitData.Truck.Length        = form["truckInfo.length"].Value <decimal>();
                bundle.PermitData.Truck.FrontOverhang = form["truckInfo.frontOverhang"].Value <decimal>();
                bundle.PermitData.Truck.RearOverhang  = form["truckInfo.rearOverhang"].Value <decimal>();
                bundle.PermitData.Truck.LeftOverhang  = form["truckInfo.leftOverhang"].Value <decimal>();
                bundle.PermitData.Truck.RightOverhang = form["truckInfo.rightOverhang"].Value <decimal>();
                //form["truckInfo.diagram"].Value<string>();
                //form["truckInfo.weightPerAxle"].Value<string>();
                //form["truckInfo.axleCount"].Value<string>();
                //form["truckInfo.axleLength"].Value<string>();
                //form["truckInfo.maxAxleWidth"].Value<string>();
                //form["truckInfo.maxAxleWeight"].Value<string>();
                //form["truckInfo.totalAxleWeight"].Value<string>();
                //form["truckInfo.axleGroupTireType"].Value<string>();
                bundle.PermitData.Trailer.Make          = form["trailerInfo.make"].Value <string>();
                bundle.PermitData.Trailer.Type          = form["trailerInfo.type"].Value <string>();
                bundle.PermitData.Trailer.LicenseNumber = form["trailerInfo.licenseNumber"].Value <string>();
                bundle.PermitData.Trailer.State         = form["trailerInfo.state"].Value <string>();
                //form["trailerInfo.emptyWeight"].Value<string>();
                bundle.PermitData.Trailer.WeightPerAxle = form["trailerInfo.weightPerAxle"].Value <decimal>();
                //form["trailerInfo.axleCount"].Value<string>();
                //form["trailerInfo.axleLength"].Value<string>();
                //form["trailerInfo.maxAxleWidth"].Value<string>();
                //form["trailerInfo.maxAxleWeight"].Value<string>();
                bundle.PermitData.Trailer.TotalAxleWeight = form["trailerInfo.totalAxleWeight"].Value <decimal>();
                //form["trailerInfo.axleGroupTireType"].Value<string>();
                bundle.PermitData.Load.Description          = form["loadInfo.description"].Value <string>();
                bundle.PermitData.Movement.StartDate        = form["movementInfo.startDate"].Value <DateTime>();
                bundle.PermitData.Movement.EndDate          = form["movementInfo.endDate"].Value <DateTime>();
                bundle.PermitData.Movement.HaulingHours     = form["movementInfo.haulingHours"].Value <decimal>();
                bundle.PermitData.Movement.Origin           = form["movementInfo.origin"].Value <string>();
                bundle.PermitData.Movement.Destination      = form["movementInfo.destination"].Value <string>();
                bundle.PermitData.Movement.RouteDescription = form["movementInfo.routeDescription"].Value <string>();
                //bundle.PermitData.Movement.RouteCountyNumbers = form["movementInfo.routeCountyNumbers"].Value<string>();
                //bundle.PermitData.Movement.MilesOfCountyRoad = form["movementInfo.milesOfCountyRoad"].Value<string>();
                bundle.PermitData.Movement.RouteLength = form["movementInfo.routeLength"].Value <decimal>();
                bundle.PermitData.Movement.StateHighwayPermitNumber = form["movementInfo.stateHighwayPermitNumber"].Value <string>();
                bundle.PermitData.Movement.StateHighwayPermitIssued = form["movementInfo.stateHighwayPermitIssued"].Value <string>();

                bundle.PermitData.Route = permit.SelectToken("data.attributes.route").ToJson();
                //return bundle; //JObject.Parse(File.ReadAllText(permit));
            }
            return(bundle);
        }
Exemple #21
0
        private static string DefaultPermitEvaluation(NancyContext context, Database database, HostConfigurationSection config)
        {
            switch (WebModule.Configuration.Behavior)
            {
            case "always": return(PermitApprovalStatus.APPROVED);

            case "random": return(PermitApprovalStatus.RANDOM);

            case "na": return(PermitApprovalStatus.NO_AUTHORITY);

            case "no_authority": return(PermitApprovalStatus.NO_AUTHORITY);

            case "under_review": return(PermitApprovalStatus.UNDER_REVIEW);

            default:
            case "never": return(PermitApprovalStatus.DENIED);
            }
        }
Exemple #22
0
 public Services(HostConfigurationSection config)
     : base("SimpleDb.sqlite", @"App_Data\Schema.sql", config)
 {
 }
Exemple #23
0
 public Database(HostConfigurationSection config)
     : base("Permits.sqlite", @"App_Data\Schema.sql", config)
 {
 }
Exemple #24
0
        private static string MockPermitEvaluation(NancyContext context, Database database, HostConfigurationSection config)
        {
            try
            {
                // Convert the form into a PermitApplicationRecord
                var permit = context.ToPermitApplicationRecord();

                // Serialize all of the information into a JSON string
                var json = permit.ToJson();

                // Add the permit to the database
                database.CreatePermitForUser(context.CurrentUser, json);
            }
            catch (Exception e)
            {
                logger.Error(e, "Failed to create permit application");
                return(PermitApprovalStatus.DENIED);
            }

            return(PermitApprovalStatus.UNDER_REVIEW);
        }
Exemple #25
0
 public Database(HostConfigurationSection config)
     : base("CompanyInformation.sqlite", @"App_Data\Schema.sql", config)
 {
 }