Beispiel #1
0
        public async Task <IActionResult> Аuthorize()
        {
            ObjectId currentUser  = ObjectId.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
            var      gitHubClient = _githubClientService.GetGitHubClient(currentUser);

            var db             = _mongoService.GetDb;
            var csrfCollection = db.GetCollection <CSRF>(_mongoService.GetDBSettings.OGitAuthCollectionName);


            var    tokenHandler = new JwtSecurityTokenHandler();
            var    key          = Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:Secret").Value);
            Random random       = new Random();
            bool   csrfUnique   = false;
            string csrf;

            do
            {
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, random.Next(10000, 3000000) + ""),
                        new Claim(ClaimTypes.NameIdentifier, random.Next(10000, 3000000) + ""),
                        new Claim(ClaimTypes.UserData, random.Next(10000, 3000000) + "")
                    }),
                    Expires            = DateTime.UtcNow.AddDays(14),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
                };
                var createdToken = tokenHandler.CreateToken(tokenDescriptor);
                csrf = tokenHandler.WriteToken(createdToken);

                // check:
                var csrfFilter = Builders <CSRF> .Filter.Eq(c => c.Csrf, csrf);

                var results = (await csrfCollection.FindAsync <CSRF>(csrfFilter)).ToList();
                if (results.Count > 0)
                {
                    csrfUnique = false;
                }
                else
                {
                    await csrfCollection.InsertOneAsync(new CSRF { Csrf = csrf, UserId = currentUser });
                }
            } while (csrfUnique);

            var userCollection = db.GetCollection <Models.User>(_mongoService.GetDBSettings.UserCollectionName);
            var filter         = Builders <Models.User> .Filter.Eq(u => u.Id, currentUser);

            var update = Builders <Models.User> .Update.Set("CSRF", csrf);

            await userCollection.UpdateOneAsync(filter, update);

            var request = new OauthLoginRequest(_configuration.GetSection("GithubOAuth:ClientId").Value)
            {
                Scopes = { "repo", "notifications", "user" },
                State  = csrf
            };
            var oauthLoginUrl = gitHubClient.Oauth.GetGitHubLoginUrl(request);

            //Microsoft.AspNetCore.Session["CSRF:State"] = csrf;

            return(Ok(oauthLoginUrl));
        }
Beispiel #2
0
        public async Task <IActionResult> FetchRepos()
        {
            ObjectId currentUser = ObjectId.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
            var      client      = _githubClientService.GetGitHubClient(currentUser);

            // Get last fetched time:
            var mongoDb        = _mongoService.GetDb;
            var mongoSettings  = _mongoService.GetDBSettings;
            var userCollection = mongoDb.GetCollection <Models.User>(mongoSettings.UserCollectionName);
            var filterUser     = Builders <Models.User> .Filter.Eq(u => u.Id, currentUser);

            var user = (await userCollection.FindAsync <Models.User>(filterUser)).FirstOrDefault();
            //Fetch:
            List <Repository> resultList = new List <Repository>();

            if (user.LastFetchedRepo != null)
            {
                SearchRepositoriesRequest request;
                SearchRepositoryResult    result;
                DateTime date = user.LastFetchedRepo ?? DateTime.UtcNow;
                request = new SearchRepositoriesRequest()
                {
                    Created = DateRange.GreaterThan(date)
                };
                do
                {
                    result = await client.Search.SearchRepo(request);

                    resultList = result.Items.ToList();
                } while (result.TotalCount > resultList.Count);
            }
            else
            {
                resultList = (await client.Repository.GetAllForCurrent()).ToList();
            }

            DateTime utcNow = DateTime.UtcNow;

            if (resultList.Count > 0)
            {
                // store in Mongo
                var reposCollection = mongoDb.GetCollection <Repository>(mongoSettings.ReposCollectionName);
                var updates         = new List <WriteModel <Repository> >();
                foreach (var r in resultList)
                {
                    var filterRepo = Builders <Repository> .Filter.Eq(u => u.Id, r.Id);

                    updates.Add(new ReplaceOneModel <Repository>(filterRepo, r)
                    {
                        IsUpsert = true
                    });
                }
                await reposCollection.BulkWriteAsync(updates, new BulkWriteOptions { IsOrdered = false });

                //await reposCollection.UpdateManyAsync(resultList, ).InsertManyAsync(resultList);

                var updateUser = Builders <Models.User> .Update.Set(u => u.LastFetchedRepo, utcNow);

                await userCollection.UpdateOneAsync(filterUser, updateUser); // update date

                var updateUserRepositories = Builders <Models.User> .Update.PushEach <Repository>(u => u.Repositories, resultList);

                await userCollection.UpdateManyAsync(filterUser, updateUserRepositories); // update Repository list of user

                // store in Neo4J
                var query = _neoContext.Cypher
                            .Unwind(resultList, "repo")
                            .Merge("(l:Language {Name: coalesce(repo.Language, 'N/A')})")
                            .OnCreate().Set("l.Name = coalesce(repo.Language, 'N/A')")
                            .Merge("(r:Repo { Id: repo.Id, Name: repo.Name })-[w:WRITTEN_IN]->(l)")
                            .With("(r)")
                            .Match("(u:User {Id:'" + currentUser.ToString() + "'})")
                            .Merge("(u)-[rel:OWNS]->(r)");
                //var queryText = query.Query.DebugQueryText;
                await query.ExecuteWithoutResultsAsync();


                return(Ok(resultList.Select(x => new RepoDTO
                {
                    Id = x.Id,
                    OpenIssues = x.OpenIssuesCount,
                    IsPublic = !x.Private,
                    Name = x.Name,
                    Owner = x.Owner.Name,
                    OwnerId = currentUser.ToString(),
                    Language = x.Language
                })));
            }

            return(Ok(resultList));
        }