Created
January 3, 2015 21:18
-
-
Save husio/388671ce576b3eb29f48 to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"html/template" | |
"log" | |
"net/http" | |
"github.com/stretchr/gomniauth" | |
"github.com/stretchr/gomniauth/common" | |
"github.com/stretchr/gomniauth/providers/google" | |
"github.com/stretchr/objx" | |
) | |
var tmpl = template.Must(template.New("").Parse(` | |
{{define "header"}} | |
<!doctype html> | |
<html> | |
<body> | |
{{end}} | |
{{define "footer"}} | |
</body> | |
</html> | |
{{end}} | |
{{define "index"}} | |
{{template "header" .}} | |
{{if .User}} | |
Logged as {{.User.Email}}. <a href="/logout">Logout</a>. | |
{{else}} | |
Login with <a href="/login">google account</a>. | |
{{end}} | |
{{template "footer" .}} | |
{{end}} | |
`)) | |
var CurrentUser *common.User | |
func main() { | |
gomniauth.SetSecurityKey("asjacjhf09hq0fhaoHAOSDHAsdasdsa") | |
googleProvider := google.New("id", "secret", "callbackurl") | |
gomniauth.WithProviders(googleProvider) | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
ctx := map[string]interface{}{ | |
"User": CurrentUser, | |
} | |
if err := tmpl.ExecuteTemplate(w, "index", ctx); err != nil { | |
log.Printf("cannot render index template: %s", err) | |
http.Error(w, err.Error(), 500) | |
} | |
}) | |
http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) { | |
state := gomniauth.NewState("after", "success") | |
authUrl, err := googleProvider.GetBeginAuthURL(state, nil) | |
if err != nil { | |
log.Printf("cannot generate login url: %s", err) | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
http.Redirect(w, r, authUrl, http.StatusFound) | |
}) | |
http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) { | |
CurrentUser = nil | |
http.Redirect(w, r, "/", http.StatusFound) | |
}) | |
http.HandleFunc("/login/google", func(w http.ResponseWriter, r *http.Request) { | |
omap, err := objx.FromURLQuery(r.URL.RawQuery) | |
if err != nil { | |
log.Printf("cannot parse login callback query: %s", err) | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
cred, err := googleProvider.CompleteAuth(omap) | |
if err != nil { | |
log.Printf("cannot complete authentication: %s", err) | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
user, err := googleProvider.GetUser(cred) | |
if err != nil { | |
log.Printf("cannot get authenticated user: %s", err) | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
CurrentUser = &user | |
http.Redirect(w, r, "/", http.StatusFound) | |
}) | |
log.Fatal(http.ListenAndServe(":5000", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment