Add basic GitHub OAuth flow.

This commit is contained in:
Mihai Parparita 2014-07-05 22:53:34 -07:00
parent b1d334f8e9
commit 9097e1508b
5 changed files with 53 additions and 12 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
app/config/*oauth*.json

1
TODO Normal file
View file

@ -0,0 +1 @@
- Option to only do this for public repos (repo vs. public_repo scopes)

View file

@ -0,0 +1,5 @@
{
"ClientId": "REPLACE_ME",
"ClientSecret": "REPLACE_ME",
"RedirectURL": "https://REPLACE_ME/github/callback"
}

View file

@ -1,12 +1,16 @@
package githop
import (
"github.com/google/go-github/github"
"encoding/json"
"html/template"
"io/ioutil"
"net/http"
"appengine"
"appengine/urlfetch"
"appengine/urlfetch"
"code.google.com/p/goauth2/oauth"
"github.com/google/go-github/github"
)
func init() {
@ -16,16 +20,47 @@ func init() {
var indexTemplate = template.Must(template.ParseFiles("templates/index.html"))
func index(w http.ResponseWriter, r *http.Request) {
appengine_context := appengine.NewContext(r)
http_client := urlfetch.Client(appengine_context)
gitub_client := github.NewClient(http_client)
orgs, _, err := gitub_client.Organizations.List("mihaip", nil)
// TODO: Don't do this every request
github_oauth_config_path := "config/github-oauth"
if appengine.IsDevAppServer() {
github_oauth_config_path += "-dev"
}
github_oauth_config_path += ".json"
github_oauth_config_bytes, err := ioutil.ReadFile(github_oauth_config_path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := indexTemplate.Execute(w, orgs); err != nil {
var github_oauth_config oauth.Config
err = json.Unmarshal(github_oauth_config_bytes, &github_oauth_config)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
github_oauth_config.Scope = "repo"
github_oauth_config.AuthURL = "https://github.com/login/oauth/authorize"
github_oauth_config.TokenURL = "https://github.com/login/oauth/access_token"
code := r.FormValue("code")
if code == "" {
http.Redirect(w, r, github_oauth_config.AuthCodeURL(""), http.StatusFound)
return
}
appengine_context := appengine.NewContext(r)
oauth_transport := &oauth.Transport{
Config: &github_oauth_config,
Transport: &urlfetch.Transport{Context: appengine_context},
}
token, _ := oauth_transport.Exchange(code)
oauth_transport.Token = token
gitub_client := github.NewClient(oauth_transport.Client())
repos, _, err := gitub_client.Repositories.List("", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := indexTemplate.Execute(w, repos); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

View file

@ -8,13 +8,12 @@
<body>
<h1>GitHop!</h1>
<code>mihaip</code> is in the following organizations:
Your repositories:
<ul>
{{range .}}
<li>
<a href="https://github.com/{{.Login}}">
<img src="{{.AvatarURL}}" width="32" height="32">
{{.Login}}
<a href="https://github.com/{{.FullName}}">
{{.FullName}}
</a>
</li>
{{end}}