public async Task <UserView> OauthFromGit(GitSignInPara data) { Dictionary <string, string> postData = new Dictionary <string, string>(); postData.Add("code", data.Code); postData.Add("client_secret", data.Client_secret); postData.Add("client_id", data.Client_id); string token = await HttpUtil.HttpPostAsync("https://github.com/login/oauth/access_token", postData, Encoding.UTF8); string pattern = @"(?<=access_token=)\w*"; token = Regex.Match(token, pattern).Value; string userStr = await HttpUtil.HttpGetAsync("https://api.github.com/user?access_token=" + token, Encoding.UTF8); GitUser gitUser = JsonConvert.DeserializeObject <GitUser>(userStr); if (gitUser.Login == null) { return new UserView { NickName = "Token过期" } } ; int userId = CreateUser(gitUser); //插入Cookie await InserCookie(gitUser, userId); UserView userView = _mapper.Map <UserView>(gitUser); return(userView); }
private static void PrintUser(GitUser u, int offset) { var tab = new string(' ', offset *2); Console.WriteLine($"{tab}{u.Login} ({u.Name}) {u.Location}"); u.Followers.ForEach(f => PrintUser(f, offset + 1)); }
public void TestMethod2(string name) { // List <GitUserRepoList> repoList = null; GitUser user = null; Mock <IGitHubUserRepo> _mockGitUserRepo = new Mock <IGitHubUserRepo>(); _mockGitUserRepo .Setup(x => x.GetGitUserAsync(It.IsAny <string>())) .Returns(user); _mockGitUserRepo .Setup(x => x.GetUserRepoListAsync(It.IsAny <string>())) .Returns(repoList); Mock <ILog> _mocklog = new Mock <ILog>(); var controller = new BGLGITApi.BglGitUserController(_mockGitUserRepo.Object, _mocklog.Object); // var badresult = controller.GetUserByName(name); var type = badresult.GetType(); Assert.IsInstanceOfType(badresult, typeof(NotFoundResult)); }
private async Task GetUserAsync(string text, Node from, CancellationToken cancellationToken) { GitUser user = await _gitService.GetUser(text); if (user != null) { var contact = await _contactService.GetContactAsync(from, cancellationToken); contact.Name = user.Name; contact.PhotoUri = new Uri(user.AvatarUrl); var navParams = new Dictionary <string, string>() { { "varName", "content" } }; await _contactService.SetContactAsync(contact, from, cancellationToken); var d = new MediaLink() { Title = user.Name, Text = "Olha aqui seu avatar kaka fei pa carai", Type = MediaType.Parse("image/jpeg"), AspectRatio = "1:1", Uri = contact.PhotoUri }; await _sender.SendMessageAsync(d, from, cancellationToken); await _mpaService.SendToMPAAsync(user.Name, from, cancellationToken, navParams); } else { await _sender.SendMessageAsync("Não tem ninguém com esse usuário no git.", from, cancellationToken); } }
public void MarkUserActive_WithUnknownUser_DoesNothing() { classUnderTest.AddUser(testUser); var unkownUser = new GitUser("Some User", "*****@*****.**", "path-to-key"); classUnderTest.MakeUserActive(unkownUser, isPairOrMob: false); Assert.That(classUnderTest.ActiveUsers.Count, Is.EqualTo(0)); }
/// <summary> /// cookie只存git 的id以及该用户来源 /// </summary> /// <param name="user"></param> /// <returns></returns> private async Task InserCookie(GitUser user, int userId) { var identity = new ClaimsIdentity("Forms"); identity.AddClaim(new Claim(ClaimTypes.Sid, user.Id.ToString())); identity.AddClaim(new Claim("Id", userId.ToString())); identity.AddClaim(new Claim(ClaimTypes.Name, user.Name ?? "")); identity.AddClaim(new Claim(AccountSource.LoginSource, AccountSource.Git)); var principal = new ClaimsPrincipal(identity); await _context.HttpContext.SignInAsync("login", principal, new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.MaxValue });// }
public GitHubUserViewModel ToGitHubUserViewModel(GitUser gitUser, IEnumerable <GitRepository> gitRepository) { var gitHubUserViewModel = new GitHubUserViewModel { UserName = gitUser.login, AvatarUrl = gitUser.avatar_url, Location = gitUser.location, RepositoryList = gitRepository.Select(i => GetGitHubRepositoryViewModel(i)) }; return(gitHubUserViewModel); }
public override IEnumerable <IRow> Extract(IUnstructuredReader input, IUpdatableRow output) { string line = string.Empty; foreach (Stream current in input.Split(_rowDelim)) { using (StreamReader streamReader = new StreamReader(current, _encoding)) { line = streamReader.ReadToEnd().Trim(); if (!string.IsNullOrEmpty(line)) { GitUser user = JsonConvert.DeserializeObject <GitUser>(line); output.Set("avatarUrl", user.AvatarUrl); output.Set("bio", user.Bio); output.Set("blog", user.Blog); output.Set("collaborators", user.Collaborators); output.Set("company", user.Company); output.Set("createdAt", user.CreatedAt.UtcDateTime); output.Set("updatedAt", user.UpdatedAt.UtcDateTime); output.Set("diskUsage", user.DiskUsage); output.Set("followers", user.Followers); output.Set("following", user.Following); output.Set("hireable", user.Hireable); output.Set("htmlUrl", user.HtmlUrl); output.Set("totalPrivateRepos", user.TotalPrivateRepos); output.Set("id", user.Id); output.Set("location", user.Location); output.Set("login", user.Login); output.Set("name", user.Name); output.Set("ownedPrivateRepos", user.OwnedPrivateRepos); output.Set("plan_collaborators", user.Plan == null?(long?)null:user.Plan.Collaborators); output.Set("plan_name", user.Plan == null ? null : user.Plan.Name); output.Set("plan_privateRepos", user.Plan == null ? (long?)null : user.Plan.PrivateRepos); output.Set("plan_space", user.Plan == null ? (long?)null : user.Plan.Space); output.Set("plan_billingEmail", user.Plan == null ? null : user.Plan.BillingEmail); output.Set("privateGists", user.PrivateGists); output.Set("publicGists", user.PublicGists); output.Set("publicRepos", user.PublicRepos); output.Set("url", user.Url); output.Set("permissions_admin", user.Permissions == null?(bool?)null:user.Permissions.Admin); output.Set("permissions_push", user.Permissions == null ? (bool?)null : user.Permissions.Push); output.Set("permissions_pull", user.Permissions == null ? (bool?)null : user.Permissions.Pull); output.Set("siteAdmin", user.SiteAdmin); output.Set("ldapDistinguishedName", user.LdapDistinguishedName); output.Set("suspendedAt", user.SuspendedAt == null?(DateTime?)null:user.SuspendedAt.Value.UtcDateTime); output.Set("Type", user.Type == null?null:user.Type.Value.ToString()); output.Set("Suspended", user.Suspended); } } yield return(output.AsReadOnly()); } }
public void SetUp() { mockOptionsManager = new Mock <IOptionsManager>(); mockFileHandler = new Mock <IFileHandler>(); mockFileHasher = new Mock <IFileHasher>(); mockGitConfigEditor = new Mock <IGitConfigEditor>(); mockSshConfigEditor = new Mock <ISshConfigEditor>(); testUser = new GitUser("Test User", "*****@*****.**", @"c:\fake-key"); mockFileHandler.Setup(mock => mock.DeserializeFromFile <List <GitUser> >(It.IsAny <string>())).Throws(new FileNotFoundException()); classUnderTest = new GitUserManager(mockOptionsManager.Object, mockFileHandler.Object, mockFileHasher.Object, mockGitConfigEditor.Object, mockSshConfigEditor.Object); }
public async Task <GitUser> GetUser(string username) { var client = RestClient.For <IGitApi>("https://api.github.com"); GitUser user = null; try { await client.GetUserAsync(username); } catch (ApiException) { } return(user); }
public void GetUsersFromName_Returns_ResponseObjectIncludingActualUser() { IDownloadService downloadService = new FakeDownloadService(); GitUserFetcher gitUserFetcher = new GitUserFetcher(downloadService); GitUser expectedGitUser = new GitUser(); expectedGitUser.id = 1334; expectedGitUser.login = "******"; var resultUsers = gitUserFetcher.GetUsersFromNameAsync("jesper").Result; var resultUser = resultUsers.Find((GitUser user) => user.login == "jesper"); Assert.AreEqual(0, expectedGitUser.CompareTo(resultUser)); }
static void loadTransaction(string depotName, string streamName, int transactionId, string workingDir, XElement transaction) { // ReSharper disable PossibleNullReferenceException string accurevUser = transaction.Attribute("user").Value; GitUser gitUser = translateUser(accurevUser); if (gitUser == null) { throw new ApplicationException(string.Format("Accurev user {0} not recognised in Git", accurevUser)); } Int64 unixDate = long.Parse(transaction.Attribute("time").Value); // ReSharper restore PossibleNullReferenceException var issueNumNodes = transaction.Descendants("version").Descendants("issueNum"); var issueNums = (issueNumNodes == null || issueNumNodes.Count() == 0 ? string.Empty : issueNumNodes.Select(n => n.Value).Distinct().Aggregate(string.Empty, (seed, num) => seed + ", " + num).Substring(2)); var commentNode = transaction.Descendants("comment").FirstOrDefault(); string comment = (commentNode == null ? string.Empty : commentNode.Value); comment = string.IsNullOrEmpty(comment) ? "[no original comment]" : comment; string[] commentLines = comment.Split(new[] { "\n" }, 2, StringSplitOptions.None); if (commentLines.Length > 1) { comment = commentLines[0] + Environment.NewLine + Environment.NewLine + commentLines[1]; } comment += string.Format("{0}{0}[AccuRev Transaction #{1}]", Environment.NewLine, transactionId); if (!string.IsNullOrEmpty(issueNums)) { comment += string.Format("{0}[Issue #s: {1}]", Environment.NewLine, issueNums); } var commentFile = string.Format(".\\_{0}_Comment.txt", depotName); var commentFilePath = Path.GetFullPath(commentFile); File.WriteAllText(commentFile, comment); execClean(workingDir); if (string.IsNullOrEmpty(streamName)) { execAccuRev(string.Format("pop -R -O -v \"{0}\" -L . -t {1} .", depotName, transactionId), workingDir); } else { execAccuRev(string.Format("pop -R -O -v \"{0}\" -L . -t {1} .", streamName, transactionId), workingDir); } execGitRaw("add --all", workingDir); execGitCommit(string.Format("commit --date={0} --author={1} --file=\"{2}\"", unixDate, gitUser, commentFilePath), workingDir, unixDate.ToString(), gitUser); execGitRaw(string.Format("config accurev2git.lasttran {0}", transactionId), workingDir); }
/// <summary> /// 创建用户 /// </summary> /// <param name="user"></param> /// <returns>user Id</returns> private int CreateUser(GitUser gitUser) { User user = _mapper.Map <User>(gitUser); var existedUser = _db.Users.Where(p => p.Sid == gitUser.Id && p.UserSource == AccountSource.Git).FirstOrDefault(); if (existedUser != null) { return(existedUser.Id); } else { _db.Users.Add(user); _db.SaveChanges(); existedUser = _db.Users.Where(p => p.Sid == gitUser.Id && p.UserSource == AccountSource.Git).FirstOrDefault(); return(existedUser.Id); } }
public void MakeUserActive_IsPairOrMob_AllowsMultipleUsers() { classUnderTest.AddUser(testUser); var otherUser = new GitUser("Some User", "*****@*****.**", "path/to/key"); classUnderTest.AddUser(otherUser); Assert.That(classUnderTest.ActiveUsers, Is.Empty); classUnderTest.MakeUserActive(testUser, isPairOrMob: true); Assert.That(classUnderTest.ActiveUsers.Count, Is.EqualTo(1)); Assert.That(classUnderTest.ActiveUsers.First(), Is.EqualTo(testUser)); classUnderTest.MakeUserActive(otherUser, isPairOrMob: true); Assert.That(classUnderTest.ActiveUsers.Count, Is.EqualTo(2)); Assert.That(classUnderTest.ActiveUsers.Last(), Is.EqualTo(otherUser)); }
/// <summary> /// Contains a BitmapImage for given GitUser. /// </summary> /// <param name="gitUser">GitUser to extract avatar for.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"><paramref name="gitUser" /> is <see langword="null" />.</exception> public BitmapImage ValueFor(GitUser gitUser) { if (gitUser == null) { throw new ArgumentNullException(nameof(gitUser)); } var image = new BitmapImage(); const int bytesToRead = 100; if (string.IsNullOrWhiteSpace(gitUser.Avatar_Url)) { return(image); } var pictureUri = new Uri(gitUser.Avatar_Url, UriKind.Absolute); var request = WebRequest.Create(pictureUri); request.Timeout = -1; var response = request.GetResponse(); var responseStream = response.GetResponseStream(); if (responseStream != null) { var reader = new BinaryReader(responseStream); var memoryStream = new MemoryStream(); var bytebuffer = new byte[bytesToRead]; var bytesRead = reader.Read(bytebuffer, 0, bytesToRead); while (bytesRead > 0) { memoryStream.Write(bytebuffer, 0, bytesRead); bytesRead = reader.Read(bytebuffer, 0, bytesToRead); } image.BeginInit(); memoryStream.Seek(0, SeekOrigin.Begin); image.StreamSource = memoryStream; } image.EndInit(); return(image); }
// An utility method to add new user to dbcontext and database // Only run when a search found a valid user private async Task AddToDB(User user) { try { // Check if newly searched user already exists in the DbContext var gitUser = _context.GitUsers.SingleOrDefault(u => u.Id == user.Id); // Create a new GitUser if not existing in the DbContext if (gitUser == null) { gitUser = new GitUser { Login = user.Login, Id = user.Id, Url = user.Url, Name = user.Name, Location = user.Location, Followers = user.Followers, Company = user.Company, Email = user.Email }; _context.GitUsers.Add(gitUser); } // Create new search item using the searched user UserSearch search = new UserSearch { AccessDate = DateTime.Now, User = gitUser }; _context.UserSearches.Add(search); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException e) { Console.WriteLine(e.Message); throw; } }
static void execGitCommit(string arguments, string workingDir, string commitDate, GitUser gitUser) { var gitPath = ConfigurationManager.AppSettings["GitPath"]; var process = new Process { StartInfo = new ProcessStartInfo(gitPath, arguments) }; if (!string.IsNullOrEmpty(workingDir)) process.StartInfo.WorkingDirectory = workingDir; process.StartInfo.EnvironmentVariables.Add("GIT_COMMITTER_DATE", commitDate); process.StartInfo.EnvironmentVariables.Add("GIT_COMMITTER_NAME", gitUser.Name); process.StartInfo.EnvironmentVariables.Add("GIT_COMMITTER_EMAIL", gitUser.Email); process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; process.Start(); var output = process.StandardOutput.ReadToEnd(); if (process.StandardError.EndOfStream == false) { var errors = process.StandardError.ReadToEnd(); throw new ApplicationException(string.Format("Git has returned an error: {0}", errors)); } }
public void TestMethod1(string name) { // List <GitUserRepoList> repoList = new List <GitUserRepoList>() { new GitUserRepoList { id = "1", name = "repo1", stargazers_count = 20 }, new GitUserRepoList { id = "2", name = "repo2", stargazers_count = 22 }, new GitUserRepoList { id = "3", name = "repo3", stargazers_count = 24 }, new GitUserRepoList { id = "4", name = "repo4", stargazers_count = 26 }, new GitUserRepoList { id = "5", name = "repo5", stargazers_count = 28 }, new GitUserRepoList { id = "6", name = "repo6", stargazers_count = 30 } }; GitUser user = new GitUser { id = "78586", login = "******", location = "Honolulu, HI", avatar_url = "https://avatars0.githubusercontent.com/u/78586?v=4", repos_url = "https://api.github.com/users/robconery/repos", UserRepoList = null }; Mock <IGitHubUserRepo> _mockGitUserRepo = new Mock <IGitHubUserRepo>(); _mockGitUserRepo .Setup(x => x.GetGitUserAsync(It.IsAny <string>())) .Returns(user); _mockGitUserRepo .Setup(x => x.GetUserRepoListAsync(It.IsAny <string>())) .Returns(repoList); Mock <ILog> _mocklog = new Mock <ILog>(); var controller = new BGLGITApi.BglGitUserController(_mockGitUserRepo.Object, _mocklog.Object); // var result = controller.GetUserByName(name); var type = result.GetType(); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, type); }
static void execGitCommit(string arguments, string workingDir, string commitDate, GitUser gitUser) { var gitPath = ConfigurationManager.AppSettings["GitPath"]; var process = new Process { StartInfo = new ProcessStartInfo(gitPath, arguments) }; if (!string.IsNullOrEmpty(workingDir)) { process.StartInfo.WorkingDirectory = workingDir; } process.StartInfo.EnvironmentVariables.Add("GIT_COMMITTER_DATE", commitDate); process.StartInfo.EnvironmentVariables.Add("GIT_COMMITTER_NAME", gitUser.Name); process.StartInfo.EnvironmentVariables.Add("GIT_COMMITTER_EMAIL", gitUser.Email); process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; process.Start(); var output = process.StandardOutput.ReadToEnd(); if (process.StandardError.EndOfStream == false) { var errors = process.StandardError.ReadToEnd(); throw new ApplicationException(string.Format("Git has returned an error: {0}", errors)); } }
public static GitUserDetails GetUserDetails(GitUser user) { if (null == user) throw new ArgumentNullException(); // GET /search/users string url = string.Format("https://{0}/users/{1}", github_root_url, user.login); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); string jsonResponse = null; try { jsonResponse = getResponse(request); } catch (WebException wex) { log.Warn(wex); return null; } catch (Exception ex) { log.Error(ex); return null; } return JsonConvert.DeserializeObject<GitUserDetails>(jsonResponse); }
protected bool Equals(GitUser other) { return(string.Equals(Username, other.Username)); }