Last active
November 28, 2018 07:52
-
-
Save bonfy/bf8592b131b0671998e92963d0758072 to your computer and use it in GitHub Desktop.
Go oauth github
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"os" | |
"time" | |
"github.com/dchest/uniuri" | |
"github.com/gorilla/mux" | |
"golang.org/x/oauth2" | |
"golang.org/x/oauth2/github" | |
) | |
const UserInfoURL = "https://api.github.com/user?access_token=" | |
var githubOauthConfig = &oauth2.Config{ | |
RedirectURL: "http://localhost:3000/callback", | |
ClientID: os.Getenv("GITHUB_OAUTH_CLIENT_ID"), | |
ClientSecret: os.Getenv("GITHUB_OAUTH_CLIENT_SECRET"), | |
Scopes: []string{"repo", "user"}, | |
Endpoint: github.Endpoint, | |
} | |
type GithubUser struct { | |
Login string `json:"login"` | |
ID int `json:"id"` | |
NodeID string `json:"node_id"` | |
AvatarURL string `json:"avatar_url"` | |
GravatarID string `json:"gravatar_id"` | |
URL string `json:"url"` | |
HTMLURL string `json:"html_url"` | |
FollowersURL string `json:"followers_url"` | |
FollowingURL string `json:"following_url"` | |
GistsURL string `json:"gists_url"` | |
StarredURL string `json:"starred_url"` | |
SubscriptionsURL string `json:"subscriptions_url"` | |
OrganizationsURL string `json:"organizations_url"` | |
ReposURL string `json:"repos_url"` | |
EventsURL string `json:"events_url"` | |
ReceivedEventsURL string `json:"received_events_url"` | |
Type string `json:"type"` | |
SiteAdmin bool `json:"site_admin"` | |
Name string `json:"name"` | |
Company interface{} `json:"company"` | |
Blog string `json:"blog"` | |
Location string `json:"location"` | |
Email string `json:"email"` | |
Hireable bool `json:"hireable"` | |
Bio string `json:"bio"` | |
PublicRepos int `json:"public_repos"` | |
PublicGists int `json:"public_gists"` | |
Followers int `json:"followers"` | |
Following int `json:"following"` | |
CreatedAt time.Time `json:"created_at"` | |
UpdatedAt time.Time `json:"updated_at"` | |
PrivateGists int `json:"private_gists"` | |
TotalPrivateRepos int `json:"total_private_repos"` | |
OwnedPrivateRepos int `json:"owned_private_repos"` | |
DiskUsage int `json:"disk_usage"` | |
Collaborators int `json:"collaborators"` | |
TwoFactorAuthentication bool `json:"two_factor_authentication"` | |
Plan struct { | |
Name string `json:"name"` | |
Space int `json:"space"` | |
Collaborators int `json:"collaborators"` | |
PrivateRepos int `json:"private_repos"` | |
} `json:"plan"` | |
} | |
func main() { | |
router := mux.NewRouter().StrictSlash(true) | |
router.HandleFunc("/", indexHandler) | |
router.HandleFunc("/login", loginHandler) | |
router.HandleFunc("/callback", callbackHandler) | |
http.ListenAndServe(":3000", router) | |
} | |
func indexHandler(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintln(w, "<a href='/login'>Log in with Github</a>") | |
} | |
func loginHandler(w http.ResponseWriter, r *http.Request) { | |
oauthStateString := uniuri.New() | |
url := githubOauthConfig.AuthCodeURL(oauthStateString) | |
http.Redirect(w, r, url, http.StatusTemporaryRedirect) | |
} | |
func callbackHandler(w http.ResponseWriter, r *http.Request) { | |
code := r.FormValue("code") | |
token, err := githubOauthConfig.Exchange(oauth2.NoContext, code) | |
if err != nil { | |
fmt.Fprintf(w, "Code exchange failed with error %s\n", err.Error()) | |
return | |
} | |
if !token.Valid() { | |
fmt.Fprintln(w, "Retreived invalid token") | |
return | |
} | |
fmt.Fprintln(w, token.AccessToken) | |
response, err := http.Get(UserInfoURL + token.AccessToken) | |
if err != nil { | |
log.Printf("Error getting user from token %s\n", err.Error()) | |
} | |
defer response.Body.Close() | |
fmt.Println(response.Body) | |
contents, err := ioutil.ReadAll(response.Body) | |
var user *GithubUser | |
err = json.Unmarshal(contents, &user) | |
if err != nil { | |
log.Printf("Error unmarshaling Google user %s\n", err.Error()) | |
return | |
} | |
fmt.Fprintf(w, "Email: %s\nName: %s\nImage link: %s\n", user.Email, user.Name, user.Login) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment