Exemplo n.º 1
0
 private GitHubService(GitHubOAuthClient client)
 {
     Client        = client;
     Organizations = new GitHubOrganizationsEndpoint(this);
     Repositories  = new GitHubRepositoriesEndpoint(this);
     User          = new GitHubUserEndpoint(this);
     Users         = new GitHubUsersEndpoint(this);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Initialize a new service instance from the specified OAuth client.
        /// </summary>
        /// <param name="client">The OAuth client.</param>
        public static GitHubService CreateFromOAuthClient(GitHubOAuthClient client)
        {
            // This should never be null
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            // Initialize the service
            return(new GitHubService());
        }
Exemplo n.º 3
0
        public ActionResult LinkGitHub()
        {
            string rootUrl = Request.Url.GetLeftPart(UriPartial.Authority);

            GitHubOAuthClient client = new GitHubOAuthClient();

            client.ClientId     = WebConfigurationManager.AppSettings["GitHubClientId"];
            client.ClientSecret = WebConfigurationManager.AppSettings["GitHubClientSecret"];
            client.RedirectUri  = rootUrl + "/umbraco/surface/Profile/LinkGitHub";

            // Set the state (a unique/random value)
            string state = Guid.NewGuid().ToString();

            Session["GitHub_" + state] = "Unicorn rainbows";

            // Construct the authorization URL
            string authorizatioUrl = client.GetAuthorizationUrl(state);

            // Redirect the user to the OAuth dialog
            return(Redirect(authorizatioUrl));
        }
 internal GitHubOrganizationsRawEndpoint(GitHubOAuthClient client)
 {
     Client = client;
 }
Exemplo n.º 5
0
        public ActionResult LinkGitHub(string state, string code = null)
        {
            // Get the member of the current ID
            int memberId = Members.GetCurrentMemberId();

            if (memberId <= 0)
            {
                return(GetErrorResult("Oh noes! An error happened."));
            }

            try
            {
                IPublishedContent profilePage = Umbraco.TypedContent(1057);
                if (profilePage == null)
                {
                    return(GetErrorResult("Oh noes! This really shouldn't happen."));
                }

                // Initialize the OAuth client
                GitHubOAuthClient client = new GitHubOAuthClient
                {
                    ClientId     = WebConfigurationManager.AppSettings["GitHubClientId"],
                    ClientSecret = WebConfigurationManager.AppSettings["GitHubClientSecret"]
                };

                // Validate state - Step 1
                if (String.IsNullOrWhiteSpace(state))
                {
                    LogHelper.Info <ProfileController>("No OAuth state specified in the query string.");
                    return(GetErrorResult("No state specified in the query string."));
                }

                // Validate state - Step 2
                string session = Session["GitHub_" + state] as string;
                if (String.IsNullOrWhiteSpace(session))
                {
                    LogHelper.Info <ProfileController>("Failed finding OAuth session item. Most likely the session expired.");
                    return(GetErrorResult("Session expired? Please click the link below and try to link with your GitHub account again ;)"));
                }

                // Remove the state from the session
                Session.Remove("GitHub_" + state);

                // Exchange the auth code for an access token
                GitHubTokenResponse accessTokenResponse;
                try
                {
                    accessTokenResponse = client.GetAccessTokenFromAuthorizationCode(code);
                }
                catch (Exception ex)
                {
                    LogHelper.Error <ProfileController>("Unable to retrieve access token from GitHub API", ex);
                    return(GetErrorResult("Oh noes! An error happened."));
                }

                // Initialize a new service instance from the retrieved access token
                var service = Skybrud.Social.GitHub.GitHubService.CreateFromAccessToken(accessTokenResponse.Body.AccessToken);

                // Get some information about the authenticated GitHub user
                GitHubGetUserResponse userResponse;
                try
                {
                    userResponse = service.User.GetUser();
                }
                catch (Exception ex)
                {
                    LogHelper.Error <ProfileController>("Unable to get user information from the GitHub API", ex);
                    return(GetErrorResult("Oh noes! An error happened."));
                }

                // Get the GitHub username from the API response
                string githubUsername = userResponse.Body.Login;

                // Get a reference to the member searcher
                BaseSearchProvider searcher = ExamineManager.Instance.SearchProviderCollection["InternalMemberSearcher"];

                // Initialize new search criteria for the GitHub username
                ISearchCriteria criteria = searcher.CreateSearchCriteria();
                criteria = criteria.RawQuery($"github:{githubUsername}");

                // Check if there are other members with the same GitHub username
                foreach (var result in searcher.Search(criteria))
                {
                    if (result.Id != memberId)
                    {
                        LogHelper.Info <ProfileController>("Failed setting GitHub username for user with ID " + memberId + ". Username is already used by member with ID " + result.Id + ".");
                        return(GetErrorResult("Another member already exists with the same GitHub username."));
                    }
                }

                // Get the member from the member service
                var ms  = ApplicationContext.Services.MemberService;
                var mem = ms.GetById(memberId);

                // Update the "github" property and save the value
                mem.SetValue("github", githubUsername);
                mem.SetValue("githubId", userResponse.Body.Id);
                mem.SetValue("githubData", userResponse.Body.JObject.ToString());
                ms.Save(mem);

                // Clear the runtime cache for the member
                ApplicationContext.ApplicationCache.RuntimeCache.ClearCacheItem("MemberData" + mem.Username);

                // Redirect the member back to the profile page
                return(RedirectToUmbracoPage(1057));
            }
            catch (Exception ex)
            {
                LogHelper.Error <ProfileController>("Unable to link with GitHub user for member with ID " + memberId, ex);
                return(GetErrorResult("Oh noes! An error happened."));
            }
        }
 internal GitHubRepositoriesRawEndpoint(GitHubOAuthClient client)
 {
     Client = client;
 }
Exemplo n.º 7
0
        public ActionResult GitHub(string state, string code)
        {
            // Get the member of the current ID
            int memberId = Members.GetCurrentMemberId();

            if (memberId > 0)
            {
                return(GetErrorResult("It seems that you're already logged into Our Umbraco. Log out out if you wish to log in with another account."));
            }

            GitHubService github = new GitHubService();

            try
            {
                IPublishedContent profilePage = Umbraco.TypedContent(1057);
                if (profilePage == null)
                {
                    LogHelper.Info <LoginController>("Profile page not found. Has this been unpublished in Umbraco?");
                    return(GetErrorResult("Oh noes! This really shouldn't happen. This is us, not you."));
                }

                // Initialize the OAuth client
                GitHubOAuthClient client = new GitHubOAuthClient
                {
                    ClientId     = WebConfigurationManager.AppSettings["GitHubClientId"],
                    ClientSecret = WebConfigurationManager.AppSettings["GitHubClientSecret"]
                };

                // Validate state - Step 1
                if (string.IsNullOrWhiteSpace(state))
                {
                    LogHelper.Info <LoginController>("No OAuth state specified in the query string.");
                    return(GetErrorResult("No state specified in the query string. Please go back to the login page and click the \"Login with GitHub\" to try again ;)"));
                }

                // Validate state - Step 2
                string session = Session["GitHub_" + state] as string;
                if (string.IsNullOrWhiteSpace(session))
                {
                    LogHelper.Info <LoginController>("Failed finding OAuth session item. Most likely the session expired.");
                    return(GetErrorResult("Session expired? Please go back to the login page and click the \"Login with GitHub\" to try again ;)"));
                }

                // Remove the state from the session
                Session.Remove("GitHub_" + state);

                // Exchange the auth code for an access token
                GitHubTokenResponse accessTokenResponse;
                try
                {
                    accessTokenResponse = client.GetAccessTokenFromAuthorizationCode(code);
                }
                catch (Exception ex)
                {
                    LogHelper.Error <LoginController>("Unable to retrieve access token from GitHub API", ex);
                    return(GetErrorResult("Oh noes! An error happened in the communication with the GitHub API. It may help going back to the login page and click the \"Login with GitHub\" to try again ;)"));
                }

                // Initialize a new service instance from the retrieved access token
                var service = Skybrud.Social.GitHub.GitHubService.CreateFromAccessToken(accessTokenResponse.Body.AccessToken);

                // Get some information about the authenticated GitHub user
                GitHubUser user;
                try
                {
                    user = service.User.GetUser().Body;
                }
                catch (Exception ex)
                {
                    LogHelper.Error <LoginController>("Unable to get user information from the GitHub API", ex);
                    return(GetErrorResult("Oh noes! An error happened in the communication with the GitHub API. It may help going back to the login page and click the \"Login with GitHub\" to try again ;)"));
                }

                // Get the total amount of members with the GitHub user ID
                var memberIds = github.GetMemberIdsFromGitHubUserId(user.Id);

                // No matching members means that the GitHub user has not yet been linked with any Our members, so we
                // create a new Our member instead
                if (memberIds.Length == 0)
                {
                    return(RegisterFromGitHub(service, user));
                }

                // More than one matching member indicates an error as there should not be more than one Our member
                // linked with the same GitHub user
                if (memberIds.Length > 1)
                {
                    LogHelper.Info <LoginController>("Multiple Our members are linked with the same GitHub account: " + user.Login + " (ID: " + user.Id + "). Matching member IDs are: " + string.Join(", ", memberIds));
                    return(GetErrorResult("Oh noes! This really shouldn't happen. This is us, not you."));
                }

                // Get a reference to the member
                var member = Services.MemberService.GetById(memberIds[0]);

                // Check whether the member was found
                if (member == null)
                {
                    LogHelper.Info <LoginController>("No Our member found with the ID " + memberIds[0]);
                    return(GetErrorResult("Oh noes! This really shouldn't happen. This is us, not you."));
                }

                FormsAuthentication.SetAuthCookie(member.Username, false);
                return(Redirect("/"));
            }
            catch (Exception ex)
            {
                LogHelper.Error <LoginController>("Failed logging in member from GitHub", ex);
                return(GetErrorResult("Oh noes! This really shouldn't happen. This is us, not you." + ex));
            }
        }
Exemplo n.º 8
0
 internal GitHubUsersRawEndpoint(GitHubOAuthClient client)
 {
     Client = client;
 }