private IAuthClient CreateOsmGateway(TokenAndSecret tokenAndSecret)
 {
     return(_clientsFactory.CreateOAuthClient(_options.OsmConfiguration.ConsumerKey,
                                              _options.OsmConfiguration.ConsumerSecret,
                                              tokenAndSecret.Token,
                                              tokenAndSecret.TokenSecret));
 }
Esempio n. 2
0
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            var token          = securityToken.Split(';').First().Trim('"');
            var tokenSecret    = securityToken.Split(';').Last().Trim('"');
            var tokenAndSecret = new TokenAndSecret(token, tokenSecret);
            var userId         = string.Empty;

            // https://www.tabsoverspaces.com/233703-named-locks-using-monitor-in-net-implementation/
            // https://stackoverflow.com/questions/55188959/what-are-the-options-for-named-locks-in-net-core
            lock (string.Intern(tokenAndSecret.ToString()))
            {
                userId = _cache.ReverseGet(tokenAndSecret);
                if (string.IsNullOrEmpty(userId))
                {
                    var osmGateway = _clientsFactory.CreateOAuthClient(_options.OsmConfiguration.ConsumerKey, _options.OsmConfiguration.ConsumerSecret, tokenAndSecret.Token, tokenAndSecret.TokenSecret);
                    var user       = osmGateway.GetUserDetails().Result;
                    userId = user.Id.ToString();
                    _logger.LogInformation($"User {userId} had just logged in");
                    _cache.Add(userId, tokenAndSecret);
                }
            }
            validatedToken = new JwtSecurityToken();
            if (string.IsNullOrWhiteSpace(userId))
            {
                throw new ArgumentException("Invalid user id", nameof(securityToken));
            }
            var identity = new ClaimsIdentity("Osm");

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId));
            identity.AddClaim(new Claim(ClaimTypes.Name, userId));

            return(new ClaimsPrincipal(identity));
        }
Esempio n. 3
0
        private IAuthClient SetupOAuthClient()
        {
            var osmGateWay = Substitute.For <IAuthClient>();

            _clientsFactory.CreateOAuthClient(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>()).Returns(osmGateWay);
            return(osmGateWay);
        }
Esempio n. 4
0
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            var token          = securityToken.Split(';').First().Trim('"');
            var tokenSecret    = securityToken.Split(';').Last().Trim('"');
            var tokenAndSecret = new TokenAndSecret(token, tokenSecret);
            var userId         = _cache.ReverseGet(tokenAndSecret);

            if (string.IsNullOrEmpty(userId))
            {
                var osmGateway = _clientsFactory.CreateOAuthClient(_options.OsmConfiguration.ConsumerKey, _options.OsmConfiguration.ConsumerSecret, tokenAndSecret.Token, tokenAndSecret.TokenSecret);
                var user       = osmGateway.GetUserDetails().Result;
                userId = user.Id.ToString();
                _logger.LogInformation("User " + userId + " had just logged in");
                _cache.Add(userId, tokenAndSecret);
            }
            validatedToken = new JwtSecurityToken();
            if (string.IsNullOrWhiteSpace(userId))
            {
                throw new ArgumentException("Invalid user id", nameof(securityToken));
            }
            var identity = new ClaimsIdentity("Osm");

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId));
            identity.AddClaim(new Claim(ClaimTypes.Name, userId));

            return(new ClaimsPrincipal(identity));
        }
        private IAuthClient SetupHttpFactory()
        {
            var gateway = Substitute.For <IAuthClient>();

            _clientsFactory.CreateOAuthClient(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>()).Returns(gateway);
            return(gateway);
        }
Esempio n. 6
0
        public async Task <IActionResult> UploadPointOfInterest([FromBody] PointOfInterestExtended pointOfInterest,
                                                                [FromQuery] string language)
        {
            if (!pointOfInterest.Source.Equals(Sources.OSM, StringComparison.InvariantCultureIgnoreCase))
            {
                return(BadRequest("OSM is the only supported source for this action..."));
            }
            if ((pointOfInterest.Description?.Length ?? 0) > 255)
            {
                return(BadRequest("Description must not be more than 255 characters..."));
            }
            if ((pointOfInterest.Title?.Length ?? 0) > 255)
            {
                return(BadRequest("Title must not be more than 255 characters..."));
            }
            var tokenAndSecret = _cache.Get(User.Identity.Name);
            var osmGateway     = _clientsFactory.CreateOAuthClient(_options.OsmConfiguration.ConsumerKey, _options.OsmConfiguration.ConsumerSecret, tokenAndSecret.Token, tokenAndSecret.TokenSecret);
            var user           = await osmGateway.GetUserDetails();

            var imageUrls = pointOfInterest.ImagesUrls ?? new string[0];

            for (var urlIndex = 0; urlIndex < imageUrls.Length; urlIndex++)
            {
                var fileName = string.IsNullOrWhiteSpace(pointOfInterest.Title)
                    ? pointOfInterest.Icon.Replace("icon-", "")
                    : pointOfInterest.Title;
                var file = _base64ImageConverter.ConvertToFile(imageUrls[urlIndex], fileName);
                if (file == null)
                {
                    continue;
                }
                using (var md5 = MD5.Create())
                {
                    var imageUrl = await _imageUrlStoreExecutor.GetImageUrlIfExists(md5, file.Content);

                    if (imageUrl != null)
                    {
                        imageUrls[urlIndex] = imageUrl;
                        continue;
                    }
                    using (var memoryStream = new MemoryStream(file.Content))
                    {
                        var imageName = await _wikimediaCommonGateway.UploadImage(pointOfInterest.Title,
                                                                                  pointOfInterest.Description, user.DisplayName, file.FileName, memoryStream,
                                                                                  pointOfInterest.Location.ToCoordinate());

                        imageUrls[urlIndex] = await _wikimediaCommonGateway.GetImageUrl(imageName);

                        await _imageUrlStoreExecutor.StoreImage(md5, file.Content, imageUrls[urlIndex]);
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(pointOfInterest.Id))
            {
                return(Ok(await _pointsOfInterestProvider.AddPointOfInterest(pointOfInterest, tokenAndSecret, language)));
            }
            return(Ok(await _pointsOfInterestProvider.UpdatePointOfInterest(pointOfInterest, tokenAndSecret, language)));
        }
Esempio n. 7
0
        private IAuthClient SetupOsmGateway(long changesetId)
        {
            var osmGateway = Substitute.For <IAuthClient>();

            osmGateway.CreateChangeset(Arg.Any <TagsCollection>()).Returns(changesetId);
            _clientsFactory.CreateOAuthClient(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>()).Returns(osmGateway);
            return(osmGateway);
        }
Esempio n. 8
0
        private int SetupGpxUrl(GpxFile gpx, List <LineString> addibleLines = null)
        {
            int traceId      = 1;
            var fetcher      = Substitute.For <IAuthClient>();
            var fileResponse = new TypedStream
            {
                FileName = "file.gpx",
                Stream   = new MemoryStream(new byte[0])
            };

            fetcher.GetTraceData(traceId).Returns(fileResponse);
            _dataContainerConverterService.Convert(Arg.Any <byte[]>(), Arg.Any <string>(), Arg.Any <string>())
            .Returns(gpx.ToBytes());
            _clientsFactory.CreateOAuthClient(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>()).Returns(fetcher);
            _addibleGpxLinesFinderService.GetLines(Arg.Any <List <LineString> >()).Returns(
                addibleLines ?? new List <LineString>
            {
                new LineString(new[] { new Coordinate(0, 0), new Coordinate(1, 1) })
            }.AsEnumerable()
                );
            return(traceId);
        }
Esempio n. 9
0
        /// <inheritdoc/>
        public async Task Add(LineString line, Dictionary <string, string> tags, TokenAndSecret tokenAndSecret)
        {
            _osmGateway = _osmApiClientsFactory.CreateOAuthClient(_options.OsmConfiguration.ConsumerKey, _options.OsmConfiguration.ConsumerSecret, tokenAndSecret.Token, tokenAndSecret.TokenSecret);
            var createdElements = new List <OsmGeo>();
            var modifiedElement = new List <OsmGeo>();
            int generatedId     = -1;
            var newWayNodes     = new List <Node>();
            var highways        = await GetHighwaysInArea(line);

            var itmHighways     = highways.Select(ToItmLineString).ToList();
            var waysToUpdateIds = new List <long?>();

            for (int coordinateIndex = 0; coordinateIndex < line.Coordinates.Length; coordinateIndex++)
            {
                var coordinate = line.Coordinates[coordinateIndex];
                if (coordinateIndex > 0)
                {
                    var previousCoordinate = line.Coordinates[coordinateIndex - 1];
                    AddIntersectingNodes(previousCoordinate, coordinate, newWayNodes, itmHighways, highways);
                }
                var closetHighway = GetClosetHighway(coordinate, itmHighways, highways);
                if (closetHighway == null)
                {
                    // no close highways, adding a new node
                    var node = new Node {
                        Id = generatedId--, Latitude = coordinate.Y, Longitude = coordinate.X
                    };
                    createdElements.Add(node);
                    newWayNodes.Add(node);
                    continue;
                }
                var itmPoint             = GetItmCoordinate(coordinate);
                var closestItmHighway    = itmHighways.First(hw => hw.GetOsmId() == closetHighway.GetOsmId());
                var closestItmPointInWay = closestItmHighway.Coordinates.OrderBy(c => c.Distance(itmPoint.Coordinate)).First();
                var indexOnWay           = closestItmHighway.Coordinates.ToList().IndexOf(closestItmPointInWay);
                var closestNode          = CreateNodeFromExistingHighway(closetHighway, indexOnWay);
                if (!CanAddNewNode(newWayNodes, closestNode.Id.Value))
                {
                    continue;
                }
                if (closestItmPointInWay.Distance(itmPoint.Coordinate) <= _options.MaxDistanceToExisitngLineForMerge)
                {
                    // close highway, adding the node id from that highway
                    newWayNodes.Add(closestNode);
                    continue;
                }
                // need to add a new node to existing highway
                var newNode = new Node {
                    Id = generatedId--, Latitude = coordinate.Y, Longitude = coordinate.X
                };
                createdElements.Add(newNode);
                newWayNodes.Add(newNode);
                var indexToInsert = GetIndexToInsert(indexOnWay, closestItmHighway, itmPoint);
                if (modifiedElement.FirstOrDefault(w => w.Id == closestItmHighway.GetOsmId()) is Way modifiedWay &&
                    modifiedWay.Nodes[indexToInsert] < 0)
                {
                    // a new node was added to this highway - no reason to add a new one to the same location
                    continue;
                }
                var simpleWay = await AddNewNodeToExistingWay(newNode.Id.ToString(), closestItmHighway.GetOsmId(), indexToInsert);

                modifiedElement.Add(simpleWay);
                waysToUpdateIds.Add(simpleWay.Id);
            }
            CloseLoopWithStartPointIfNeeded(newWayNodes);
            var newWay = CreateWay(newWayNodes, tags, generatedId--);

            createdElements.Add(newWay);
            waysToUpdateIds.Add(newWay.Id);

            var changes = new OsmChange
            {
                Create = createdElements.ToArray(),
                Modify = modifiedElement.ToArray(),
                Delete = new OsmGeo[0]
            };
            var changesetId = await _osmGateway.CreateChangeset(CreateCommentFromTags(tags));

            try
            {
                var diffResult = await _osmGateway.UploadChangeset(changesetId, changes);

                waysToUpdateIds = waysToUpdateIds.Select(id =>
                {
                    var newIdResult = diffResult.Results.FirstOrDefault(r => r.OldId.Equals(id));
                    return(newIdResult?.NewId ?? id);
                }).ToList();
                await AddWaysToElasticSearch(waysToUpdateIds);
            }
            finally
            {
                await _osmGateway.CloseChangeset(changesetId);
            }
        }
Esempio n. 10
0
        private IAuthClient CreateClient()
        {
            var user = _cache.Get(User.Identity.Name);

            return(_clientsFactory.CreateOAuthClient(_options.OsmConfiguration.ConsumerKey, _options.OsmConfiguration.ConsumerSecret, user.Token, user.TokenSecret));
        }
Esempio n. 11
0
        private IAuthClient CreateOsmGateway()
        {
            var token = _cache.Get(User.Identity.Name);

            return(_clentsFactory.CreateOAuthClient(_options.OsmConfiguration.ConsumerKey, _options.OsmConfiguration.ConsumerSecret, token.Token, token.TokenSecret));
        }