Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
markbates committed Oct 14, 2014
0 parents commit 5709a55
Show file tree
Hide file tree
Showing 23 changed files with 1,144 additions and 0 deletions.
26 changes: 26 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
*.log
.DS_Store
doc
tmp
pkg
*.gem
*.pid
coverage
coverage.data
build/*
*.pbxuser
*.mode1v3
.svn
profile
.console_history
.sass-cache/*
.rake_tasks~
*.log.lck
solr/
.jhw-cache/
jhw.*
*.sublime*
node_modules/
dist/
generated/
.vendor/
7 changes: 7 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
language: go

go:
- 1.1
- 1.2
- 1.3
- tip
22 changes: 22 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
Copyright (c) 2014 Mark Bates

MIT License

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Goth

Package goth provides a simple, clean, and idiomatic way to write authentication
packages for Go web applications.

Unlike other similar packages, Goth, let's you write OAuth, OAuth2, or any other
protocol providers, as long as they implement the `Provider` and `Session` interfaces.

This package was inspired by [https://github.com/intridea/omniauth](https://github.com/intridea/omniauth).

## Installation

```text
$ go get github.com/markbates/goth
```

## Examples

See the [examples](examples) folder for a working application that let's users authenticate
through Twitter or Facebook.

## Issues

Issues always stand a significantly better chance of getting fixed if the are accompanied by a
pull request.

## Contributing

Would I love to see more providers? Certainly! Would you love to contribute one? Hopefully, yes!

1. Fork it
2. Create your feature branch (git checkout -b my-new-feature)
3. Write Tests!
4. Commit your changes (git commit -am 'Add some feature')
5. Push to the branch (git push origin my-new-feature)
6. Create new Pull Request
10 changes: 10 additions & 0 deletions doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
Package goth provides a simple, clean, and idiomatic way to write authentication
packages for Go web applications.
This package was inspired by https://github.com/intridea/omniauth.
See the examples folder for a working application that let's users authenticate
through Twitter or Facebook.
*/
package goth
56 changes: 56 additions & 0 deletions examples/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package main

import (
"fmt"
"html/template"
"net/http"
"os"

"github.com/gorilla/context"
"github.com/gorilla/pat"
"github.com/markbates/goth"
"github.com/markbates/goth/gothic"
"github.com/markbates/goth/providers/facebook"
"github.com/markbates/goth/providers/twitter"
)

func main() {
goth.UseProviders(
twitter.New(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),
facebook.New(os.Getenv("FACEBOOK_KEY"), os.Getenv("FACEBOOK_SECRET"), "http://localhost:3000/auth/facebook/callback"),
)

p := pat.New()
p.Get("/auth/{provider}/callback", func(res http.ResponseWriter, req *http.Request) {
user, err := gothic.CompleteUserAuth(res, req)
if err != nil {
fmt.Fprintln(res, err)
return
}
t, _ := template.New("foo").Parse(userTemplate)
t.Execute(res, user)
})

p.Get("/auth/{provider}", gothic.BeginAuthHandler)
p.Get("/", func(res http.ResponseWriter, req *http.Request) {
t, _ := template.New("foo").Parse(indexTemplate)
t.Execute(res, nil)
})
http.ListenAndServe(":3000", context.ClearHandler(p))
}

var indexTemplate = `
<p><a href="/auth/twitter">Log in with Twitter</a></p>
<p><a href="/auth/facebook">Log in with Facebook</a></p>
`

var userTemplate = `
<p>Name: {{.Name}}</p>
<p>Email: {{.Email}}</p>
<p>NickName: {{.NickName}}</p>
<p>Location: {{.Location}}</p>
<p>AvatarURL: {{.AvatarURL}} <img src="{{.AvatarURL}}"></p>
<p>Description: {{.Description}}</p>
<p>UserID: {{.UserID}}</p>
<p>AccessToken: {{.AccessToken}}</p>
`
149 changes: 149 additions & 0 deletions gothic/gothic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/*
Package gothic wraps common behaviour when using Goth. This makes it quick, and easy, to get up
and running with Goth. Of course, if you want complete control over how things flow, in regards
to the authentication process, feel free and use Goth directly.
See https://github.com/markbates/goth/examples/main.go to see this in action.
*/
package gothic

import (
"errors"
"fmt"
"net/http"

"github.com/gorilla/context"
"github.com/gorilla/sessions"
"github.com/markbates/goth"
)

// SessionName is the key used to access the session store.
const SessionName = "_gothic_session"

// AppKey should be replaced by applications using gothic.
var AppKey = "XDZZYmriq8pJ5k8OKqdDuUFym2e7Im5O1MzdyapfotOnrqQ7ZEdTN9AA7K6aPieC"

// Store can/should be set by applications using gothic. The default is a cookie store.
var Store sessions.Store

func init() {
if Store == nil {
Store = sessions.NewCookieStore([]byte(AppKey))
}
}

/*
BeginAuthHandler is a convienence handler for starting the authentication process.
It expects to be able to get the name of the provider from the query parameters
as either "provider" or ":provider".
BeginAuthHandler will redirect the user to the appropriate authentication end-point
for the requested provider.
See https://github.com/markbates/goth/examples/main.go to see this in action.
*/
func BeginAuthHandler(res http.ResponseWriter, req *http.Request) {
url, err := GetAuthURL(res, req)
if err != nil {
res.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(res, err)
return
}

http.Redirect(res, req, url, http.StatusTemporaryRedirect)
}

/*
GetAuthURL starts the authentication process with the requested provided.
It will return a URL that should be used to send users to.
It expects to be able to get the name of the provider from the query parameters
as either "provider" or ":provider".
I would recommend using the BeginAuthHandler instead of doing all of these steps
yourself, but that's entirely up to you.
*/
func GetAuthURL(res http.ResponseWriter, req *http.Request) (string, error) {
defer context.Clear(req)

providerName, err := getProviderName(req)
if err != nil {
return "", err
}

provider, err := goth.GetProvider(providerName)
if err != nil {
return "", err
}
sess, err := provider.BeginAuth()
if err != nil {
return "", err
}

url, err := sess.GetAuthURL()
if err != nil {
return "", err
}

session, _ := Store.Get(req, SessionName)
session.Values[SessionName] = sess.Marshal()
err = session.Save(req, res)
if err != nil {
return "", err
}

return url, err
}

/*
CompleteUserAuth does what it says on the tin. It completes the authentication
process and fetches all of the basic information about the user from the provider.
It expects to be able to get the name of the provider from the query parameters
as either "provider" or ":provider".
See https://github.com/markbates/goth/examples/main.go to see this in action.
*/
func CompleteUserAuth(res http.ResponseWriter, req *http.Request) (goth.User, error) {
defer context.Clear(req)

providerName, err := getProviderName(req)
if err != nil {
return goth.User{}, err
}

provider, err := goth.GetProvider(providerName)
if err != nil {
return goth.User{}, err
}

session, _ := Store.Get(req, SessionName)

if session.Values[SessionName] == nil {
return goth.User{}, errors.New("could not find a matching session for this request")
}

sess, err := provider.UnmarshalSession(session.Values[SessionName].(string))
if err != nil {
return goth.User{}, err
}

_, err = sess.Authorize(provider, req.URL.Query())

if err != nil {
return goth.User{}, err
}

return provider.FetchUser(sess)
}

func getProviderName(req *http.Request) (string, error) {
provider := req.URL.Query().Get("provider")
if provider == "" {
provider = req.URL.Query().Get(":provider")
}
if provider == "" {
return provider, errors.New("you must select a provider")
}
return provider, nil
}
Loading

0 comments on commit 5709a55

Please sign in to comment.