예제 #1
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();
            }
        }
예제 #2
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();
 }
예제 #3
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));
        }
예제 #4
0
파일: Server.cs 프로젝트: prowestgis/upp-wg
        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));
        }
예제 #5
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);
        }
예제 #6
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));
        }
예제 #7
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
            }));
        }
예제 #8
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);
            }
        }
예제 #9
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);
        }
예제 #10
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/"));
        }
        private bool TryToRegister()
        {
            // Get the base url of the service directory host; this is where we send the registration info
            var baseUrl = config.Keyword(Keys.SERVICE_DIRECTORY__BASE_URI);

            // Get the parameters of the service we are registering
            var serviceUri         = config.Keyword(Keys.SERVICE_DIRECTORY__HOST_URI);
            var serviceLabel       = config.Keyword(Keys.SERVICE_DIRECTORY__LABEL);
            var serviceScopes      = config.Keyword(Keys.SERVICE_DIRECTORY__SCOPES);
            var serviceName        = config.Keyword(Keys.SERVICE_DIRECTORY__NAME);
            var serviceType        = (ServiceRegistrationType)config.Keyword(Keys.SERVICE_DIRECTORY__TYPE);
            var servicePriority    = config.Keyword <int>(Keys.SERVICE_DIRECTORY__PRIORITY);
            var serviceFormat      = config.Keyword(Keys.SERVICE_DIRECTORY__FORMAT);
            var serviceDescription = config.Keyword(Keys.SERVICE_DIRECTORY__DESCRIPTION);
            var serviceOAuth       = config.Keyword(Keys.SERVICE_DIRECTORY__OAUTH);
            var serviceToken       = config.Keyword(Keys.SERVICE_DIRECTORY__TOKEN);
            var serviceAuthority   = config.Keyword(AppKeys.UPP_AUTHORITY);

            // Make sure there are actual values passed in
            if (String.IsNullOrEmpty(baseUrl))
            {
                logger.Warn("No service directory URL set in the configuration file. Keyword '{0}'", Keys.SERVICE_DIRECTORY__BASE_URI);
                return(false);
            }

            if (String.IsNullOrEmpty(serviceUri))
            {
                logger.Warn("No service URI is set in the configuration file. Keyword '{0}'", Keys.SERVICE_DIRECTORY__HOST_URI);
                return(false);
            }

            if (String.IsNullOrEmpty(serviceScopes))
            {
                logger.Warn("No service scopes are set in the configuration file. Keyword '{0}'", Keys.SERVICE_DIRECTORY__SCOPES);
                return(false);
            }

            // Split the service URI into a host and a path
            var _serviceUri = new Uri(serviceUri);
            var serviceHost = String.Format("{0}://{1}", _serviceUri.Scheme, _serviceUri.Authority);
            var servicePath = _serviceUri.AbsolutePath;

            // Construct and serialize the JSON document for registering the service
            var body = new ServiceRegistrationRecord
            {
                Kind       = "Service",
                ApiVersion = "v1",
                Metadata   = new ServiceRegistrationMetadata
                {
                    Name = serviceName,                // Unique DNS-style service name, e.g. esri.routing, mndot.bridges, upp.data, etc.
                    Uid  = hostIdentity,               // RFC 4122 UUID assigned to the UPP Systems, e.g. 123e4567-e89b-12d3-a456-426655440000

                    Labels = new ServiceRegistrationLabels
                    {
                        FriendlyName = serviceLabel,     // Human-readable service name, e.g. "Clearwater County UPP Service"
                        Scopes       = serviceScopes,    // space-delimited list of scopes supported by this service
                        Authority    = serviceAuthority, // Assigned name of the UPP authority, e.g. "clearwater_co_mn",
                        Type         = serviceType.Key,  // What service is offered? geometry, routing, data, permit, etc.
                        Format       = serviceFormat     // Everything using this API provides data services
                    },
                    Annotations = new ServiceRegistrationAnnotations
                    {
                        Description = serviceDescription,
                        Priority    = servicePriority, // Priority of this service
                        OAuthId     = serviceOAuth,    // If this service uses one of the OAuth backend providers
                        TokenId     = serviceToken     // If this service uses one of the token backend providers
                    }
                },
                Spec = new ServiceRegistrationSpec
                {
                    Type         = "ExternalName",
                    ExternalName = serviceHost,
                    Path         = servicePath
                }
            };

            // Get just the host name for the services directory REST endpoint
            var _servicesDirectoryUri = new Uri(baseUrl);

            // Try to POST our registration information to the service directory
            var client  = new RestClient(String.Format("{0}://{1}", _servicesDirectoryUri.Scheme, _servicesDirectoryUri.Authority));
            var request = new RestRequest(String.Format("{0}/{1}", _servicesDirectoryUri.AbsolutePath, "services"), Method.POST);

            request.RequestFormat = DataFormat.Json;
            request.AddBody(body);

            logger.Debug("Attempting to register with service directory at {0}{1}", client.BaseUrl, request.Resource);
            logger.Debug("POST {0}", request.Resource);

            // Sending the request now....
            lastRequest = DateTime.Now;

            // Get the response and see if we were able to register outselves
            var response = client.Execute(request);

            logger.Debug(request.Parameters.Find(param => param.Type == ParameterType.RequestBody).Value.ToString());
            logger.Debug("Service Directory Response: {0}", response.Content);

            // Parse the response
            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return(false);
            }

            // Success!!
            return(true);
        }