2018-03-09 04:39:51 +02:00
|
|
|
// Package oauth2 allows users to be created and authenticated
|
|
|
|
// via oauth2 services like facebook, google etc. Currently
|
|
|
|
// only the web server flow is supported.
|
|
|
|
//
|
|
|
|
// The general flow looks like this:
|
|
|
|
// 1. User goes to Start handler and has his session packed with goodies
|
|
|
|
// then redirects to the OAuth service.
|
2018-09-16 00:39:26 +02:00
|
|
|
// 2. OAuth service returns to OAuthCallback which extracts state and
|
|
|
|
// parameters and generally checks that everything is ok. It uses the
|
|
|
|
// token received to get an access token from the oauth2 library
|
|
|
|
// 3. Calls the OAuth2Provider.FindUserDetails which should return the user's
|
|
|
|
// details in a generic form.
|
|
|
|
// 4. Passes the user details into the OAuth2ServerStorer.NewFromOAuth2 in
|
|
|
|
// order to create a user object we can work with.
|
2018-03-09 04:39:51 +02:00
|
|
|
// 5. Saves the user in the database, logs them in, redirects.
|
|
|
|
//
|
|
|
|
// In order to do this there are a number of parts:
|
2018-09-16 00:39:26 +02:00
|
|
|
// 1. The configuration of a provider
|
|
|
|
// (handled by authboss.Config.Modules.OAuth2Providers).
|
|
|
|
// 2. The flow of redirection of client, parameter passing etc
|
|
|
|
// (handled by this package)
|
|
|
|
// 3. The HTTP call to the service once a token has been retrieved to
|
|
|
|
// get user details (handled by OAuth2Provider.FindUserDetails)
|
|
|
|
// 4. The creation of a user from the user details returned from the
|
|
|
|
// FindUserDetails (authboss.OAuth2ServerStorer)
|
2020-07-03 20:02:23 +02:00
|
|
|
// 5. The special casing of the ServerStorer implementation's Load()
|
|
|
|
// function to deal properly with incoming OAuth2 pids. See
|
|
|
|
// authboss.ParseOAuth2PID as a way to do this.
|
2018-03-09 04:39:51 +02:00
|
|
|
//
|
2018-09-16 00:39:26 +02:00
|
|
|
// Of these parts, the responsibility of the authboss library consumer
|
2020-07-03 20:02:23 +02:00
|
|
|
// is on 1, 3, 4, and 5. Configuration of providers that should be used is
|
|
|
|
// totally up to the consumer. The FindUserDetails function is typically up to
|
|
|
|
// the user, but we have some basic ones included in this package too.
|
2018-09-16 00:39:26 +02:00
|
|
|
// The creation of users from the FindUserDetail's map[string]string return
|
|
|
|
// is handled as part of the implementation of the OAuth2ServerStorer.
|
2015-03-13 04:20:36 +02:00
|
|
|
package oauth2
|
|
|
|
|
|
|
|
import (
|
2018-03-09 04:39:51 +02:00
|
|
|
"context"
|
2015-03-13 04:20:36 +02:00
|
|
|
"crypto/rand"
|
|
|
|
"encoding/base64"
|
2015-03-25 04:39:20 +02:00
|
|
|
"encoding/json"
|
2015-03-13 04:20:36 +02:00
|
|
|
"fmt"
|
2018-07-17 19:10:07 +02:00
|
|
|
"io"
|
2015-03-13 04:20:36 +02:00
|
|
|
"net/http"
|
2015-03-14 01:23:43 +02:00
|
|
|
"net/url"
|
2015-03-13 04:20:36 +02:00
|
|
|
"path"
|
|
|
|
"path/filepath"
|
2018-03-09 04:39:51 +02:00
|
|
|
"sort"
|
2015-03-13 04:20:36 +02:00
|
|
|
"strings"
|
|
|
|
|
2020-07-03 20:24:07 +02:00
|
|
|
"github.com/friendsofgo/errors"
|
2018-03-09 04:39:51 +02:00
|
|
|
"golang.org/x/oauth2"
|
2017-02-22 01:04:30 +02:00
|
|
|
|
2020-07-03 20:24:07 +02:00
|
|
|
"github.com/volatiletech/authboss/v3"
|
2018-03-09 04:39:51 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// FormValue constants
|
|
|
|
const (
|
|
|
|
FormValueOAuth2State = "state"
|
|
|
|
FormValueOAuth2Redir = "redir"
|
2015-03-13 04:20:36 +02:00
|
|
|
)
|
|
|
|
|
2015-03-13 11:15:58 +02:00
|
|
|
var (
|
2017-02-22 01:04:30 +02:00
|
|
|
errOAuthStateValidation = errors.New("could not validate oauth2 state param")
|
2015-03-13 11:15:58 +02:00
|
|
|
)
|
|
|
|
|
2015-03-16 23:42:45 +02:00
|
|
|
// OAuth2 module
|
2015-04-01 00:27:47 +02:00
|
|
|
type OAuth2 struct {
|
|
|
|
*authboss.Authboss
|
|
|
|
}
|
2015-03-13 04:20:36 +02:00
|
|
|
|
|
|
|
func init() {
|
2016-05-09 19:20:10 +02:00
|
|
|
authboss.RegisterModule("oauth2", &OAuth2{})
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
// Init module
|
|
|
|
func (o *OAuth2) Init(ab *authboss.Authboss) error {
|
2015-04-01 00:27:47 +02:00
|
|
|
o.Authboss = ab
|
2015-03-13 04:20:36 +02:00
|
|
|
|
2020-09-18 17:28:09 +02:00
|
|
|
// Do annoying sorting on keys so we can have predictable
|
2018-09-16 00:39:26 +02:00
|
|
|
// route registration (both for consistency inside the router but
|
|
|
|
// also for tests -_-)
|
2018-03-09 04:39:51 +02:00
|
|
|
var keys []string
|
|
|
|
for k := range o.Authboss.Config.Modules.OAuth2Providers {
|
|
|
|
keys = append(keys, k)
|
|
|
|
}
|
|
|
|
sort.Strings(keys)
|
2015-03-13 04:20:36 +02:00
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
for _, provider := range keys {
|
|
|
|
cfg := o.Authboss.Config.Modules.OAuth2Providers[provider]
|
|
|
|
provider = strings.ToLower(provider)
|
2015-03-13 04:20:36 +02:00
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
init := fmt.Sprintf("/oauth2/%s", provider)
|
|
|
|
callback := fmt.Sprintf("/oauth2/callback/%s", provider)
|
2015-03-13 04:20:36 +02:00
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
o.Authboss.Config.Core.Router.Get(init, o.Authboss.Core.ErrorHandler.Wrap(o.Start))
|
|
|
|
o.Authboss.Config.Core.Router.Get(callback, o.Authboss.Core.ErrorHandler.Wrap(o.End))
|
2015-03-14 07:09:01 +02:00
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
if mount := o.Authboss.Config.Paths.Mount; len(mount) > 0 {
|
|
|
|
callback = path.Join(mount, callback)
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
2015-03-13 11:15:58 +02:00
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
cfg.OAuth2Config.RedirectURL = o.Authboss.Config.Paths.RootURL + callback
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
return nil
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
// Start the oauth2 process
|
|
|
|
func (o *OAuth2) Start(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
logger := o.Authboss.RequestLogger(r)
|
2015-03-13 04:20:36 +02:00
|
|
|
|
|
|
|
provider := strings.ToLower(filepath.Base(r.URL.Path))
|
2018-03-09 04:39:51 +02:00
|
|
|
logger.Infof("started oauth2 flow for provider: %s", provider)
|
|
|
|
cfg, ok := o.Authboss.Config.Modules.OAuth2Providers[provider]
|
2015-03-13 04:20:36 +02:00
|
|
|
if !ok {
|
2018-03-09 04:39:51 +02:00
|
|
|
return errors.Errorf("oauth2 provider %q not found", provider)
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
// Create nonce
|
|
|
|
nonce := make([]byte, 32)
|
2018-07-17 19:10:07 +02:00
|
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
2018-03-09 04:39:51 +02:00
|
|
|
return errors.Wrap(err, "failed to create nonce")
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
state := base64.URLEncoding.EncodeToString(nonce)
|
|
|
|
authboss.PutSession(w, authboss.SessionOAuth2State, state)
|
2015-03-13 04:20:36 +02:00
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
// This clearly ignores the fact that query parameters can have multiple
|
|
|
|
// values but I guess we're ignoring that
|
2015-03-25 04:39:20 +02:00
|
|
|
passAlongs := make(map[string]string)
|
2015-03-14 01:23:43 +02:00
|
|
|
for k, vals := range r.URL.Query() {
|
|
|
|
for _, val := range vals {
|
2015-03-25 04:39:20 +02:00
|
|
|
passAlongs[k] = val
|
2015-03-14 01:23:43 +02:00
|
|
|
}
|
|
|
|
}
|
2015-03-25 04:39:20 +02:00
|
|
|
|
2015-03-14 01:23:43 +02:00
|
|
|
if len(passAlongs) > 0 {
|
2018-03-09 04:39:51 +02:00
|
|
|
byt, err := json.Marshal(passAlongs)
|
2015-03-25 04:39:20 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2018-03-09 04:39:51 +02:00
|
|
|
authboss.PutSession(w, authboss.SessionOAuth2Params, string(byt))
|
2015-03-25 04:39:20 +02:00
|
|
|
} else {
|
2018-03-09 04:39:51 +02:00
|
|
|
authboss.DelSession(w, authboss.SessionOAuth2Params)
|
2015-03-14 01:23:43 +02:00
|
|
|
}
|
|
|
|
|
2020-01-29 15:52:00 +02:00
|
|
|
authCodeUrl := cfg.OAuth2Config.AuthCodeURL(state)
|
2015-03-13 04:20:36 +02:00
|
|
|
|
2015-04-01 00:27:47 +02:00
|
|
|
extraParams := cfg.AdditionalParams.Encode()
|
2015-03-13 04:20:36 +02:00
|
|
|
if len(extraParams) > 0 {
|
2020-01-29 15:52:00 +02:00
|
|
|
authCodeUrl = fmt.Sprintf("%s&%s", authCodeUrl, extraParams)
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
ro := authboss.RedirectOptions{
|
|
|
|
Code: http.StatusTemporaryRedirect,
|
2020-01-29 15:52:00 +02:00
|
|
|
RedirectPath: authCodeUrl,
|
2018-03-09 04:39:51 +02:00
|
|
|
}
|
|
|
|
return o.Authboss.Core.Redirector.Redirect(w, r, ro)
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
// for testing, mocked out at the beginning
|
2015-03-13 11:15:58 +02:00
|
|
|
var exchanger = (*oauth2.Config).Exchange
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
// End the oauth2 process, this is the handler for the oauth2 callback
|
|
|
|
// that the third party will redirect to.
|
|
|
|
func (o *OAuth2) End(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
logger := o.Authboss.RequestLogger(r)
|
2015-03-13 04:20:36 +02:00
|
|
|
provider := strings.ToLower(filepath.Base(r.URL.Path))
|
2018-03-09 04:39:51 +02:00
|
|
|
logger.Infof("finishing oauth2 flow for provider: %s", provider)
|
2015-03-13 04:20:36 +02:00
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
// This shouldn't happen because the router should 404 first, but just in case
|
|
|
|
cfg, ok := o.Authboss.Config.Modules.OAuth2Providers[provider]
|
|
|
|
if !ok {
|
|
|
|
return errors.Errorf("oauth2 provider %q not found", provider)
|
|
|
|
}
|
|
|
|
|
|
|
|
wantState, ok := authboss.GetSession(r, authboss.SessionOAuth2State)
|
|
|
|
if !ok {
|
|
|
|
return errors.New("oauth2 endpoint hit without session state")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Verify we got the same state in the session as was passed to us in the
|
|
|
|
// query parameter.
|
|
|
|
state := r.FormValue(FormValueOAuth2State)
|
|
|
|
if state != wantState {
|
|
|
|
return errOAuthStateValidation
|
2015-03-25 04:39:20 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
rawParams, ok := authboss.GetSession(r, authboss.SessionOAuth2Params)
|
|
|
|
var params map[string]string
|
2015-03-25 04:39:20 +02:00
|
|
|
if ok {
|
2018-03-09 04:39:51 +02:00
|
|
|
if err := json.Unmarshal([]byte(rawParams), ¶ms); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to decode oauth2 params")
|
2015-03-25 04:39:20 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
authboss.DelSession(w, authboss.SessionOAuth2State)
|
|
|
|
authboss.DelSession(w, authboss.SessionOAuth2Params)
|
|
|
|
|
2015-03-13 04:20:36 +02:00
|
|
|
hasErr := r.FormValue("error")
|
|
|
|
if len(hasErr) > 0 {
|
2018-03-09 04:39:51 +02:00
|
|
|
reason := r.FormValue("error_reason")
|
|
|
|
logger.Infof("oauth2 login failed: %s, reason: %s", hasErr, reason)
|
|
|
|
|
|
|
|
handled, err := o.Authboss.Events.FireAfter(authboss.EventOAuth2Fail, w, r)
|
|
|
|
if err != nil {
|
2015-03-14 01:23:43 +02:00
|
|
|
return err
|
2018-03-09 04:39:51 +02:00
|
|
|
} else if handled {
|
|
|
|
return nil
|
2015-03-14 01:23:43 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
ro := authboss.RedirectOptions{
|
|
|
|
Code: http.StatusTemporaryRedirect,
|
|
|
|
RedirectPath: o.Authboss.Config.Paths.OAuth2LoginNotOK,
|
|
|
|
Failure: fmt.Sprintf("%s login cancelled or failed", strings.Title(provider)),
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
2018-03-09 04:39:51 +02:00
|
|
|
return o.Authboss.Core.Redirector.Redirect(w, r, ro)
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
// Get the code which we can use to make an access token
|
2015-03-13 04:20:36 +02:00
|
|
|
code := r.FormValue("code")
|
2018-03-09 04:39:51 +02:00
|
|
|
token, err := exchanger(cfg.OAuth2Config, r.Context(), code)
|
2015-03-13 04:20:36 +02:00
|
|
|
if err != nil {
|
2017-02-22 01:04:30 +02:00
|
|
|
return errors.Wrap(err, "could not validate oauth2 code")
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
details, err := cfg.FindUserDetails(r.Context(), *cfg.OAuth2Config, token)
|
2015-03-14 01:23:43 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
storer := authboss.EnsureCanOAuth2(o.Authboss.Config.Storage.Server)
|
|
|
|
user, err := storer.NewFromOAuth2(r.Context(), provider, details)
|
2015-03-13 04:20:36 +02:00
|
|
|
if err != nil {
|
2018-03-09 04:39:51 +02:00
|
|
|
return errors.Wrap(err, "failed to create oauth2 user from values")
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
user.PutOAuth2Provider(provider)
|
|
|
|
user.PutOAuth2AccessToken(token.AccessToken)
|
|
|
|
user.PutOAuth2Expiry(token.Expiry)
|
2015-03-13 11:15:58 +02:00
|
|
|
if len(token.RefreshToken) != 0 {
|
2018-03-09 04:39:51 +02:00
|
|
|
user.PutOAuth2RefreshToken(token.RefreshToken)
|
2015-03-13 11:15:58 +02:00
|
|
|
}
|
2015-03-14 01:23:43 +02:00
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
if err := storer.SaveOAuth2(r.Context(), user); err != nil {
|
2015-03-14 01:23:43 +02:00
|
|
|
return err
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
r = r.WithContext(context.WithValue(r.Context(), authboss.CTXKeyUser, user))
|
2015-03-13 04:20:36 +02:00
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
handled, err := o.Authboss.Events.FireBefore(authboss.EventOAuth2, w, r)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
} else if handled {
|
2015-03-14 01:23:43 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
// Fully log user in
|
|
|
|
authboss.PutSession(w, authboss.SessionKey, authboss.MakeOAuth2PID(provider, user.GetOAuth2UID()))
|
|
|
|
authboss.DelSession(w, authboss.SessionHalfAuthKey)
|
2015-03-25 04:39:20 +02:00
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
// Create a query string from all the pieces we've received
|
|
|
|
// as passthru from the original request.
|
|
|
|
redirect := o.Authboss.Config.Paths.OAuth2LoginOK
|
2015-03-25 04:39:20 +02:00
|
|
|
query := make(url.Values)
|
2018-03-09 04:39:51 +02:00
|
|
|
for k, v := range params {
|
2015-03-25 04:39:20 +02:00
|
|
|
switch k {
|
|
|
|
case authboss.CookieRemember:
|
2018-03-09 04:39:51 +02:00
|
|
|
if v == "true" {
|
|
|
|
r = r.WithContext(context.WithValue(r.Context(), authboss.CTXKeyValues, RMTrue{}))
|
|
|
|
}
|
|
|
|
case FormValueOAuth2Redir:
|
2015-03-25 04:39:20 +02:00
|
|
|
redirect = v
|
|
|
|
default:
|
|
|
|
query.Set(k, v)
|
2015-03-14 01:23:43 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
handled, err = o.Authboss.Events.FireAfter(authboss.EventOAuth2, w, r)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
} else if handled {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-03-25 04:39:20 +02:00
|
|
|
if len(query) > 0 {
|
|
|
|
redirect = fmt.Sprintf("%s?%s", redirect, query.Encode())
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
ro := authboss.RedirectOptions{
|
|
|
|
Code: http.StatusTemporaryRedirect,
|
|
|
|
RedirectPath: redirect,
|
|
|
|
Success: fmt.Sprintf("Logged in successfully with %s.", strings.Title(provider)),
|
|
|
|
}
|
|
|
|
return o.Authboss.Config.Core.Redirector.Redirect(w, r, ro)
|
2015-03-13 04:20:36 +02:00
|
|
|
}
|
2015-03-17 06:46:15 +02:00
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
// RMTrue is a dummy struct implementing authboss.RememberValuer
|
|
|
|
// in order to tell the remember me module to remember them.
|
|
|
|
type RMTrue struct{}
|
2015-03-17 06:46:15 +02:00
|
|
|
|
2018-03-09 04:39:51 +02:00
|
|
|
// GetShouldRemember always returns true
|
|
|
|
func (RMTrue) GetShouldRemember() bool { return true }
|