diff --git a/models/error_oauth2.go b/models/error_oauth2.go new file mode 100644 index 00000000000..94c68a2c12c --- /dev/null +++ b/models/error_oauth2.go @@ -0,0 +1,24 @@ +// Copyright 2017 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package models + +import "fmt" + +// ErrOpenIDConnectInitialize represents a "OpenIDConnectInitialize" kind of error. +type ErrOpenIDConnectInitialize struct { + OpenIDConnectAutoDiscoveryURL string + ProviderName string + Cause error +} + +// IsErrOpenIDConnectInitialize checks if an error is a ExternalLoginUserAlreadyExist. +func IsErrOpenIDConnectInitialize(err error) bool { + _, ok := err.(ErrOpenIDConnectInitialize) + return ok +} + +func (err ErrOpenIDConnectInitialize) Error() string { + return fmt.Sprintf("Failed to initialize OpenID Connect Provider with name '%s' with url '%s': %v", err.ProviderName, err.OpenIDConnectAutoDiscoveryURL, err.Cause) +} diff --git a/models/login_source.go b/models/login_source.go index 401bbf6714a..9c8121977bd 100644 --- a/models/login_source.go +++ b/models/login_source.go @@ -121,9 +121,11 @@ func (cfg *PAMConfig) ToDB() ([]byte, error) { // OAuth2Config holds configuration for the OAuth2 login source. type OAuth2Config struct { - Provider string - ClientID string - ClientSecret string + Provider string + ClientID string + ClientSecret string + OpenIDConnectAutoDiscoveryURL string + CustomURLMapping *oauth2.CustomURLMapping } // FromDB fills up an OAuth2Config from serialized format. @@ -294,9 +296,15 @@ func CreateLoginSource(source *LoginSource) error { } _, err = x.Insert(source) - if err == nil && source.IsOAuth2() { + if err == nil && source.IsOAuth2() && source.IsActived { oAuth2Config := source.OAuth2() - oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret) + err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping) + err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config) + + if err != nil { + // remove the LoginSource in case of errors while registering OAuth2 providers + x.Delete(source) + } } return err } @@ -321,11 +329,25 @@ func GetLoginSourceByID(id int64) (*LoginSource, error) { // UpdateSource updates a LoginSource record in DB. func UpdateSource(source *LoginSource) error { + var originalLoginSource *LoginSource + if source.IsOAuth2() { + // keep track of the original values so we can restore in case of errors while registering OAuth2 providers + var err error + if originalLoginSource, err = GetLoginSourceByID(source.ID); err != nil { + return err + } + } + _, err := x.Id(source.ID).AllCols().Update(source) - if err == nil && source.IsOAuth2() { + if err == nil && source.IsOAuth2() && source.IsActived { oAuth2Config := source.OAuth2() - oauth2.RemoveProvider(source.Name) - oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret) + err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping) + err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config) + + if err != nil { + // restore original values since we cannot update the provider it self + x.Id(source.ID).AllCols().Update(originalLoginSource) + } } return err } @@ -580,27 +602,6 @@ func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMCon return user, CreateUser(user) } -// ________ _____ __ .__ ________ -// \_____ \ / _ \ __ ___/ |_| |__ \_____ \ -// / | \ / /_\ \| | \ __\ | \ / ____/ -// / | \/ | \ | /| | | Y \/ \ -// \_______ /\____|__ /____/ |__| |___| /\_______ \ -// \/ \/ \/ \/ - -// OAuth2Provider describes the display values of a single OAuth2 provider -type OAuth2Provider struct { - Name string - DisplayName string - Image string -} - -// OAuth2Providers contains the map of registered OAuth2 providers in Gitea (based on goth) -// key is used to map the OAuth2Provider with the goth provider type (also in LoginSource.OAuth2Config.Provider) -// value is used to store display data -var OAuth2Providers = map[string]OAuth2Provider{ - "github": {Name: "github", DisplayName: "GitHub", Image: "/img/github.png"}, -} - // ExternalUserLogin attempts a login using external source types. func ExternalUserLogin(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) { if !source.IsActived { @@ -684,59 +685,4 @@ func UserSignIn(username, password string) (*User, error) { } return nil, ErrUserNotExist{user.ID, user.Name, 0} -} - -// GetActiveOAuth2ProviderLoginSources returns all actived LoginOAuth2 sources -func GetActiveOAuth2ProviderLoginSources() ([]*LoginSource, error) { - sources := make([]*LoginSource, 0, 1) - if err := x.UseBool().Find(&sources, &LoginSource{IsActived: true, Type: LoginOAuth2}); err != nil { - return nil, err - } - return sources, nil -} - -// GetActiveOAuth2LoginSourceByName returns a OAuth2 LoginSource based on the given name -func GetActiveOAuth2LoginSourceByName(name string) (*LoginSource, error) { - loginSource := &LoginSource{ - Name: name, - Type: LoginOAuth2, - IsActived: true, - } - - has, err := x.UseBool().Get(loginSource) - if !has || err != nil { - return nil, err - } - - return loginSource, nil -} - -// GetActiveOAuth2Providers returns the map of configured active OAuth2 providers -// key is used as technical name (like in the callbackURL) -// values to display -func GetActiveOAuth2Providers() (map[string]OAuth2Provider, error) { - // Maybe also separate used and unused providers so we can force the registration of only 1 active provider for each type - - loginSources, err := GetActiveOAuth2ProviderLoginSources() - if err != nil { - return nil, err - } - - providers := make(map[string]OAuth2Provider) - for _, source := range loginSources { - providers[source.Name] = OAuth2Providers[source.OAuth2().Provider] - } - - return providers, nil -} - -// InitOAuth2 initialize the OAuth2 lib and register all active OAuth2 providers in the library -func InitOAuth2() { - oauth2.Init() - loginSources, _ := GetActiveOAuth2ProviderLoginSources() - - for _, source := range loginSources { - oAuth2Config := source.OAuth2() - oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret) - } -} +} \ No newline at end of file diff --git a/models/oauth2.go b/models/oauth2.go new file mode 100644 index 00000000000..9de64a05877 --- /dev/null +++ b/models/oauth2.go @@ -0,0 +1,122 @@ +// Copyright 2017 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package models + +import ( + "sort" + "code.gitea.io/gitea/modules/auth/oauth2" +) + +// OAuth2Provider describes the display values of a single OAuth2 provider +type OAuth2Provider struct { + Name string + DisplayName string + Image string + CustomURLMapping *oauth2.CustomURLMapping +} + +// OAuth2Providers contains the map of registered OAuth2 providers in Gitea (based on goth) +// key is used to map the OAuth2Provider with the goth provider type (also in LoginSource.OAuth2Config.Provider) +// value is used to store display data +var OAuth2Providers = map[string]OAuth2Provider{ + "bitbucket": {Name: "bitbucket", DisplayName: "Bitbucket", Image: "/img/auth/bitbucket.png"}, + "dropbox": {Name: "dropbox", DisplayName: "Dropbox", Image: "/img/auth/dropbox.png"}, + "facebook": {Name: "facebook", DisplayName: "Facebook", Image: "/img/auth/facebook.png"}, + "github": {Name: "github", DisplayName: "GitHub", Image: "/img/auth/github.png", + CustomURLMapping: &oauth2.CustomURLMapping{ + TokenURL: oauth2.GetDefaultTokenURL("github"), + AuthURL: oauth2.GetDefaultAuthURL("github"), + ProfileURL: oauth2.GetDefaultProfileURL("github"), + EmailURL: oauth2.GetDefaultEmailURL("github"), + }, + }, + "gitlab": {Name: "gitlab", DisplayName: "GitLab", Image: "/img/auth/gitlab.png", + CustomURLMapping: &oauth2.CustomURLMapping{ + TokenURL: oauth2.GetDefaultTokenURL("gitlab"), + AuthURL: oauth2.GetDefaultAuthURL("gitlab"), + ProfileURL: oauth2.GetDefaultProfileURL("gitlab"), + }, + }, + "gplus": {Name: "gplus", DisplayName: "Google+", Image: "/img/auth/google_plus.png"}, + "openidConnect": {Name: "openidConnect", DisplayName: "OpenID Connect", Image: "/img/auth/openid_connect.png"}, + "twitter": {Name: "twitter", DisplayName: "Twitter", Image: "/img/auth/twitter.png"}, +} + +// OAuth2DefaultCustomURLMappings contains the map of default URL's for OAuth2 providers that are allowed to have custom urls +// key is used to map the OAuth2Provider +// value is the mapping as defined for the OAuth2Provider +var OAuth2DefaultCustomURLMappings = map[string]*oauth2.CustomURLMapping { + "github": OAuth2Providers["github"].CustomURLMapping, + "gitlab": OAuth2Providers["gitlab"].CustomURLMapping, +} + +// GetActiveOAuth2ProviderLoginSources returns all actived LoginOAuth2 sources +func GetActiveOAuth2ProviderLoginSources() ([]*LoginSource, error) { + sources := make([]*LoginSource, 0, 1) + if err := x.UseBool().Find(&sources, &LoginSource{IsActived: true, Type: LoginOAuth2}); err != nil { + return nil, err + } + return sources, nil +} + +// GetActiveOAuth2LoginSourceByName returns a OAuth2 LoginSource based on the given name +func GetActiveOAuth2LoginSourceByName(name string) (*LoginSource, error) { + loginSource := &LoginSource{ + Name: name, + Type: LoginOAuth2, + IsActived: true, + } + + has, err := x.UseBool().Get(loginSource) + if !has || err != nil { + return nil, err + } + + return loginSource, nil +} + +// GetActiveOAuth2Providers returns the map of configured active OAuth2 providers +// key is used as technical name (like in the callbackURL) +// values to display +func GetActiveOAuth2Providers() ([]string, map[string]OAuth2Provider, error) { + // Maybe also separate used and unused providers so we can force the registration of only 1 active provider for each type + + loginSources, err := GetActiveOAuth2ProviderLoginSources() + if err != nil { + return nil, nil, err + } + + var orderedKeys []string + providers := make(map[string]OAuth2Provider) + for _, source := range loginSources { + providers[source.Name] = OAuth2Providers[source.OAuth2().Provider] + orderedKeys = append(orderedKeys, source.Name) + } + + sort.Strings(orderedKeys) + + return orderedKeys, providers, nil +} + +// InitOAuth2 initialize the OAuth2 lib and register all active OAuth2 providers in the library +func InitOAuth2() { + oauth2.Init() + loginSources, _ := GetActiveOAuth2ProviderLoginSources() + + for _, source := range loginSources { + oAuth2Config := source.OAuth2() + oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping) + } +} + +// wrapOpenIDConnectInitializeError is used to wrap the error but this cannot be done in modules/auth/oauth2 +// inside oauth2: import cycle not allowed models -> modules/auth/oauth2 -> models +func wrapOpenIDConnectInitializeError(err error, providerName string, oAuth2Config *OAuth2Config) error { + if err != nil && "openidConnect" == oAuth2Config.Provider { + err = ErrOpenIDConnectInitialize{ProviderName: providerName, OpenIDConnectAutoDiscoveryURL: oAuth2Config.OpenIDConnectAutoDiscoveryURL, Cause: err} + } + return err +} + diff --git a/modules/auth/auth_form.go b/modules/auth/auth_form.go index 338be53457f..8dc039835fd 100644 --- a/modules/auth/auth_form.go +++ b/modules/auth/auth_form.go @@ -11,34 +11,40 @@ import ( // AuthenticationForm form for authentication type AuthenticationForm struct { - ID int64 - Type int `binding:"Range(2,6)"` - Name string `binding:"Required;MaxSize(30)"` - Host string - Port int - BindDN string - BindPassword string - UserBase string - UserDN string - AttributeUsername string - AttributeName string - AttributeSurname string - AttributeMail string - AttributesInBind bool - Filter string - AdminFilter string - IsActive bool - SMTPAuth string - SMTPHost string - SMTPPort int - AllowedDomains string - SecurityProtocol int `binding:"Range(0,2)"` - TLS bool - SkipVerify bool - PAMServiceName string - Oauth2Provider string - Oauth2Key string - Oauth2Secret string + ID int64 + Type int `binding:"Range(2,6)"` + Name string `binding:"Required;MaxSize(30)"` + Host string + Port int + BindDN string + BindPassword string + UserBase string + UserDN string + AttributeUsername string + AttributeName string + AttributeSurname string + AttributeMail string + AttributesInBind bool + Filter string + AdminFilter string + IsActive bool + SMTPAuth string + SMTPHost string + SMTPPort int + AllowedDomains string + SecurityProtocol int `binding:"Range(0,2)"` + TLS bool + SkipVerify bool + PAMServiceName string + Oauth2Provider string + Oauth2Key string + Oauth2Secret string + OpenIDConnectAutoDiscoveryURL string + Oauth2UseCustomURL bool + Oauth2TokenURL string + Oauth2AuthURL string + Oauth2ProfileURL string + Oauth2EmailURL string } // Validate validates fields diff --git a/modules/auth/oauth2/oauth2.go b/modules/auth/oauth2/oauth2.go index ca4cde73b67..4584c48db70 100644 --- a/modules/auth/oauth2/oauth2.go +++ b/modules/auth/oauth2/oauth2.go @@ -5,6 +5,7 @@ package oauth2 import ( + "math" "net/http" "os" "path/filepath" @@ -15,7 +16,14 @@ import ( "github.com/gorilla/sessions" "github.com/markbates/goth" "github.com/markbates/goth/gothic" + "github.com/markbates/goth/providers/bitbucket" + "github.com/markbates/goth/providers/dropbox" + "github.com/markbates/goth/providers/facebook" "github.com/markbates/goth/providers/github" + "github.com/markbates/goth/providers/gitlab" + "github.com/markbates/goth/providers/gplus" + "github.com/markbates/goth/providers/openidConnect" + "github.com/markbates/goth/providers/twitter" "github.com/satori/go.uuid" ) @@ -24,6 +32,14 @@ var ( providerHeaderKey = "gitea-oauth2-provider" ) +// CustomURLMapping describes the urls values to use when customizing OAuth2 provider URLs +type CustomURLMapping struct { + AuthURL string + TokenURL string + ProfileURL string + EmailURL string +} + // Init initialize the setup of the OAuth2 library func Init() { sessionDir := filepath.Join(setting.AppDataPath, "sessions", "oauth2") @@ -31,7 +47,15 @@ func Init() { log.Fatal(4, "Fail to create dir %s: %v", sessionDir, err) } - gothic.Store = sessions.NewFilesystemStore(sessionDir, []byte(sessionUsersStoreKey)) + store := sessions.NewFilesystemStore(sessionDir, []byte(sessionUsersStoreKey)) + // according to the Goth lib: + // set the maxLength of the cookies stored on the disk to a larger number to prevent issues with: + // securecookie: the value is too long + // when using OpenID Connect , since this can contain a large amount of extra information in the id_token + + // Note, when using the FilesystemStore only the session.ID is written to a browser cookie, so this is explicit for the storage on disk + store.MaxLength(math.MaxInt16) + gothic.Store = store gothic.SetState = func(req *http.Request) string { return uuid.NewV4().String() @@ -74,12 +98,14 @@ func ProviderCallback(provider string, request *http.Request, response http.Resp } // RegisterProvider register a OAuth2 provider in goth lib -func RegisterProvider(providerName, providerType, clientID, clientSecret string) { - provider := createProvider(providerName, providerType, clientID, clientSecret) +func RegisterProvider(providerName, providerType, clientID, clientSecret, openIDConnectAutoDiscoveryURL string, customURLMapping *CustomURLMapping) error { + provider, err := createProvider(providerName, providerType, clientID, clientSecret, openIDConnectAutoDiscoveryURL, customURLMapping) - if provider != nil { + if err == nil && provider != nil { goth.UseProviders(provider) } + + return err } // RemoveProvider removes the given OAuth2 provider from the goth lib @@ -88,20 +114,111 @@ func RemoveProvider(providerName string) { } // used to create different types of goth providers -func createProvider(providerName, providerType, clientID, clientSecret string) goth.Provider { +func createProvider(providerName, providerType, clientID, clientSecret, openIDConnectAutoDiscoveryURL string, customURLMapping *CustomURLMapping) (goth.Provider, error) { callbackURL := setting.AppURL + "user/oauth2/" + providerName + "/callback" var provider goth.Provider + var err error switch providerType { + case "bitbucket": + provider = bitbucket.New(clientID, clientSecret, callbackURL, "account") + case "dropbox": + provider = dropbox.New(clientID, clientSecret, callbackURL) + case "facebook": + provider = facebook.New(clientID, clientSecret, callbackURL, "email") case "github": - provider = github.New(clientID, clientSecret, callbackURL, "user:email") + authURL := github.AuthURL + tokenURL := github.TokenURL + profileURL := github.ProfileURL + emailURL := github.EmailURL + if customURLMapping != nil { + if len(customURLMapping.AuthURL) > 0 { + authURL = customURLMapping.AuthURL + } + if len(customURLMapping.TokenURL) > 0 { + tokenURL = customURLMapping.TokenURL + } + if len(customURLMapping.ProfileURL) > 0 { + profileURL = customURLMapping.ProfileURL + } + if len(customURLMapping.EmailURL) > 0 { + emailURL = customURLMapping.EmailURL + } + } + provider = github.NewCustomisedURL(clientID, clientSecret, callbackURL, authURL, tokenURL, profileURL, emailURL) + case "gitlab": + authURL := gitlab.AuthURL + tokenURL := gitlab.TokenURL + profileURL := gitlab.ProfileURL + if customURLMapping != nil { + if len(customURLMapping.AuthURL) > 0 { + authURL = customURLMapping.AuthURL + } + if len(customURLMapping.TokenURL) > 0 { + tokenURL = customURLMapping.TokenURL + } + if len(customURLMapping.ProfileURL) > 0 { + profileURL = customURLMapping.ProfileURL + } + } + provider = gitlab.NewCustomisedURL(clientID, clientSecret, callbackURL, authURL, tokenURL, profileURL) + case "gplus": + provider = gplus.New(clientID, clientSecret, callbackURL, "email") + case "openidConnect": + if provider, err = openidConnect.New(clientID, clientSecret, callbackURL, openIDConnectAutoDiscoveryURL); err != nil { + log.Warn("Failed to create OpenID Connect Provider with name '%s' with url '%s': %v", providerName, openIDConnectAutoDiscoveryURL, err) + } + case "twitter": + provider = twitter.NewAuthenticate(clientID, clientSecret, callbackURL) } // always set the name if provider is created so we can support multiple setups of 1 provider - if provider != nil { + if err == nil && provider != nil { provider.SetName(providerName) } - return provider + return provider, err +} + +// GetDefaultTokenURL return the default token url for the given provider +func GetDefaultTokenURL(provider string) string { + switch provider { + case "github": + return github.TokenURL + case "gitlab": + return gitlab.TokenURL + } + return "" +} + +// GetDefaultAuthURL return the default authorize url for the given provider +func GetDefaultAuthURL(provider string) string { + switch provider { + case "github": + return github.AuthURL + case "gitlab": + return gitlab.AuthURL + } + return "" +} + +// GetDefaultProfileURL return the default profile url for the given provider +func GetDefaultProfileURL(provider string) string { + switch provider { + case "github": + return github.ProfileURL + case "gitlab": + return gitlab.ProfileURL + } + return "" +} + +// GetDefaultEmailURL return the default email url for the given provider +func GetDefaultEmailURL(provider string) string { + switch provider { + case "github": + return github.EmailURL + } + return "" } diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index f1f6925bb58..4ffed1ddaef 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -1171,12 +1171,28 @@ auths.allowed_domains_helper = Leave it empty to not restrict any domains. Multi auths.enable_tls = Enable TLS Encryption auths.skip_tls_verify = Skip TLS Verify auths.pam_service_name = PAM Service Name -auths.oauth2_provider = OAuth2 provider +auths.oauth2_provider = OAuth2 Provider auths.oauth2_clientID = Client ID (Key) auths.oauth2_clientSecret = Client Secret +auths.openIdConnectAutoDiscoveryURL = OpenID Connect Auto Discovery URL +auths.oauth2_use_custom_url = Use custom URLs instead of default URLs +auths.oauth2_tokenURL = Token URL +auths.oauth2_authURL = Authorize URL +auths.oauth2_profileURL = Profile URL +auths.oauth2_emailURL = Email URL auths.enable_auto_register = Enable Auto Registration auths.tips = Tips -auths.tip.github = Register a new OAuth application on https://github.com/settings/applications/new and use /user/oauth2//callback as "Authorization callback URL" +auths.tips.oauth2.general = OAuth2 Authentication +auths.tips.oauth2.general.tip = When registering a new OAuth2 authentication, the callback/redirect URL should be: /user/oauth2//callback +auths.tip.oauth2_provider = OAuth2 Provider +auths.tip.bitbucket = Register a new OAuth consumer on https://bitbucket.org/account/user//oauth-consumers/new and add the permission "Account"-"Read" +auths.tip.dropbox = Create a new App on https://www.dropbox.com/developers/apps +auths.tip.facebook = Register a new App on https://developers.facebook.com/apps and add the product "Facebook Login" +auths.tip.github = Register a new OAuth application on https://github.com/settings/applications/new +auths.tip.gitlab = Register a new application on https://gitlab.com/profile/applications +auths.tip.google_plus = Obtain OAuth2 client credentials from the Google API console (https://console.developers.google.com/) +auths.tip.openid_connect = Use the OpenID Connect Discovery URL (/.well-known/openid-configuration) to specify the endpoints +auths.tip.twitter = Go to https://dev.twitter.com/apps , create an application and ensure that the “Allow this application to be used to Sign in with Twitter” option is enabled. auths.edit = Edit Authentication Setting auths.activated = This authentication is activated auths.new_success = New authentication '%s' has been added successfully. diff --git a/public/css/index.css b/public/css/index.css index b0fc396cca5..3fa2d6d0fd9 100644 --- a/public/css/index.css +++ b/public/css/index.css @@ -965,7 +965,7 @@ footer .ui.language .menu { float: left; } .signin .oauth2 a { - margin-right: 5px; + margin-right: 3px; } .signin .oauth2 a:last-child { margin-right: 0px; @@ -974,6 +974,9 @@ footer .ui.language .menu { width: 32px; height: 32px; } +.signin .oauth2 img.openidConnect { + width: auto; +} .user.activate form, .user.forgot.password form, .user.reset.password form, diff --git a/public/img/auth/bitbucket.png b/public/img/auth/bitbucket.png new file mode 100644 index 00000000000..b3d022a5a70 Binary files /dev/null and b/public/img/auth/bitbucket.png differ diff --git a/public/img/auth/dropbox.png b/public/img/auth/dropbox.png new file mode 100644 index 00000000000..da2348872a0 Binary files /dev/null and b/public/img/auth/dropbox.png differ diff --git a/public/img/auth/facebook.png b/public/img/auth/facebook.png new file mode 100644 index 00000000000..29273af14fb Binary files /dev/null and b/public/img/auth/facebook.png differ diff --git a/public/img/github.png b/public/img/auth/github.png similarity index 100% rename from public/img/github.png rename to public/img/auth/github.png diff --git a/public/img/auth/gitlab.png b/public/img/auth/gitlab.png new file mode 100644 index 00000000000..ca30b459019 Binary files /dev/null and b/public/img/auth/gitlab.png differ diff --git a/public/img/auth/google_plus.png b/public/img/auth/google_plus.png new file mode 100644 index 00000000000..720824230a5 Binary files /dev/null and b/public/img/auth/google_plus.png differ diff --git a/public/img/auth/openid_connect.png b/public/img/auth/openid_connect.png new file mode 100644 index 00000000000..af033cd1fe1 Binary files /dev/null and b/public/img/auth/openid_connect.png differ diff --git a/public/img/auth/twitter.png b/public/img/auth/twitter.png new file mode 100644 index 00000000000..a4f14de57ae Binary files /dev/null and b/public/img/auth/twitter.png differ diff --git a/public/js/index.js b/public/js/index.js index 9b48c24cd3d..31b15a76a79 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -1047,6 +1047,56 @@ function initAdmin() { } } + function onOAuth2Change() { + $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide(); + $('.open_id_connect_auto_discovery_url input[required]').removeAttr('required'); + + var provider = $('#oauth2_provider').val(); + switch (provider) { + case 'github': + case 'gitlab': + $('.oauth2_use_custom_url').show(); + break; + case 'openidConnect': + $('.open_id_connect_auto_discovery_url input').attr('required', 'required'); + $('.open_id_connect_auto_discovery_url').show(); + break; + } + onOAuth2UseCustomURLChange(); + } + + function onOAuth2UseCustomURLChange() { + var provider = $('#oauth2_provider').val(); + $('.oauth2_use_custom_url_field').hide(); + $('.oauth2_use_custom_url_field input[required]').removeAttr('required'); + + if ($('#oauth2_use_custom_url').is(':checked')) { + if (!$('#oauth2_token_url').val()) { + $('#oauth2_token_url').val($('#' + provider + '_token_url').val()); + } + if (!$('#oauth2_auth_url').val()) { + $('#oauth2_auth_url').val($('#' + provider + '_auth_url').val()); + } + if (!$('#oauth2_profile_url').val()) { + $('#oauth2_profile_url').val($('#' + provider + '_profile_url').val()); + } + if (!$('#oauth2_email_url').val()) { + $('#oauth2_email_url').val($('#' + provider + '_email_url').val()); + } + switch (provider) { + case 'github': + $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input').attr('required', 'required'); + $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url').show(); + break; + case 'gitlab': + $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input').attr('required', 'required'); + $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show(); + $('#oauth2_email_url').val(''); + break; + } + } + } + // New authentication if ($('.admin.new.authentication').length > 0) { $('#auth_type').change(function () { @@ -1075,22 +1125,28 @@ function initAdmin() { break; case '6': // OAuth2 $('.oauth2').show(); - $('.oauth2 input').attr('required', 'required'); + $('.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input').attr('required', 'required'); + onOAuth2Change(); break; } - if (authType == '2' || authType == '5') { onSecurityProtocolChange() } }); $('#auth_type').change(); - $('#security_protocol').change(onSecurityProtocolChange) + $('#security_protocol').change(onSecurityProtocolChange); + $('#oauth2_provider').change(onOAuth2Change); + $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange); } // Edit authentication if ($('.admin.edit.authentication').length > 0) { var authType = $('#auth_type').val(); if (authType == '2' || authType == '5') { $('#security_protocol').change(onSecurityProtocolChange); + } else if (authType == '6') { + $('#oauth2_provider').change(onOAuth2Change); + $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange); + onOAuth2Change(); } } diff --git a/public/less/_form.less b/public/less/_form.less index fc0fdddad10..4542c092db0 100644 --- a/public/less/_form.less +++ b/public/less/_form.less @@ -56,7 +56,7 @@ } } a { - margin-right: 5px; + margin-right: 3px; &:last-child { margin-right: 0px; } @@ -64,6 +64,9 @@ img { width: 32px; height: 32px; + &.openidConnect { + width: auto; + } } } } diff --git a/routers/admin/auths.go b/routers/admin/auths.go index 345494b4f66..eb7c7e8e939 100644 --- a/routers/admin/auths.go +++ b/routers/admin/auths.go @@ -7,16 +7,17 @@ package admin import ( "fmt" - "github.com/Unknwon/com" - "github.com/go-xorm/core" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/auth/ldap" + "code.gitea.io/gitea/modules/auth/oauth2" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" + + "github.com/Unknwon/com" + "github.com/go-xorm/core" ) const ( @@ -77,6 +78,7 @@ func NewAuthSource(ctx *context.Context) { ctx.Data["SecurityProtocols"] = securityProtocols ctx.Data["SMTPAuths"] = models.SMTPAuths ctx.Data["OAuth2Providers"] = models.OAuth2Providers + ctx.Data["OAuth2DefaultCustomURLMappings"] = models.OAuth2DefaultCustomURLMappings // only the first as default for key := range models.OAuth2Providers { @@ -123,10 +125,23 @@ func parseSMTPConfig(form auth.AuthenticationForm) *models.SMTPConfig { } func parseOAuth2Config(form auth.AuthenticationForm) *models.OAuth2Config { + var customURLMapping *oauth2.CustomURLMapping + if form.Oauth2UseCustomURL { + customURLMapping = &oauth2.CustomURLMapping{ + TokenURL: form.Oauth2TokenURL, + AuthURL: form.Oauth2AuthURL, + ProfileURL: form.Oauth2ProfileURL, + EmailURL: form.Oauth2EmailURL, + } + } else { + customURLMapping = nil + } return &models.OAuth2Config{ - Provider: form.Oauth2Provider, - ClientID: form.Oauth2Key, - ClientSecret: form.Oauth2Secret, + Provider: form.Oauth2Provider, + ClientID: form.Oauth2Key, + ClientSecret: form.Oauth2Secret, + OpenIDConnectAutoDiscoveryURL: form.OpenIDConnectAutoDiscoveryURL, + CustomURLMapping: customURLMapping, } } @@ -142,6 +157,7 @@ func NewAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) { ctx.Data["SecurityProtocols"] = securityProtocols ctx.Data["SMTPAuths"] = models.SMTPAuths ctx.Data["OAuth2Providers"] = models.OAuth2Providers + ctx.Data["OAuth2DefaultCustomURLMappings"] = models.OAuth2DefaultCustomURLMappings hasTLS := false var config core.Conversion @@ -199,6 +215,7 @@ func EditAuthSource(ctx *context.Context) { ctx.Data["SecurityProtocols"] = securityProtocols ctx.Data["SMTPAuths"] = models.SMTPAuths ctx.Data["OAuth2Providers"] = models.OAuth2Providers + ctx.Data["OAuth2DefaultCustomURLMappings"] = models.OAuth2DefaultCustomURLMappings source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid")) if err != nil { @@ -222,6 +239,7 @@ func EditAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) { ctx.Data["SMTPAuths"] = models.SMTPAuths ctx.Data["OAuth2Providers"] = models.OAuth2Providers + ctx.Data["OAuth2DefaultCustomURLMappings"] = models.OAuth2DefaultCustomURLMappings source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid")) if err != nil { @@ -257,7 +275,12 @@ func EditAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) { source.IsActived = form.IsActive source.Cfg = config if err := models.UpdateSource(source); err != nil { - ctx.Handle(500, "UpdateSource", err) + if models.IsErrOpenIDConnectInitialize(err) { + ctx.Flash.Error(err.Error(), true) + ctx.HTML(200, tplAuthEdit) + } else { + ctx.Handle(500, "UpdateSource", err) + } return } log.Trace("Authentication changed by admin(%s): %d", ctx.User.Name, source.ID) diff --git a/routers/user/auth.go b/routers/user/auth.go index ba20dc7d42f..68bfe6b05c2 100644 --- a/routers/user/auth.go +++ b/routers/user/auth.go @@ -107,17 +107,19 @@ func checkAutoLogin(ctx *context.Context) bool { // SignIn render sign in page func SignIn(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("sign_in") // Check auto-login. if checkAutoLogin(ctx) { return } - oauth2Providers, err := models.GetActiveOAuth2Providers() + orderedOAuth2Names, oauth2Providers, err := models.GetActiveOAuth2Providers() if err != nil { ctx.Handle(500, "UserSignIn", err) return } + ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names ctx.Data["OAuth2Providers"] = oauth2Providers ctx.Data["Title"] = ctx.Tr("sign_in") ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login" @@ -129,11 +131,14 @@ func SignIn(ctx *context.Context) { // SignInPost response for sign in request func SignInPost(ctx *context.Context, form auth.SignInForm) { - oauth2Providers, err := models.GetActiveOAuth2Providers() + ctx.Data["Title"] = ctx.Tr("sign_in") + + orderedOAuth2Names, oauth2Providers, err := models.GetActiveOAuth2Providers() if err != nil { ctx.Handle(500, "UserSignIn", err) return } + ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names ctx.Data["OAuth2Providers"] = oauth2Providers ctx.Data["Title"] = ctx.Tr("sign_in") ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login" diff --git a/templates/admin/auth/edit.tmpl b/templates/admin/auth/edit.tmpl index ea5104b79fd..3c74b2ad175 100644 --- a/templates/admin/auth/edit.tmpl +++ b/templates/admin/auth/edit.tmpl @@ -164,6 +164,39 @@ +
+ + +
+ +
+
+ + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ {{if .OAuth2DefaultCustomURLMappings}}{{range $key, $value := .OAuth2DefaultCustomURLMappings}} + + + + + {{end}}{{end}} {{end}}
diff --git a/templates/admin/auth/new.tmpl b/templates/admin/auth/new.tmpl index a18a782fc1c..00239b0462c 100644 --- a/templates/admin/auth/new.tmpl +++ b/templates/admin/auth/new.tmpl @@ -80,8 +80,29 @@
GMail Settings:

Host: smtp.gmail.com, Port: 587, Enable TLS Encryption: true

-
OAuth GitHub:
-

{{.i18n.Tr "admin.auths.tip.github"}}

+ +
{{.i18n.Tr "admin.auths.tips.oauth2.general"}}:
+

{{.i18n.Tr "admin.auths.tips.oauth2.general.tip"}}

+ +
{{.i18n.Tr "admin.auths.tip.oauth2_provider"}}
+
+
  • Bitbucket
  • + {{.i18n.Tr "admin.auths.tip.bitbucket"}} +
  • Dropbox
  • + {{.i18n.Tr "admin.auths.tip.dropbox"}} +
  • Facebook
  • + {{.i18n.Tr "admin.auths.tip.facebook"}} +
  • GitHub
  • + {{.i18n.Tr "admin.auths.tip.github"}} +
  • GitLab
  • + {{.i18n.Tr "admin.auths.tip.gitlab"}} +
  • Google+
  • + {{.i18n.Tr "admin.auths.tip.google_plus"}} +
  • OpenID Connect
  • + {{.i18n.Tr "admin.auths.tip.openid_connect"}} +
  • Twitter
  • + {{.i18n.Tr "admin.auths.tip.twitter"}} +
    diff --git a/templates/admin/auth/source/oauth.tmpl b/templates/admin/auth/source/oauth.tmpl index 4d8e12e0283..5d585c04dc6 100644 --- a/templates/admin/auth/source/oauth.tmpl +++ b/templates/admin/auth/source/oauth.tmpl @@ -20,4 +20,39 @@ - +
    + + +
    + +
    +
    + + +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    + {{if .OAuth2DefaultCustomURLMappings}} + {{range $key, $value := .OAuth2DefaultCustomURLMappings}} + + + + + {{end}} + {{end}} + \ No newline at end of file diff --git a/templates/user/auth/link_account.tmpl b/templates/user/auth/link_account.tmpl index 5dc54ca5a4d..73aafd6feb8 100644 --- a/templates/user/auth/link_account.tmpl +++ b/templates/user/auth/link_account.tmpl @@ -8,6 +8,8 @@ + {{template "user/auth/signup_inner" .}} {{template "base/footer" .}} diff --git a/templates/user/auth/signin_inner.tmpl b/templates/user/auth/signin_inner.tmpl index c89f2f358d5..0dfd6c7f165 100644 --- a/templates/user/auth/signin_inner.tmpl +++ b/templates/user/auth/signin_inner.tmpl @@ -38,11 +38,14 @@ {{end}} - {{if .OAuth2Providers}} + {{if and .OrderedOAuth2Names .OAuth2Providers}}
    -

    {{.i18n.Tr "sign_in_with"}}

    {{range $key, $value := .OAuth2Providers}}{{$value.DisplayName}}{{end}} +

    {{.i18n.Tr "sign_in_with"}}

    {{range $key := .OrderedOAuth2Names}} + {{$provider := index $.OAuth2Providers $key}} + {{$provider.DisplayName}}{{if eq $provider.Name + {{end}}
    diff --git a/vendor/github.com/markbates/goth/providers/bitbucket/bitbucket.go b/vendor/github.com/markbates/goth/providers/bitbucket/bitbucket.go new file mode 100644 index 00000000000..06d9c923cbc --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/bitbucket/bitbucket.go @@ -0,0 +1,206 @@ +// Package bitbucket implements the OAuth2 protocol for authenticating users through Bitbucket. +package bitbucket + +import ( + "bytes" + "encoding/json" + "io" + "io/ioutil" + "net/http" + "net/url" + + "github.com/markbates/goth" + "golang.org/x/oauth2" + "fmt" +) + +const ( + authURL string = "https://bitbucket.org/site/oauth2/authorize" + tokenURL string = "https://bitbucket.org/site/oauth2/access_token" + endpointProfile string = "https://api.bitbucket.org/2.0/user" + endpointEmail string = "https://api.bitbucket.org/2.0/user/emails" +) + +// New creates a new Bitbucket provider, and sets up important connection details. +// You should always call `bitbucket.New` to get a new Provider. Never try to create +// one manually. +func New(clientKey, secret, callbackURL string, scopes ...string) *Provider { + p := &Provider{ + ClientKey: clientKey, + Secret: secret, + CallbackURL: callbackURL, + providerName: "bitbucket", + } + p.config = newConfig(p, scopes) + return p +} + +// Provider is the implementation of `goth.Provider` for accessing Bitbucket. +type Provider struct { + ClientKey string + Secret string + CallbackURL string + HTTPClient *http.Client + config *oauth2.Config + providerName string +} + +// Name is the name used to retrieve this provider later. +func (p *Provider) Name() string { + return p.providerName +} + +// SetName is to update the name of the provider (needed in case of multiple providers of 1 type) +func (p *Provider) SetName(name string) { + p.providerName = name +} + +func (p *Provider) Client() *http.Client { + return goth.HTTPClientWithFallBack(p.HTTPClient) +} + +// Debug is a no-op for the bitbucket package. +func (p *Provider) Debug(debug bool) {} + +// BeginAuth asks Bitbucket for an authentication end-point. +func (p *Provider) BeginAuth(state string) (goth.Session, error) { + url := p.config.AuthCodeURL(state) + session := &Session{ + AuthURL: url, + } + return session, nil +} + +// FetchUser will go to Bitbucket and access basic information about the user. +func (p *Provider) FetchUser(session goth.Session) (goth.User, error) { + sess := session.(*Session) + user := goth.User{ + AccessToken: sess.AccessToken, + Provider: p.Name(), + RefreshToken: sess.RefreshToken, + ExpiresAt: sess.ExpiresAt, + } + + if user.AccessToken == "" { + // data is not yet retrieved since accessToken is still empty + return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName) + } + + response, err := goth.HTTPClientWithFallBack(p.Client()).Get(endpointProfile + "?access_token=" + url.QueryEscape(sess.AccessToken)) + if err != nil { + return user, err + } + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, response.StatusCode) + } + + bits, err := ioutil.ReadAll(response.Body) + if err != nil { + return user, err + } + + err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData) + if err != nil { + return user, err + } + + err = userFromReader(bytes.NewReader(bits), &user) + + response, err = goth.HTTPClientWithFallBack(p.Client()).Get(endpointEmail + "?access_token=" + url.QueryEscape(sess.AccessToken)) + if err != nil { + return user, err + } + defer response.Body.Close() + + bits, err = ioutil.ReadAll(response.Body) + if err != nil { + return user, err + } + + err = emailFromReader(bytes.NewReader(bits), &user) + return user, err +} + +func userFromReader(reader io.Reader, user *goth.User) error { + u := struct { + ID string `json:"uuid"` + Links struct { + Avatar struct { + URL string `json:"href"` + } `json:"avatar"` + } `json:"links"` + Email string `json:"email"` + Username string `json:"username"` + Name string `json:"display_name"` + Location string `json:"location"` + }{} + + err := json.NewDecoder(reader).Decode(&u) + if err != nil { + return err + } + + user.Name = u.Name + user.NickName = u.Username + user.AvatarURL = u.Links.Avatar.URL + user.UserID = u.ID + user.Location = u.Location + + return err +} + +func emailFromReader(reader io.Reader, user *goth.User) error { + e := struct { + Values []struct { + Email string `json:"email"` + } `json:"values"` + }{} + + err := json.NewDecoder(reader).Decode(&e) + if err != nil { + return err + } + + if len(e.Values) > 0 { + user.Email = e.Values[0].Email + } + + return err +} + +func newConfig(provider *Provider, scopes []string) *oauth2.Config { + c := &oauth2.Config{ + ClientID: provider.ClientKey, + ClientSecret: provider.Secret, + RedirectURL: provider.CallbackURL, + Endpoint: oauth2.Endpoint{ + AuthURL: authURL, + TokenURL: tokenURL, + }, + Scopes: []string{}, + } + + for _, scope := range scopes { + c.Scopes = append(c.Scopes, scope) + } + + return c +} + +//RefreshTokenAvailable refresh token is provided by auth provider or not +func (p *Provider) RefreshTokenAvailable() bool { + return true +} + +//RefreshToken get new access token based on the refresh token +func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) { + token := &oauth2.Token{RefreshToken: refreshToken} + ts := p.config.TokenSource(goth.ContextForClient(p.Client()), token) + newToken, err := ts.Token() + if err != nil { + return nil, err + } + return newToken, err +} diff --git a/vendor/github.com/markbates/goth/providers/bitbucket/session.go b/vendor/github.com/markbates/goth/providers/bitbucket/session.go new file mode 100644 index 00000000000..a65242151bf --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/bitbucket/session.go @@ -0,0 +1,61 @@ +package bitbucket + +import ( + "encoding/json" + "errors" + "strings" + "time" + + "github.com/markbates/goth" +) + +// Session stores data during the auth process with Bitbucket. +type Session struct { + AuthURL string + AccessToken string + RefreshToken string + ExpiresAt time.Time +} + +// GetAuthURL will return the URL set by calling the `BeginAuth` function on the Bitbucket provider. +func (s Session) GetAuthURL() (string, error) { + if s.AuthURL == "" { + return "", errors.New(goth.NoAuthUrlErrorMessage) + } + return s.AuthURL, nil +} + +// Authorize the session with Bitbucket and return the access token to be stored for future use. +func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) { + p := provider.(*Provider) + token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code")) + if err != nil { + return "", err + } + + if !token.Valid() { + return "", errors.New("Invalid token received from provider") + } + + s.AccessToken = token.AccessToken + s.RefreshToken = token.RefreshToken + s.ExpiresAt = token.Expiry + return token.AccessToken, err +} + +// Marshal the session into a string +func (s Session) Marshal() string { + b, _ := json.Marshal(s) + return string(b) +} + +// UnmarshalSession will unmarshal a JSON string into a session. +func (p *Provider) UnmarshalSession(data string) (goth.Session, error) { + sess := &Session{} + err := json.NewDecoder(strings.NewReader(data)).Decode(sess) + return sess, err +} + +func (s Session) String() string { + return s.Marshal() +} diff --git a/vendor/github.com/markbates/goth/providers/dropbox/dropbox.go b/vendor/github.com/markbates/goth/providers/dropbox/dropbox.go new file mode 100644 index 00000000000..61533d405eb --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/dropbox/dropbox.go @@ -0,0 +1,191 @@ +// Package dropbox implements the OAuth2 protocol for authenticating users through Dropbox. +package dropbox + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "strings" + + "github.com/markbates/goth" + "golang.org/x/oauth2" + "fmt" +) + +const ( + authURL = "https://www.dropbox.com/1/oauth2/authorize" + tokenURL = "https://api.dropbox.com/1/oauth2/token" + accountURL = "https://api.dropbox.com/1/account/info" +) + +// Provider is the implementation of `goth.Provider` for accessing Dropbox. +type Provider struct { + ClientKey string + Secret string + CallbackURL string + HTTPClient *http.Client + config *oauth2.Config + providerName string +} + +// Session stores data during the auth process with Dropbox. +type Session struct { + AuthURL string + Token string +} + +// New creates a new Dropbox provider and sets up important connection details. +// You should always call `dropbox.New` to get a new provider. Never try to +// create one manually. +func New(clientKey, secret, callbackURL string, scopes ...string) *Provider { + p := &Provider{ + ClientKey: clientKey, + Secret: secret, + CallbackURL: callbackURL, + providerName: "dropbox", + } + p.config = newConfig(p, scopes) + return p +} + +// Name is the name used to retrieve this provider later. +func (p *Provider) Name() string { + return p.providerName +} + +// SetName is to update the name of the provider (needed in case of multiple providers of 1 type) +func (p *Provider) SetName(name string) { + p.providerName = name +} + +func (p *Provider) Client() *http.Client { + return goth.HTTPClientWithFallBack(p.HTTPClient) +} + +// Debug is a no-op for the dropbox package. +func (p *Provider) Debug(debug bool) {} + +// BeginAuth asks Dropbox for an authentication end-point. +func (p *Provider) BeginAuth(state string) (goth.Session, error) { + return &Session{ + AuthURL: p.config.AuthCodeURL(state), + }, nil +} + +// FetchUser will go to Dropbox and access basic information about the user. +func (p *Provider) FetchUser(session goth.Session) (goth.User, error) { + s := session.(*Session) + user := goth.User{ + AccessToken: s.Token, + Provider: p.Name(), + } + + if user.AccessToken == "" { + // data is not yet retrieved since accessToken is still empty + return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName) + } + + req, err := http.NewRequest("GET", accountURL, nil) + if err != nil { + return user, err + } + req.Header.Set("Authorization", "Bearer "+s.Token) + resp, err := p.Client().Do(req) + if err != nil { + return user, err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, resp.StatusCode) + } + + err = userFromReader(resp.Body, &user) + return user, err +} + +// UnmarshalSession wil unmarshal a JSON string into a session. +func (p *Provider) UnmarshalSession(data string) (goth.Session, error) { + s := &Session{} + err := json.NewDecoder(strings.NewReader(data)).Decode(s) + return s, err +} + +// GetAuthURL gets the URL set by calling the `BeginAuth` function on the Dropbox provider. +func (s *Session) GetAuthURL() (string, error) { + if s.AuthURL == "" { + return "", errors.New("dropbox: missing AuthURL") + } + return s.AuthURL, nil +} + +// Authorize the session with Dropbox and return the access token to be stored for future use. +func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) { + p := provider.(*Provider) + token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code")) + if err != nil { + return "", err + } + + if !token.Valid() { + return "", errors.New("Invalid token received from provider") + } + + s.Token = token.AccessToken + return token.AccessToken, nil +} + +// Marshal the session into a string +func (s *Session) Marshal() string { + b, _ := json.Marshal(s) + return string(b) +} + +func (s Session) String() string { + return s.Marshal() +} + +func newConfig(p *Provider, scopes []string) *oauth2.Config { + c := &oauth2.Config{ + ClientID: p.ClientKey, + ClientSecret: p.Secret, + RedirectURL: p.CallbackURL, + Endpoint: oauth2.Endpoint{ + AuthURL: authURL, + TokenURL: tokenURL, + }, + } + return c +} + +func userFromReader(r io.Reader, user *goth.User) error { + u := struct { + Name string `json:"display_name"` + NameDetails struct { + NickName string `json:"familiar_name"` + } `json:"name_details"` + Location string `json:"country"` + Email string `json:"email"` + }{} + err := json.NewDecoder(r).Decode(&u) + if err != nil { + return err + } + user.Email = u.Email + user.Name = u.Name + user.NickName = u.NameDetails.NickName + user.UserID = u.Email // Dropbox doesn't provide a separate user ID + user.Location = u.Location + return nil +} + +//RefreshToken refresh token is not provided by dropbox +func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) { + return nil, errors.New("Refresh token is not provided by dropbox") +} + +//RefreshTokenAvailable refresh token is not provided by dropbox +func (p *Provider) RefreshTokenAvailable() bool { + return false +} diff --git a/vendor/github.com/markbates/goth/providers/facebook/facebook.go b/vendor/github.com/markbates/goth/providers/facebook/facebook.go new file mode 100644 index 00000000000..e0cfdf1e34a --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/facebook/facebook.go @@ -0,0 +1,195 @@ +// Package facebook implements the OAuth2 protocol for authenticating users through Facebook. +// This package can be used as a reference implementation of an OAuth2 provider for Goth. +package facebook + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "io/ioutil" + "net/http" + "net/url" + + "github.com/markbates/goth" + "golang.org/x/oauth2" + "fmt" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" +) + +const ( + authURL string = "https://www.facebook.com/dialog/oauth" + tokenURL string = "https://graph.facebook.com/oauth/access_token" + endpointProfile string = "https://graph.facebook.com/me?fields=email,first_name,last_name,link,about,id,name,picture,location" +) + +// New creates a new Facebook provider, and sets up important connection details. +// You should always call `facebook.New` to get a new Provider. Never try to create +// one manually. +func New(clientKey, secret, callbackURL string, scopes ...string) *Provider { + p := &Provider{ + ClientKey: clientKey, + Secret: secret, + CallbackURL: callbackURL, + providerName: "facebook", + } + p.config = newConfig(p, scopes) + return p +} + +// Provider is the implementation of `goth.Provider` for accessing Facebook. +type Provider struct { + ClientKey string + Secret string + CallbackURL string + HTTPClient *http.Client + config *oauth2.Config + providerName string +} + +// Name is the name used to retrieve this provider later. +func (p *Provider) Name() string { + return p.providerName +} + +// SetName is to update the name of the provider (needed in case of multiple providers of 1 type) +func (p *Provider) SetName(name string) { + p.providerName = name +} + +func (p *Provider) Client() *http.Client { + return goth.HTTPClientWithFallBack(p.HTTPClient) +} + +// Debug is a no-op for the facebook package. +func (p *Provider) Debug(debug bool) {} + +// BeginAuth asks Facebook for an authentication end-point. +func (p *Provider) BeginAuth(state string) (goth.Session, error) { + url := p.config.AuthCodeURL(state) + session := &Session{ + AuthURL: url, + } + return session, nil +} + +// FetchUser will go to Facebook and access basic information about the user. +func (p *Provider) FetchUser(session goth.Session) (goth.User, error) { + sess := session.(*Session) + user := goth.User{ + AccessToken: sess.AccessToken, + Provider: p.Name(), + ExpiresAt: sess.ExpiresAt, + } + + if user.AccessToken == "" { + // data is not yet retrieved since accessToken is still empty + return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName) + } + + // always add appsecretProof to make calls more protected + // https://github.com/markbates/goth/issues/96 + // https://developers.facebook.com/docs/graph-api/securing-requests + hash := hmac.New(sha256.New, []byte(p.Secret)) + hash.Write([]byte(sess.AccessToken)) + appsecretProof := hex.EncodeToString(hash.Sum(nil)) + + response, err := p.Client().Get(endpointProfile + "&access_token=" + url.QueryEscape(sess.AccessToken) + "&appsecret_proof=" + appsecretProof) + if err != nil { + return user, err + } + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, response.StatusCode) + } + + bits, err := ioutil.ReadAll(response.Body) + if err != nil { + return user, err + } + + err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData) + if err != nil { + return user, err + } + + err = userFromReader(bytes.NewReader(bits), &user) + return user, err +} + +func userFromReader(reader io.Reader, user *goth.User) error { + u := struct { + ID string `json:"id"` + Email string `json:"email"` + About string `json:"about"` + Name string `json:"name"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Link string `json:"link"` + Picture struct { + Data struct { + URL string `json:"url"` + } `json:"data"` + } `json:"picture"` + Location struct { + Name string `json:"name"` + } `json:"location"` + }{} + + err := json.NewDecoder(reader).Decode(&u) + if err != nil { + return err + } + + user.Name = u.Name + user.FirstName = u.FirstName + user.LastName = u.LastName + user.NickName = u.Name + user.Email = u.Email + user.Description = u.About + user.AvatarURL = u.Picture.Data.URL + user.UserID = u.ID + user.Location = u.Location.Name + + return err +} + +func newConfig(provider *Provider, scopes []string) *oauth2.Config { + c := &oauth2.Config{ + ClientID: provider.ClientKey, + ClientSecret: provider.Secret, + RedirectURL: provider.CallbackURL, + Endpoint: oauth2.Endpoint{ + AuthURL: authURL, + TokenURL: tokenURL, + }, + Scopes: []string{ + "email", + }, + } + + defaultScopes := map[string]struct{}{ + "email": {}, + } + + for _, scope := range scopes { + if _, exists := defaultScopes[scope]; !exists { + c.Scopes = append(c.Scopes, scope) + } + } + + return c +} + +//RefreshToken refresh token is not provided by facebook +func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) { + return nil, errors.New("Refresh token is not provided by facebook") +} + +//RefreshTokenAvailable refresh token is not provided by facebook +func (p *Provider) RefreshTokenAvailable() bool { + return false +} diff --git a/vendor/github.com/markbates/goth/providers/facebook/session.go b/vendor/github.com/markbates/goth/providers/facebook/session.go new file mode 100644 index 00000000000..5cdcca443ac --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/facebook/session.go @@ -0,0 +1,59 @@ +package facebook + +import ( + "encoding/json" + "errors" + "strings" + "time" + + "github.com/markbates/goth" +) + +// Session stores data during the auth process with Facebook. +type Session struct { + AuthURL string + AccessToken string + ExpiresAt time.Time +} + +// GetAuthURL will return the URL set by calling the `BeginAuth` function on the Facebook provider. +func (s Session) GetAuthURL() (string, error) { + if s.AuthURL == "" { + return "", errors.New(goth.NoAuthUrlErrorMessage) + } + return s.AuthURL, nil +} + +// Authorize the session with Facebook and return the access token to be stored for future use. +func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) { + p := provider.(*Provider) + token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code")) + if err != nil { + return "", err + } + + if !token.Valid() { + return "", errors.New("Invalid token received from provider") + } + + s.AccessToken = token.AccessToken + s.ExpiresAt = token.Expiry + return token.AccessToken, err +} + +// Marshal the session into a string +func (s Session) Marshal() string { + b, _ := json.Marshal(s) + return string(b) +} + +func (s Session) String() string { + return s.Marshal() +} + +// UnmarshalSession will unmarshal a JSON string into a session. +func (p *Provider) UnmarshalSession(data string) (goth.Session, error) { + sess := &Session{} + err := json.NewDecoder(strings.NewReader(data)).Decode(sess) + return sess, err +} diff --git a/vendor/github.com/markbates/goth/providers/github/github.go b/vendor/github.com/markbates/goth/providers/github/github.go index 866150e63a8..b3c29b9670c 100644 --- a/vendor/github.com/markbates/goth/providers/github/github.go +++ b/vendor/github.com/markbates/goth/providers/github/github.go @@ -37,13 +37,20 @@ var ( // You should always call `github.New` to get a new Provider. Never try to create // one manually. func New(clientKey, secret, callbackURL string, scopes ...string) *Provider { + return NewCustomisedURL(clientKey, secret, callbackURL, AuthURL, TokenURL, ProfileURL, EmailURL, scopes...) +} + +// NewCustomisedURL is similar to New(...) but can be used to set custom URLs to connect to +func NewCustomisedURL(clientKey, secret, callbackURL, authURL, tokenURL, profileURL, emailURL string, scopes ...string) *Provider { p := &Provider{ - ClientKey: clientKey, - Secret: secret, - CallbackURL: callbackURL, - providerName: "github", - } - p.config = newConfig(p, scopes) + ClientKey: clientKey, + Secret: secret, + CallbackURL: callbackURL, + providerName: "github", + profileURL: profileURL, + emailURL: emailURL, + } + p.config = newConfig(p, authURL, tokenURL, scopes) return p } @@ -55,6 +62,8 @@ type Provider struct { HTTPClient *http.Client config *oauth2.Config providerName string + profileURL string + emailURL string } // Name is the name used to retrieve this provider later. @@ -96,7 +105,7 @@ func (p *Provider) FetchUser(session goth.Session) (goth.User, error) { return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName) } - response, err := p.Client().Get(ProfileURL + "?access_token=" + url.QueryEscape(sess.AccessToken)) + response, err := p.Client().Get(p.profileURL + "?access_token=" + url.QueryEscape(sess.AccessToken)) if err != nil { return user, err } @@ -163,7 +172,7 @@ func userFromReader(reader io.Reader, user *goth.User) error { } func getPrivateMail(p *Provider, sess *Session) (email string, err error) { - response, err := p.Client().Get(EmailURL + "?access_token=" + url.QueryEscape(sess.AccessToken)) + response, err := p.Client().Get(p.emailURL + "?access_token=" + url.QueryEscape(sess.AccessToken)) if err != nil { if response != nil { response.Body.Close() @@ -194,14 +203,14 @@ func getPrivateMail(p *Provider, sess *Session) (email string, err error) { return } -func newConfig(provider *Provider, scopes []string) *oauth2.Config { +func newConfig(provider *Provider, authURL, tokenURL string, scopes []string) *oauth2.Config { c := &oauth2.Config{ ClientID: provider.ClientKey, ClientSecret: provider.Secret, RedirectURL: provider.CallbackURL, Endpoint: oauth2.Endpoint{ - AuthURL: AuthURL, - TokenURL: TokenURL, + AuthURL: authURL, + TokenURL: tokenURL, }, Scopes: []string{}, } diff --git a/vendor/github.com/markbates/goth/providers/gitlab/gitlab.go b/vendor/github.com/markbates/goth/providers/gitlab/gitlab.go new file mode 100644 index 00000000000..fe188c01a99 --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/gitlab/gitlab.go @@ -0,0 +1,187 @@ +// Package gitlab implements the OAuth2 protocol for authenticating users through gitlab. +// This package can be used as a reference implementation of an OAuth2 provider for Goth. +package gitlab + +import ( + "bytes" + "encoding/json" + "io" + "io/ioutil" + "net/http" + "net/url" + "strconv" + + "github.com/markbates/goth" + "golang.org/x/oauth2" + "fmt" +) + +// These vars define the Authentication, Token, and Profile URLS for Gitlab. If +// using Gitlab CE or EE, you should change these values before calling New. +// +// Examples: +// gitlab.AuthURL = "https://gitlab.acme.com/oauth/authorize +// gitlab.TokenURL = "https://gitlab.acme.com/oauth/token +// gitlab.ProfileURL = "https://gitlab.acme.com/api/v3/user +var ( + AuthURL = "https://gitlab.com/oauth/authorize" + TokenURL = "https://gitlab.com/oauth/token" + ProfileURL = "https://gitlab.com/api/v3/user" +) + +// Provider is the implementation of `goth.Provider` for accessing Gitlab. +type Provider struct { + ClientKey string + Secret string + CallbackURL string + HTTPClient *http.Client + config *oauth2.Config + providerName string + authURL string + tokenURL string + profileURL string +} + +// New creates a new Gitlab provider and sets up important connection details. +// You should always call `gitlab.New` to get a new provider. Never try to +// create one manually. +func New(clientKey, secret, callbackURL string, scopes ...string) *Provider { + return NewCustomisedURL(clientKey, secret, callbackURL, AuthURL, TokenURL, ProfileURL, scopes...) +} + +// NewCustomisedURL is similar to New(...) but can be used to set custom URLs to connect to +func NewCustomisedURL(clientKey, secret, callbackURL, authURL, tokenURL, profileURL string, scopes ...string) *Provider { + p := &Provider{ + ClientKey: clientKey, + Secret: secret, + CallbackURL: callbackURL, + providerName: "gitlab", + profileURL: profileURL, + } + p.config = newConfig(p, authURL, tokenURL, scopes) + return p +} + +// Name is the name used to retrieve this provider later. +func (p *Provider) Name() string { + return p.providerName +} + +// SetName is to update the name of the provider (needed in case of multiple providers of 1 type) +func (p *Provider) SetName(name string) { + p.providerName = name +} + +func (p *Provider) Client() *http.Client { + return goth.HTTPClientWithFallBack(p.HTTPClient) +} + +// Debug is a no-op for the gitlab package. +func (p *Provider) Debug(debug bool) {} + +// BeginAuth asks Gitlab for an authentication end-point. +func (p *Provider) BeginAuth(state string) (goth.Session, error) { + return &Session{ + AuthURL: p.config.AuthCodeURL(state), + }, nil +} + +// FetchUser will go to Gitlab and access basic information about the user. +func (p *Provider) FetchUser(session goth.Session) (goth.User, error) { + sess := session.(*Session) + user := goth.User{ + AccessToken: sess.AccessToken, + Provider: p.Name(), + RefreshToken: sess.RefreshToken, + ExpiresAt: sess.ExpiresAt, + } + + if user.AccessToken == "" { + // data is not yet retrieved since accessToken is still empty + return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName) + } + + response, err := p.Client().Get(p.profileURL + "?access_token=" + url.QueryEscape(sess.AccessToken)) + if err != nil { + if response != nil { + response.Body.Close() + } + return user, err + } + + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, response.StatusCode) + } + + bits, err := ioutil.ReadAll(response.Body) + if err != nil { + return user, err + } + + err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData) + if err != nil { + return user, err + } + + err = userFromReader(bytes.NewReader(bits), &user) + + return user, err +} + +func newConfig(provider *Provider, authURL, tokenURL string, scopes []string) *oauth2.Config { + c := &oauth2.Config{ + ClientID: provider.ClientKey, + ClientSecret: provider.Secret, + RedirectURL: provider.CallbackURL, + Endpoint: oauth2.Endpoint{ + AuthURL: authURL, + TokenURL: tokenURL, + }, + Scopes: []string{}, + } + + if len(scopes) > 0 { + for _, scope := range scopes { + c.Scopes = append(c.Scopes, scope) + } + } + return c +} + +func userFromReader(r io.Reader, user *goth.User) error { + u := struct { + Name string `json:"name"` + Email string `json:"email"` + NickName string `json:"username"` + ID int `json:"id"` + AvatarURL string `json:"avatar_url"` + }{} + err := json.NewDecoder(r).Decode(&u) + if err != nil { + return err + } + user.Email = u.Email + user.Name = u.Name + user.NickName = u.NickName + user.UserID = strconv.Itoa(u.ID) + user.AvatarURL = u.AvatarURL + return nil +} + +//RefreshTokenAvailable refresh token is provided by auth provider or not +func (p *Provider) RefreshTokenAvailable() bool { + return true +} + +//RefreshToken get new access token based on the refresh token +func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) { + token := &oauth2.Token{RefreshToken: refreshToken} + ts := p.config.TokenSource(goth.ContextForClient(p.Client()), token) + newToken, err := ts.Token() + if err != nil { + return nil, err + } + return newToken, err +} diff --git a/vendor/github.com/markbates/goth/providers/gitlab/session.go b/vendor/github.com/markbates/goth/providers/gitlab/session.go new file mode 100644 index 00000000000..a2f90647c27 --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/gitlab/session.go @@ -0,0 +1,63 @@ +package gitlab + +import ( + "encoding/json" + "errors" + "strings" + "time" + + "github.com/markbates/goth" +) + +// Session stores data during the auth process with Gitlab. +type Session struct { + AuthURL string + AccessToken string + RefreshToken string + ExpiresAt time.Time +} + +var _ goth.Session = &Session{} + +// GetAuthURL will return the URL set by calling the `BeginAuth` function on the Gitlab provider. +func (s Session) GetAuthURL() (string, error) { + if s.AuthURL == "" { + return "", errors.New(goth.NoAuthUrlErrorMessage) + } + return s.AuthURL, nil +} + +// Authorize the session with Gitlab and return the access token to be stored for future use. +func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) { + p := provider.(*Provider) + token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code")) + if err != nil { + return "", err + } + + if !token.Valid() { + return "", errors.New("Invalid token received from provider") + } + + s.AccessToken = token.AccessToken + s.RefreshToken = token.RefreshToken + s.ExpiresAt = token.Expiry + return token.AccessToken, err +} + +// Marshal the session into a string +func (s Session) Marshal() string { + b, _ := json.Marshal(s) + return string(b) +} + +func (s Session) String() string { + return s.Marshal() +} + +// UnmarshalSession wil unmarshal a JSON string into a session. +func (p *Provider) UnmarshalSession(data string) (goth.Session, error) { + s := &Session{} + err := json.NewDecoder(strings.NewReader(data)).Decode(s) + return s, err +} diff --git a/vendor/github.com/markbates/goth/providers/gplus/gplus.go b/vendor/github.com/markbates/goth/providers/gplus/gplus.go new file mode 100644 index 00000000000..06655c2f7f6 --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/gplus/gplus.go @@ -0,0 +1,195 @@ +// Package gplus implements the OAuth2 protocol for authenticating users through Google+. +// This package can be used as a reference implementation of an OAuth2 provider for Goth. +package gplus + +import ( + "bytes" + "encoding/json" + "io" + "io/ioutil" + "net/http" + "net/url" + "strings" + + "github.com/markbates/goth" + "golang.org/x/oauth2" + "fmt" +) + +const ( + authURL string = "https://accounts.google.com/o/oauth2/auth?access_type=offline" + tokenURL string = "https://accounts.google.com/o/oauth2/token" + endpointProfile string = "https://www.googleapis.com/oauth2/v2/userinfo" +) + +// New creates a new Google+ provider, and sets up important connection details. +// You should always call `gplus.New` to get a new Provider. Never try to create +// one manually. +func New(clientKey, secret, callbackURL string, scopes ...string) *Provider { + p := &Provider{ + ClientKey: clientKey, + Secret: secret, + CallbackURL: callbackURL, + providerName: "gplus", + } + p.config = newConfig(p, scopes) + return p +} + +// Provider is the implementation of `goth.Provider` for accessing Google+. +type Provider struct { + ClientKey string + Secret string + CallbackURL string + HTTPClient *http.Client + config *oauth2.Config + prompt oauth2.AuthCodeOption + providerName string +} + +// Name is the name used to retrieve this provider later. +func (p *Provider) Name() string { + return p.providerName +} + +// SetName is to update the name of the provider (needed in case of multiple providers of 1 type) +func (p *Provider) SetName(name string) { + p.providerName = name +} + +func (p *Provider) Client() *http.Client { + return goth.HTTPClientWithFallBack(p.HTTPClient) +} + +// Debug is a no-op for the gplus package. +func (p *Provider) Debug(debug bool) {} + +// BeginAuth asks Google+ for an authentication end-point. +func (p *Provider) BeginAuth(state string) (goth.Session, error) { + var opts []oauth2.AuthCodeOption + if p.prompt != nil { + opts = append(opts, p.prompt) + } + url := p.config.AuthCodeURL(state, opts...) + session := &Session{ + AuthURL: url, + } + return session, nil +} + +// FetchUser will go to Google+ and access basic information about the user. +func (p *Provider) FetchUser(session goth.Session) (goth.User, error) { + sess := session.(*Session) + user := goth.User{ + AccessToken: sess.AccessToken, + Provider: p.Name(), + RefreshToken: sess.RefreshToken, + ExpiresAt: sess.ExpiresAt, + } + + if user.AccessToken == "" { + // data is not yet retrieved since accessToken is still empty + return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName) + } + + response, err := p.Client().Get(endpointProfile + "?access_token=" + url.QueryEscape(sess.AccessToken)) + if err != nil { + return user, err + } + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, response.StatusCode) + } + + bits, err := ioutil.ReadAll(response.Body) + if err != nil { + return user, err + } + + err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData) + if err != nil { + return user, err + } + + err = userFromReader(bytes.NewReader(bits), &user) + return user, err +} + +func userFromReader(reader io.Reader, user *goth.User) error { + u := struct { + ID string `json:"id"` + Email string `json:"email"` + Name string `json:"name"` + FirstName string `json:"given_name"` + LastName string `json:"family_name"` + Link string `json:"link"` + Picture string `json:"picture"` + }{} + + err := json.NewDecoder(reader).Decode(&u) + if err != nil { + return err + } + + user.Name = u.Name + user.FirstName = u.FirstName + user.LastName = u.LastName + user.NickName = u.Name + user.Email = u.Email + //user.Description = u.Bio + user.AvatarURL = u.Picture + user.UserID = u.ID + //user.Location = u.Location.Name + + return err +} + +func newConfig(provider *Provider, scopes []string) *oauth2.Config { + c := &oauth2.Config{ + ClientID: provider.ClientKey, + ClientSecret: provider.Secret, + RedirectURL: provider.CallbackURL, + Endpoint: oauth2.Endpoint{ + AuthURL: authURL, + TokenURL: tokenURL, + }, + Scopes: []string{}, + } + + if len(scopes) > 0 { + for _, scope := range scopes { + c.Scopes = append(c.Scopes, scope) + } + } else { + c.Scopes = []string{"profile", "email", "openid"} + } + return c +} + +//RefreshTokenAvailable refresh token is provided by auth provider or not +func (p *Provider) RefreshTokenAvailable() bool { + return true +} + +//RefreshToken get new access token based on the refresh token +func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) { + token := &oauth2.Token{RefreshToken: refreshToken} + ts := p.config.TokenSource(goth.ContextForClient(p.Client()), token) + newToken, err := ts.Token() + if err != nil { + return nil, err + } + return newToken, err +} + +// SetPrompt sets the prompt values for the GPlus OAuth call. Use this to +// force users to choose and account every time by passing "select_account", +// for example. +// See https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters +func (p *Provider) SetPrompt(prompt ...string) { + if len(prompt) == 0 { + return + } + p.prompt = oauth2.SetAuthURLParam("prompt", strings.Join(prompt, " ")) +} diff --git a/vendor/github.com/markbates/goth/providers/gplus/session.go b/vendor/github.com/markbates/goth/providers/gplus/session.go new file mode 100644 index 00000000000..9710031f4d9 --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/gplus/session.go @@ -0,0 +1,61 @@ +package gplus + +import ( + "encoding/json" + "errors" + "strings" + "time" + + "github.com/markbates/goth" +) + +// Session stores data during the auth process with Google+. +type Session struct { + AuthURL string + AccessToken string + RefreshToken string + ExpiresAt time.Time +} + +// GetAuthURL will return the URL set by calling the `BeginAuth` function on the Google+ provider. +func (s Session) GetAuthURL() (string, error) { + if s.AuthURL == "" { + return "", errors.New(goth.NoAuthUrlErrorMessage) + } + return s.AuthURL, nil +} + +// Authorize the session with Google+ and return the access token to be stored for future use. +func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) { + p := provider.(*Provider) + token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code")) + if err != nil { + return "", err + } + + if !token.Valid() { + return "", errors.New("Invalid token received from provider") + } + + s.AccessToken = token.AccessToken + s.RefreshToken = token.RefreshToken + s.ExpiresAt = token.Expiry + return token.AccessToken, err +} + +// Marshal the session into a string +func (s Session) Marshal() string { + b, _ := json.Marshal(s) + return string(b) +} + +func (s Session) String() string { + return s.Marshal() +} + +// UnmarshalSession will unmarshal a JSON string into a session. +func (p *Provider) UnmarshalSession(data string) (goth.Session, error) { + sess := &Session{} + err := json.NewDecoder(strings.NewReader(data)).Decode(sess) + return sess, err +} diff --git a/vendor/github.com/markbates/goth/providers/openidConnect/openidConnect.go b/vendor/github.com/markbates/goth/providers/openidConnect/openidConnect.go new file mode 100644 index 00000000000..7ffd11c6079 --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/openidConnect/openidConnect.go @@ -0,0 +1,384 @@ +package openidConnect + +import ( + "net/http" + "strings" + "fmt" + "encoding/json" + "encoding/base64" + "io/ioutil" + "errors" + "golang.org/x/oauth2" + "github.com/markbates/goth" + "time" + "bytes" +) + +const ( + // Standard Claims http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims + // fixed, cannot be changed + subjectClaim = "sub" + expiryClaim = "exp" + audienceClaim = "aud" + issuerClaim = "iss" + + PreferredUsernameClaim = "preferred_username" + EmailClaim = "email" + NameClaim = "name" + NicknameClaim = "nickname" + PictureClaim = "picture" + GivenNameClaim = "given_name" + FamilyNameClaim = "family_name" + AddressClaim = "address" + + // Unused but available to set in Provider claims + MiddleNameClaim = "middle_name" + ProfileClaim = "profile" + WebsiteClaim = "website" + EmailVerifiedClaim = "email_verified" + GenderClaim = "gender" + BirthdateClaim = "birthdate" + ZoneinfoClaim = "zoneinfo" + LocaleClaim = "locale" + PhoneNumberClaim = "phone_number" + PhoneNumberVerifiedClaim = "phone_number_verified" + UpdatedAtClaim = "updated_at" + + clockSkew = 10 * time.Second +) + +// Provider is the implementation of `goth.Provider` for accessing OpenID Connect provider +type Provider struct { + ClientKey string + Secret string + CallbackURL string + HTTPClient *http.Client + config *oauth2.Config + openIDConfig *OpenIDConfig + providerName string + + UserIdClaims []string + NameClaims []string + NickNameClaims []string + EmailClaims []string + AvatarURLClaims []string + FirstNameClaims []string + LastNameClaims []string + LocationClaims []string + + SkipUserInfoRequest bool +} + +type OpenIDConfig struct { + AuthEndpoint string `json:"authorization_endpoint"` + TokenEndpoint string `json:"token_endpoint"` + UserInfoEndpoint string `json:"userinfo_endpoint"` + Issuer string `json:"issuer"` +} + +// New creates a new OpenID Connect provider, and sets up important connection details. +// You should always call `openidConnect.New` to get a new Provider. Never try to create +// one manually. +// New returns an implementation of an OpenID Connect Authorization Code Flow +// See http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth +// ID Token decryption is not (yet) supported +// UserInfo decryption is not (yet) supported +func New(clientKey, secret, callbackURL, openIDAutoDiscoveryURL string, scopes ...string) (*Provider, error) { + p := &Provider{ + ClientKey: clientKey, + Secret: secret, + CallbackURL: callbackURL, + + UserIdClaims: []string{subjectClaim}, + NameClaims: []string{NameClaim}, + NickNameClaims: []string{NicknameClaim, PreferredUsernameClaim}, + EmailClaims: []string{EmailClaim}, + AvatarURLClaims:[]string{PictureClaim}, + FirstNameClaims:[]string{GivenNameClaim}, + LastNameClaims: []string{FamilyNameClaim}, + LocationClaims: []string{AddressClaim}, + + providerName: "openid-connect", + } + + openIDConfig, err := getOpenIDConfig(p, openIDAutoDiscoveryURL) + if err != nil { + return nil, err + } + p.openIDConfig = openIDConfig + + p.config = newConfig(p, scopes, openIDConfig) + return p, nil +} + +// Name is the name used to retrieve this provider later. +func (p *Provider) Name() string { + return p.providerName +} + +// SetName is to update the name of the provider (needed in case of multiple providers of 1 type) +func (p *Provider) SetName(name string) { + p.providerName = name +} + +func (p *Provider) Client() *http.Client { + return goth.HTTPClientWithFallBack(p.HTTPClient) +} + +// Debug is a no-op for the openidConnect package. +func (p *Provider) Debug(debug bool) {} + +// BeginAuth asks the OpenID Connect provider for an authentication end-point. +func (p *Provider) BeginAuth(state string) (goth.Session, error) { + url := p.config.AuthCodeURL(state) + session := &Session{ + AuthURL: url, + } + return session, nil +} + +// FetchUser will use the the id_token and access requested information about the user. +func (p *Provider) FetchUser(session goth.Session) (goth.User, error) { + sess := session.(*Session) + + expiresAt := sess.ExpiresAt + + if sess.IDToken == "" { + return goth.User{}, fmt.Errorf("%s cannot get user information without id_token", p.providerName) + } + + // decode returned id token to get expiry + claims, err := decodeJWT(sess.IDToken) + + if err != nil { + return goth.User{}, fmt.Errorf("oauth2: error decoding JWT token: %v", err) + } + + expiry, err := p.validateClaims(claims) + if err != nil { + return goth.User{}, fmt.Errorf("oauth2: error validating JWT token: %v", err) + } + + if expiry.Before(expiresAt) { + expiresAt = expiry + } + + if err := p.getUserInfo(sess.AccessToken, claims); err != nil { + return goth.User{}, err + } + + user := goth.User{ + AccessToken: sess.AccessToken, + Provider: p.Name(), + RefreshToken: sess.RefreshToken, + ExpiresAt: expiresAt, + RawData: claims, + } + + p.userFromClaims(claims, &user) + return user, err +} + +//RefreshTokenAvailable refresh token is provided by auth provider or not +func (p *Provider) RefreshTokenAvailable() bool { + return true +} + +//RefreshToken get new access token based on the refresh token +func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) { + token := &oauth2.Token{RefreshToken: refreshToken} + ts := p.config.TokenSource(oauth2.NoContext, token) + newToken, err := ts.Token() + if err != nil { + return nil, err + } + return newToken, err +} + +// validate according to standard, returns expiry +// http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation +func (p *Provider) validateClaims(claims map[string]interface{}) (time.Time, error) { + audience := getClaimValue(claims, []string{audienceClaim}) + if audience != p.ClientKey { + return time.Time{}, errors.New("audience in token does not match client key") + } + + issuer := getClaimValue(claims, []string{issuerClaim}) + if issuer != p.openIDConfig.Issuer { + return time.Time{}, errors.New("issuer in token does not match issuer in OpenIDConfig discovery") + } + + // expiry is required for JWT, not for UserInfoResponse + // is actually a int64, so force it in to that type + expiryClaim := int64(claims[expiryClaim].(float64)) + expiry := time.Unix(expiryClaim, 0) + if expiry.Add(clockSkew).Before(time.Now()) { + return time.Time{}, errors.New("user info JWT token is expired") + } + return expiry, nil +} + +func (p *Provider) userFromClaims(claims map[string]interface{}, user *goth.User) { + // required + user.UserID = getClaimValue(claims, p.UserIdClaims) + + user.Name = getClaimValue(claims, p.NameClaims) + user.NickName = getClaimValue(claims, p.NickNameClaims) + user.Email = getClaimValue(claims, p.EmailClaims) + user.AvatarURL = getClaimValue(claims, p.AvatarURLClaims) + user.FirstName = getClaimValue(claims, p.FirstNameClaims) + user.LastName = getClaimValue(claims, p.LastNameClaims) + user.Location = getClaimValue(claims, p.LocationClaims) +} + +func (p *Provider) getUserInfo(accessToken string, claims map[string]interface{}) error { + // skip if there is no UserInfoEndpoint or is explicitly disabled + if p.openIDConfig.UserInfoEndpoint == "" || p.SkipUserInfoRequest { + return nil + } + + userInfoClaims, err := p.fetchUserInfo(p.openIDConfig.UserInfoEndpoint, accessToken) + if err != nil { + return err + } + + // The sub (subject) Claim MUST always be returned in the UserInfo Response. + // http://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse + userInfoSubject := getClaimValue(userInfoClaims, []string{subjectClaim}) + if userInfoSubject == "" { + return fmt.Errorf("userinfo response did not contain a 'sub' claim: %#v", userInfoClaims) + } + + // The sub Claim in the UserInfo Response MUST be verified to exactly match the sub Claim in the ID Token; + // if they do not match, the UserInfo Response values MUST NOT be used. + // http://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse + subject := getClaimValue(claims, []string{subjectClaim}) + if userInfoSubject != subject { + return fmt.Errorf("userinfo 'sub' claim (%s) did not match id_token 'sub' claim (%s)", userInfoSubject, subject) + } + + // Merge in userinfo claims in case id_token claims contained some that userinfo did not + for k, v := range userInfoClaims { + claims[k] = v + } + + return nil +} + +// fetch and decode JSON from the given UserInfo URL +func (p *Provider) fetchUserInfo(url, accessToken string) (map[string]interface{}, error) { + req, _ := http.NewRequest("GET", url, nil) + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken)) + + resp, err := p.Client().Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("Non-200 response from UserInfo: %d, WWW-Authenticate=%s", resp.StatusCode, resp.Header.Get("WWW-Authenticate")) + } + + // The UserInfo Claims MUST be returned as the members of a JSON object + // http://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse + data, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + return unMarshal(data) +} + +func getOpenIDConfig(p *Provider, openIDAutoDiscoveryURL string) (*OpenIDConfig, error) { + res, err := p.Client().Get(openIDAutoDiscoveryURL) + if err != nil { + return nil, err + } + defer res.Body.Close() + + body, err := ioutil.ReadAll(res.Body) + if err != nil { + return nil, err + } + + openIDConfig := &OpenIDConfig{} + err = json.Unmarshal(body, openIDConfig) + if err != nil { + return nil, err + } + + return openIDConfig, nil +} + +func newConfig(provider *Provider, scopes []string, openIDConfig *OpenIDConfig) *oauth2.Config { + c := &oauth2.Config{ + ClientID: provider.ClientKey, + ClientSecret: provider.Secret, + RedirectURL: provider.CallbackURL, + Endpoint: oauth2.Endpoint{ + AuthURL: openIDConfig.AuthEndpoint, + TokenURL: openIDConfig.TokenEndpoint, + }, + Scopes: []string{}, + } + + if len(scopes) > 0 { + foundOpenIDScope := false + + for _, scope := range scopes { + if scope == "openid" { + foundOpenIDScope = true + } + c.Scopes = append(c.Scopes, scope) + } + + if !foundOpenIDScope { + c.Scopes = append(c.Scopes, "openid") + } + } else { + c.Scopes = []string{"openid"} + } + + return c +} + +func getClaimValue(data map[string]interface{}, claims []string) string { + for _, claim := range claims { + if value, ok := data[claim]; ok { + if stringValue, ok := value.(string); ok && len(stringValue) > 0 { + return stringValue + } + } + } + + return "" +} + +// decodeJWT decodes a JSON Web Token into a simple map +// http://openid.net/specs/draft-jones-json-web-token-07.html +func decodeJWT(jwt string) (map[string]interface{}, error) { + jwtParts := strings.Split(jwt, ".") + if len(jwtParts) != 3 { + return nil, errors.New("jws: invalid token received, not all parts available") + } + + // Re-pad, if needed + encodedPayload := jwtParts[1] + if l := len(encodedPayload) % 4; l != 0 { + encodedPayload += strings.Repeat("=", 4-l) + } + + decodedPayload, err := base64.StdEncoding.DecodeString(encodedPayload) + if err != nil { + return nil, err + } + + return unMarshal(decodedPayload) +} + +func unMarshal(payload []byte) (map[string]interface{}, error) { + data := make(map[string]interface{}) + + return data, json.NewDecoder(bytes.NewBuffer(payload)).Decode(&data) +} diff --git a/vendor/github.com/markbates/goth/providers/openidConnect/session.go b/vendor/github.com/markbates/goth/providers/openidConnect/session.go new file mode 100644 index 00000000000..a34584fdef1 --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/openidConnect/session.go @@ -0,0 +1,63 @@ +package openidConnect + +import ( + "errors" + "github.com/markbates/goth" + "encoding/json" + "strings" + "time" + "golang.org/x/oauth2" +) + +// Session stores data during the auth process with the OpenID Connect provider. +type Session struct { + AuthURL string + AccessToken string + RefreshToken string + ExpiresAt time.Time + IDToken string +} + +// GetAuthURL will return the URL set by calling the `BeginAuth` function on the OpenID Connect provider. +func (s Session) GetAuthURL() (string, error) { + if s.AuthURL == "" { + return "", errors.New("an AuthURL has not be set") + } + return s.AuthURL, nil +} + +// Authorize the session with the OpenID Connect provider and return the access token to be stored for future use. +func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) { + p := provider.(*Provider) + token, err := p.config.Exchange(oauth2.NoContext, params.Get("code")) + if err != nil { + return "", err + } + + if !token.Valid() { + return "", errors.New("Invalid token received from provider") + } + + s.AccessToken = token.AccessToken + s.RefreshToken = token.RefreshToken + s.ExpiresAt = token.Expiry + s.IDToken = token.Extra("id_token").(string) + return token.AccessToken, err +} + +// Marshal the session into a string +func (s Session) Marshal() string { + b, _ := json.Marshal(s) + return string(b) +} + +func (s Session) String() string { + return s.Marshal() +} + +// UnmarshalSession will unmarshal a JSON string into a session. +func (p *Provider) UnmarshalSession(data string) (goth.Session, error) { + sess := &Session{} + err := json.NewDecoder(strings.NewReader(data)).Decode(sess) + return sess, err +} diff --git a/vendor/github.com/markbates/goth/providers/twitter/session.go b/vendor/github.com/markbates/goth/providers/twitter/session.go new file mode 100644 index 00000000000..049928ff262 --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/twitter/session.go @@ -0,0 +1,54 @@ +package twitter + +import ( + "encoding/json" + "errors" + "strings" + + "github.com/markbates/goth" + "github.com/mrjones/oauth" +) + +// Session stores data during the auth process with Twitter. +type Session struct { + AuthURL string + AccessToken *oauth.AccessToken + RequestToken *oauth.RequestToken +} + +// GetAuthURL will return the URL set by calling the `BeginAuth` function on the Twitter provider. +func (s Session) GetAuthURL() (string, error) { + if s.AuthURL == "" { + return "", errors.New(goth.NoAuthUrlErrorMessage) + } + return s.AuthURL, nil +} + +// Authorize the session with Twitter and return the access token to be stored for future use. +func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) { + p := provider.(*Provider) + accessToken, err := p.consumer.AuthorizeToken(s.RequestToken, params.Get("oauth_verifier")) + if err != nil { + return "", err + } + + s.AccessToken = accessToken + return accessToken.Token, err +} + +// Marshal the session into a string +func (s Session) Marshal() string { + b, _ := json.Marshal(s) + return string(b) +} + +func (s Session) String() string { + return s.Marshal() +} + +// UnmarshalSession will unmarshal a JSON string into a session. +func (p *Provider) UnmarshalSession(data string) (goth.Session, error) { + sess := &Session{} + err := json.NewDecoder(strings.NewReader(data)).Decode(sess) + return sess, err +} diff --git a/vendor/github.com/markbates/goth/providers/twitter/twitter.go b/vendor/github.com/markbates/goth/providers/twitter/twitter.go new file mode 100644 index 00000000000..3703f21974b --- /dev/null +++ b/vendor/github.com/markbates/goth/providers/twitter/twitter.go @@ -0,0 +1,160 @@ +// Package twitter implements the OAuth protocol for authenticating users through Twitter. +// This package can be used as a reference implementation of an OAuth provider for Goth. +package twitter + +import ( + "bytes" + "encoding/json" + "errors" + "io/ioutil" + "net/http" + + "github.com/markbates/goth" + "github.com/mrjones/oauth" + "golang.org/x/oauth2" + "fmt" +) + +var ( + requestURL = "https://api.twitter.com/oauth/request_token" + authorizeURL = "https://api.twitter.com/oauth/authorize" + authenticateURL = "https://api.twitter.com/oauth/authenticate" + tokenURL = "https://api.twitter.com/oauth/access_token" + endpointProfile = "https://api.twitter.com/1.1/account/verify_credentials.json" +) + +// New creates a new Twitter provider, and sets up important connection details. +// You should always call `twitter.New` to get a new Provider. Never try to create +// one manually. +// +// If you'd like to use authenticate instead of authorize, use NewAuthenticate instead. +func New(clientKey, secret, callbackURL string) *Provider { + p := &Provider{ + ClientKey: clientKey, + Secret: secret, + CallbackURL: callbackURL, + providerName: "twitter", + } + p.consumer = newConsumer(p, authorizeURL) + return p +} + +// NewAuthenticate is the almost same as New. +// NewAuthenticate uses the authenticate URL instead of the authorize URL. +func NewAuthenticate(clientKey, secret, callbackURL string) *Provider { + p := &Provider{ + ClientKey: clientKey, + Secret: secret, + CallbackURL: callbackURL, + providerName: "twitter", + } + p.consumer = newConsumer(p, authenticateURL) + return p +} + +// Provider is the implementation of `goth.Provider` for accessing Twitter. +type Provider struct { + ClientKey string + Secret string + CallbackURL string + HTTPClient *http.Client + debug bool + consumer *oauth.Consumer + providerName string +} + +// Name is the name used to retrieve this provider later. +func (p *Provider) Name() string { + return p.providerName +} + +// SetName is to update the name of the provider (needed in case of multiple providers of 1 type) +func (p *Provider) SetName(name string) { + p.providerName = name +} + +func (p *Provider) Client() *http.Client { + return goth.HTTPClientWithFallBack(p.HTTPClient) +} + +// Debug sets the logging of the OAuth client to verbose. +func (p *Provider) Debug(debug bool) { + p.debug = debug +} + +// BeginAuth asks Twitter for an authentication end-point and a request token for a session. +// Twitter does not support the "state" variable. +func (p *Provider) BeginAuth(state string) (goth.Session, error) { + requestToken, url, err := p.consumer.GetRequestTokenAndUrl(p.CallbackURL) + session := &Session{ + AuthURL: url, + RequestToken: requestToken, + } + return session, err +} + +// FetchUser will go to Twitter and access basic information about the user. +func (p *Provider) FetchUser(session goth.Session) (goth.User, error) { + sess := session.(*Session) + user := goth.User{ + Provider: p.Name(), + } + + if sess.AccessToken == nil { + // data is not yet retrieved since accessToken is still empty + return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName) + } + + response, err := p.consumer.Get( + endpointProfile, + map[string]string{"include_entities": "false", "skip_status": "true"}, + sess.AccessToken) + if err != nil { + return user, err + } + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, response.StatusCode) + } + + bits, err := ioutil.ReadAll(response.Body) + err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData) + if err != nil { + return user, err + } + + user.Name = user.RawData["name"].(string) + user.NickName = user.RawData["screen_name"].(string) + user.Description = user.RawData["description"].(string) + user.AvatarURL = user.RawData["profile_image_url"].(string) + user.UserID = user.RawData["id_str"].(string) + user.Location = user.RawData["location"].(string) + user.AccessToken = sess.AccessToken.Token + user.AccessTokenSecret = sess.AccessToken.Secret + return user, err +} + +func newConsumer(provider *Provider, authURL string) *oauth.Consumer { + c := oauth.NewConsumer( + provider.ClientKey, + provider.Secret, + oauth.ServiceProvider{ + RequestTokenUrl: requestURL, + AuthorizeTokenUrl: authURL, + AccessTokenUrl: tokenURL, + }) + + c.Debug(provider.debug) + return c +} + +//RefreshToken refresh token is not provided by twitter +func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) { + return nil, errors.New("Refresh token is not provided by twitter") +} + +//RefreshTokenAvailable refresh token is not provided by twitter +func (p *Provider) RefreshTokenAvailable() bool { + return false +} diff --git a/vendor/github.com/mrjones/oauth/MIT-LICENSE.txt b/vendor/github.com/mrjones/oauth/MIT-LICENSE.txt new file mode 100644 index 00000000000..6c9461e6c67 --- /dev/null +++ b/vendor/github.com/mrjones/oauth/MIT-LICENSE.txt @@ -0,0 +1,7 @@ +Copyright (C) 2013 Matthew R. Jones + +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. diff --git a/vendor/github.com/mrjones/oauth/README.md b/vendor/github.com/mrjones/oauth/README.md new file mode 100644 index 00000000000..c0f7eb5479b --- /dev/null +++ b/vendor/github.com/mrjones/oauth/README.md @@ -0,0 +1,51 @@ +OAuth 1.0 Library for [Go](http://golang.org) +======================== + +[![GoDoc](http://godoc.org/github.com/mrjones/oauth?status.png)](http://godoc.org/github.com/mrjones/oauth) + +[![CircleCI](https://circleci.com/gh/mrjones/oauth/tree/master.svg?style=svg)](https://circleci.com/gh/mrjones/oauth/tree/master) + +(If you need an OAuth 2.0 library, check out: https://godoc.org/golang.org/x/oauth2) + +Developing your own apps, with this library +------------------------------------------- + +* First, install the library + + go get github.com/mrjones/oauth + +* Then, check out the comments in oauth.go + +* Or, have a look at the examples: + + * Netflix + + go run examples/netflix/netflix.go --consumerkey [key] --consumersecret [secret] --appname [appname] + + * Twitter + + Command line: + + go run examples/twitter/twitter.go --consumerkey [key] --consumersecret [secret] + + Or, in the browser (using an HTTP server): + + go run examples/twitterserver/twitterserver.go --consumerkey [key] --consumersecret [secret] --port 8888 + + * The Google Latitude example is broken, now that Google uses OAuth 2.0 + +Contributing to this library +---------------------------- + +* Please install the pre-commit hook, which will run tests, and go-fmt before committing. + + ln -s $PWD/pre-commit.sh .git/hooks/pre-commit + +* Running tests and building is as you'd expect: + + go test *.go + go build *.go + + + + diff --git a/vendor/github.com/mrjones/oauth/oauth.go b/vendor/github.com/mrjones/oauth/oauth.go new file mode 100644 index 00000000000..95eee64abd6 --- /dev/null +++ b/vendor/github.com/mrjones/oauth/oauth.go @@ -0,0 +1,1412 @@ +// OAuth 1.0 consumer implementation. +// See http://www.oauth.net and RFC 5849 +// +// There are typically three parties involved in an OAuth exchange: +// (1) The "Service Provider" (e.g. Google, Twitter, NetFlix) who operates the +// service where the data resides. +// (2) The "End User" who owns that data, and wants to grant access to a third-party. +// (3) That third-party who wants access to the data (after first being authorized by +// the user). This third-party is referred to as the "Consumer" in OAuth +// terminology. +// +// This library is designed to help implement the third-party consumer by handling the +// low-level authentication tasks, and allowing for authenticated requests to the +// service provider on behalf of the user. +// +// Caveats: +// - Currently only supports HMAC and RSA signatures. +// - Currently only supports SHA1 and SHA256 hashes. +// - Currently only supports OAuth 1.0 +// +// Overview of how to use this library: +// (1) First create a new Consumer instance with the NewConsumer function +// (2) Get a RequestToken, and "authorization url" from GetRequestTokenAndUrl() +// (3) Save the RequestToken, you will need it again in step 6. +// (4) Redirect the user to the "authorization url" from step 2, where they will +// authorize your access to the service provider. +// (5) Wait. You will be called back on the CallbackUrl that you provide, and you +// will recieve a "verification code". +// (6) Call AuthorizeToken() with the RequestToken from step 2 and the +// "verification code" from step 5. +// (7) You will get back an AccessToken. Save this for as long as you need access +// to the user's data, and treat it like a password; it is a secret. +// (8) You can now throw away the RequestToken from step 2, it is no longer +// necessary. +// (9) Call "MakeHttpClient" using the AccessToken from step 7 to get an +// HTTP client which can access protected resources. +package oauth + +import ( + "bytes" + "crypto" + "crypto/hmac" + cryptoRand "crypto/rand" + "crypto/rsa" + "encoding/base64" + "errors" + "fmt" + "io" + "io/ioutil" + "math/rand" + "mime/multipart" + "net/http" + "net/url" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +const ( + OAUTH_VERSION = "1.0" + SIGNATURE_METHOD_HMAC = "HMAC-" + SIGNATURE_METHOD_RSA = "RSA-" + + HTTP_AUTH_HEADER = "Authorization" + OAUTH_HEADER = "OAuth " + BODY_HASH_PARAM = "oauth_body_hash" + CALLBACK_PARAM = "oauth_callback" + CONSUMER_KEY_PARAM = "oauth_consumer_key" + NONCE_PARAM = "oauth_nonce" + SESSION_HANDLE_PARAM = "oauth_session_handle" + SIGNATURE_METHOD_PARAM = "oauth_signature_method" + SIGNATURE_PARAM = "oauth_signature" + TIMESTAMP_PARAM = "oauth_timestamp" + TOKEN_PARAM = "oauth_token" + TOKEN_SECRET_PARAM = "oauth_token_secret" + VERIFIER_PARAM = "oauth_verifier" + VERSION_PARAM = "oauth_version" +) + +var HASH_METHOD_MAP = map[crypto.Hash]string{ + crypto.SHA1: "SHA1", + crypto.SHA256: "SHA256", +} + +// TODO(mrjones) Do we definitely want separate "Request" and "Access" token classes? +// They're identical structurally, but used for different purposes. +type RequestToken struct { + Token string + Secret string +} + +type AccessToken struct { + Token string + Secret string + AdditionalData map[string]string +} + +type DataLocation int + +const ( + LOC_BODY DataLocation = iota + 1 + LOC_URL + LOC_MULTIPART + LOC_JSON + LOC_XML +) + +// Information about how to contact the service provider (see #1 above). +// You usually find all of these URLs by reading the documentation for the service +// that you're trying to connect to. +// Some common examples are: +// (1) Google, standard APIs: +// http://code.google.com/apis/accounts/docs/OAuth_ref.html +// - RequestTokenUrl: https://www.google.com/accounts/OAuthGetRequestToken +// - AuthorizeTokenUrl: https://www.google.com/accounts/OAuthAuthorizeToken +// - AccessTokenUrl: https://www.google.com/accounts/OAuthGetAccessToken +// Note: Some Google APIs (for example, Google Latitude) use different values for +// one or more of those URLs. +// (2) Twitter API: +// http://dev.twitter.com/pages/auth +// - RequestTokenUrl: http://api.twitter.com/oauth/request_token +// - AuthorizeTokenUrl: https://api.twitter.com/oauth/authorize +// - AccessTokenUrl: https://api.twitter.com/oauth/access_token +// (3) NetFlix API: +// http://developer.netflix.com/docs/Security +// - RequestTokenUrl: http://api.netflix.com/oauth/request_token +// - AuthroizeTokenUrl: https://api-user.netflix.com/oauth/login +// - AccessTokenUrl: http://api.netflix.com/oauth/access_token +// Set HttpMethod if the service provider requires a different HTTP method +// to be used for OAuth token requests +type ServiceProvider struct { + RequestTokenUrl string + AuthorizeTokenUrl string + AccessTokenUrl string + HttpMethod string + BodyHash bool + IgnoreTimestamp bool + + // Enables non spec-compliant behavior: + // Allow parameters to be passed in the query string rather + // than the body. + // See https://github.com/mrjones/oauth/pull/63 + SignQueryParams bool +} + +func (sp *ServiceProvider) httpMethod() string { + if sp.HttpMethod != "" { + return sp.HttpMethod + } + + return "GET" +} + +// lockedNonceGenerator wraps a non-reentrant random number generator with a +// lock +type lockedNonceGenerator struct { + nonceGenerator nonceGenerator + lock sync.Mutex +} + +func newLockedNonceGenerator(c clock) *lockedNonceGenerator { + return &lockedNonceGenerator{ + nonceGenerator: rand.New(rand.NewSource(c.Nanos())), + } +} + +func (n *lockedNonceGenerator) Int63() int64 { + n.lock.Lock() + r := n.nonceGenerator.Int63() + n.lock.Unlock() + return r +} + +// Consumers are stateless, you can call the various methods (GetRequestTokenAndUrl, +// AuthorizeToken, and Get) on various different instances of Consumers *as long as +// they were set up in the same way.* It is up to you, as the caller to persist the +// necessary state (RequestTokens and AccessTokens). +type Consumer struct { + // Some ServiceProviders require extra parameters to be passed for various reasons. + // For example Google APIs require you to set a scope= parameter to specify how much + // access is being granted. The proper values for scope= depend on the service: + // For more, see: http://code.google.com/apis/accounts/docs/OAuth.html#prepScope + AdditionalParams map[string]string + + // The rest of this class is configured via the NewConsumer function. + consumerKey string + serviceProvider ServiceProvider + + // Some APIs (e.g. Netflix) aren't quite standard OAuth, and require passing + // additional parameters when authorizing the request token. For most APIs + // this field can be ignored. For Netflix, do something like: + // consumer.AdditionalAuthorizationUrlParams = map[string]string{ + // "application_name": "YourAppName", + // "oauth_consumer_key": "YourConsumerKey", + // } + AdditionalAuthorizationUrlParams map[string]string + + debug bool + + // Defaults to http.Client{}, can be overridden (e.g. for testing) as necessary + HttpClient HttpClient + + // Some APIs (e.g. Intuit/Quickbooks) require sending additional headers along with + // requests. (like "Accept" to specify the response type as XML or JSON) Note that this + // will only *add* headers, not set existing ones. + AdditionalHeaders map[string][]string + + // Private seams for mocking dependencies when testing + clock clock + // Seeded generators are not reentrant + nonceGenerator nonceGenerator + signer signer +} + +func newConsumer(consumerKey string, serviceProvider ServiceProvider, httpClient *http.Client) *Consumer { + clock := &defaultClock{} + if httpClient == nil { + httpClient = &http.Client{} + } + return &Consumer{ + consumerKey: consumerKey, + serviceProvider: serviceProvider, + clock: clock, + HttpClient: httpClient, + nonceGenerator: newLockedNonceGenerator(clock), + + AdditionalParams: make(map[string]string), + AdditionalAuthorizationUrlParams: make(map[string]string), + } +} + +// Creates a new Consumer instance, with a HMAC-SHA1 signer +// - consumerKey and consumerSecret: +// values you should obtain from the ServiceProvider when you register your +// application. +// +// - serviceProvider: +// see the documentation for ServiceProvider for how to create this. +// +func NewConsumer(consumerKey string, consumerSecret string, + serviceProvider ServiceProvider) *Consumer { + consumer := newConsumer(consumerKey, serviceProvider, nil) + + consumer.signer = &HMACSigner{ + consumerSecret: consumerSecret, + hashFunc: crypto.SHA1, + } + + return consumer +} + +// Creates a new Consumer instance, with a HMAC-SHA1 signer +// - consumerKey and consumerSecret: +// values you should obtain from the ServiceProvider when you register your +// application. +// +// - serviceProvider: +// see the documentation for ServiceProvider for how to create this. +// +// - httpClient: +// Provides a custom implementation of the httpClient used under the hood +// to make the request. This is especially useful if you want to use +// Google App Engine. +// +func NewCustomHttpClientConsumer(consumerKey string, consumerSecret string, + serviceProvider ServiceProvider, httpClient *http.Client) *Consumer { + consumer := newConsumer(consumerKey, serviceProvider, httpClient) + + consumer.signer = &HMACSigner{ + consumerSecret: consumerSecret, + hashFunc: crypto.SHA1, + } + + return consumer +} + +// Creates a new Consumer instance, with a HMAC signer +// - consumerKey and consumerSecret: +// values you should obtain from the ServiceProvider when you register your +// application. +// +// - hashFunc: +// the crypto.Hash to use for signatures +// +// - serviceProvider: +// see the documentation for ServiceProvider for how to create this. +// +// - httpClient: +// Provides a custom implementation of the httpClient used under the hood +// to make the request. This is especially useful if you want to use +// Google App Engine. Can be nil for default. +// +func NewCustomConsumer(consumerKey string, consumerSecret string, + hashFunc crypto.Hash, serviceProvider ServiceProvider, + httpClient *http.Client) *Consumer { + consumer := newConsumer(consumerKey, serviceProvider, httpClient) + + consumer.signer = &HMACSigner{ + consumerSecret: consumerSecret, + hashFunc: hashFunc, + } + + return consumer +} + +// Creates a new Consumer instance, with a RSA-SHA1 signer +// - consumerKey: +// value you should obtain from the ServiceProvider when you register your +// application. +// +// - privateKey: +// the private key to use for signatures +// +// - serviceProvider: +// see the documentation for ServiceProvider for how to create this. +// +func NewRSAConsumer(consumerKey string, privateKey *rsa.PrivateKey, + serviceProvider ServiceProvider) *Consumer { + consumer := newConsumer(consumerKey, serviceProvider, nil) + + consumer.signer = &RSASigner{ + privateKey: privateKey, + hashFunc: crypto.SHA1, + rand: cryptoRand.Reader, + } + + return consumer +} + +// Creates a new Consumer instance, with a RSA signer +// - consumerKey: +// value you should obtain from the ServiceProvider when you register your +// application. +// +// - privateKey: +// the private key to use for signatures +// +// - hashFunc: +// the crypto.Hash to use for signatures +// +// - serviceProvider: +// see the documentation for ServiceProvider for how to create this. +// +// - httpClient: +// Provides a custom implementation of the httpClient used under the hood +// to make the request. This is especially useful if you want to use +// Google App Engine. Can be nil for default. +// +func NewCustomRSAConsumer(consumerKey string, privateKey *rsa.PrivateKey, + hashFunc crypto.Hash, serviceProvider ServiceProvider, + httpClient *http.Client) *Consumer { + consumer := newConsumer(consumerKey, serviceProvider, httpClient) + + consumer.signer = &RSASigner{ + privateKey: privateKey, + hashFunc: hashFunc, + rand: cryptoRand.Reader, + } + + return consumer +} + +// Kicks off the OAuth authorization process. +// - callbackUrl: +// Authorizing a token *requires* redirecting to the service provider. This is the +// URL which the service provider will redirect the user back to after that +// authorization is completed. The service provider will pass back a verification +// code which is necessary to complete the rest of the process (in AuthorizeToken). +// Notes on callbackUrl: +// - Some (all?) service providers allow for setting "oob" (for out-of-band) as a +// callback url. If this is set the service provider will present the +// verification code directly to the user, and you must provide a place for +// them to copy-and-paste it into. +// - Otherwise, the user will be redirected to callbackUrl in the browser, and +// will append a "oauth_verifier=" parameter. +// +// This function returns: +// - rtoken: +// A temporary RequestToken, used during the authorization process. You must save +// this since it will be necessary later in the process when calling +// AuthorizeToken(). +// +// - url: +// A URL that you should redirect the user to in order that they may authorize you +// to the service provider. +// +// - err: +// Set only if there was an error, nil otherwise. +func (c *Consumer) GetRequestTokenAndUrl(callbackUrl string) (rtoken *RequestToken, loginUrl string, err error) { + return c.GetRequestTokenAndUrlWithParams(callbackUrl, c.AdditionalParams) +} + +func (c *Consumer) GetRequestTokenAndUrlWithParams(callbackUrl string, additionalParams map[string]string) (rtoken *RequestToken, loginUrl string, err error) { + params := c.baseParams(c.consumerKey, additionalParams) + if callbackUrl != "" { + params.Add(CALLBACK_PARAM, callbackUrl) + } + + req := &request{ + method: c.serviceProvider.httpMethod(), + url: c.serviceProvider.RequestTokenUrl, + oauthParams: params, + } + if _, err := c.signRequest(req, ""); err != nil { // We don't have a token secret for the key yet + return nil, "", err + } + + resp, err := c.getBody(c.serviceProvider.httpMethod(), c.serviceProvider.RequestTokenUrl, params) + if err != nil { + return nil, "", errors.New("getBody: " + err.Error()) + } + + requestToken, err := parseRequestToken(*resp) + if err != nil { + return nil, "", errors.New("parseRequestToken: " + err.Error()) + } + + loginParams := make(url.Values) + for k, v := range c.AdditionalAuthorizationUrlParams { + loginParams.Set(k, v) + } + loginParams.Set(TOKEN_PARAM, requestToken.Token) + + loginUrl = c.serviceProvider.AuthorizeTokenUrl + "?" + loginParams.Encode() + + return requestToken, loginUrl, nil +} + +// After the user has authorized you to the service provider, use this method to turn +// your temporary RequestToken into a permanent AccessToken. You must pass in two values: +// - rtoken: +// The RequestToken returned from GetRequestTokenAndUrl() +// +// - verificationCode: +// The string which passed back from the server, either as the oauth_verifier +// query param appended to callbackUrl *OR* a string manually entered by the user +// if callbackUrl is "oob" +// +// It will return: +// - atoken: +// A permanent AccessToken which can be used to access the user's data (until it is +// revoked by the user or the service provider). +// +// - err: +// Set only if there was an error, nil otherwise. +func (c *Consumer) AuthorizeToken(rtoken *RequestToken, verificationCode string) (atoken *AccessToken, err error) { + return c.AuthorizeTokenWithParams(rtoken, verificationCode, c.AdditionalParams) +} + +func (c *Consumer) AuthorizeTokenWithParams(rtoken *RequestToken, verificationCode string, additionalParams map[string]string) (atoken *AccessToken, err error) { + params := map[string]string{ + VERIFIER_PARAM: verificationCode, + TOKEN_PARAM: rtoken.Token, + } + return c.makeAccessTokenRequestWithParams(params, rtoken.Secret, additionalParams) +} + +// Use the service provider to refresh the AccessToken for a given session. +// Note that this is only supported for service providers that manage an +// authorization session (e.g. Yahoo). +// +// Most providers do not return the SESSION_HANDLE_PARAM needed to refresh +// the token. +// +// See http://oauth.googlecode.com/svn/spec/ext/session/1.0/drafts/1/spec.html +// for more information. +// - accessToken: +// The AccessToken returned from AuthorizeToken() +// +// It will return: +// - atoken: +// An AccessToken which can be used to access the user's data (until it is +// revoked by the user or the service provider). +// +// - err: +// Set if accessToken does not contain the SESSION_HANDLE_PARAM needed to +// refresh the token, or if an error occurred when making the request. +func (c *Consumer) RefreshToken(accessToken *AccessToken) (atoken *AccessToken, err error) { + params := make(map[string]string) + sessionHandle, ok := accessToken.AdditionalData[SESSION_HANDLE_PARAM] + if !ok { + return nil, errors.New("Missing " + SESSION_HANDLE_PARAM + " in access token.") + } + params[SESSION_HANDLE_PARAM] = sessionHandle + params[TOKEN_PARAM] = accessToken.Token + + return c.makeAccessTokenRequest(params, accessToken.Secret) +} + +// Use the service provider to obtain an AccessToken for a given session +// - params: +// The access token request paramters. +// +// - secret: +// Secret key to use when signing the access token request. +// +// It will return: +// - atoken +// An AccessToken which can be used to access the user's data (until it is +// revoked by the user or the service provider). +// +// - err: +// Set only if there was an error, nil otherwise. +func (c *Consumer) makeAccessTokenRequest(params map[string]string, secret string) (atoken *AccessToken, err error) { + return c.makeAccessTokenRequestWithParams(params, secret, c.AdditionalParams) +} + +func (c *Consumer) makeAccessTokenRequestWithParams(params map[string]string, secret string, additionalParams map[string]string) (atoken *AccessToken, err error) { + orderedParams := c.baseParams(c.consumerKey, additionalParams) + for key, value := range params { + orderedParams.Add(key, value) + } + + req := &request{ + method: c.serviceProvider.httpMethod(), + url: c.serviceProvider.AccessTokenUrl, + oauthParams: orderedParams, + } + if _, err := c.signRequest(req, secret); err != nil { + return nil, err + } + + resp, err := c.getBody(c.serviceProvider.httpMethod(), c.serviceProvider.AccessTokenUrl, orderedParams) + if err != nil { + return nil, err + } + + return parseAccessToken(*resp) +} + +type RoundTripper struct { + consumer *Consumer + token *AccessToken +} + +func (c *Consumer) MakeRoundTripper(token *AccessToken) (*RoundTripper, error) { + return &RoundTripper{consumer: c, token: token}, nil +} + +func (c *Consumer) MakeHttpClient(token *AccessToken) (*http.Client, error) { + return &http.Client{ + Transport: &RoundTripper{consumer: c, token: token}, + }, nil +} + +// ** DEPRECATED ** +// Please call Get on the http client returned by MakeHttpClient instead! +// +// Executes an HTTP Get, authorized via the AccessToken. +// - url: +// The base url, without any query params, which is being accessed +// +// - userParams: +// Any key=value params to be included in the query string +// +// - token: +// The AccessToken returned by AuthorizeToken() +// +// This method returns: +// - resp: +// The HTTP Response resulting from making this request. +// +// - err: +// Set only if there was an error, nil otherwise. +func (c *Consumer) Get(url string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) { + return c.makeAuthorizedRequest("GET", url, LOC_URL, "", userParams, token) +} + +func encodeUserParams(userParams map[string]string) string { + data := url.Values{} + for k, v := range userParams { + data.Add(k, v) + } + return data.Encode() +} + +// ** DEPRECATED ** +// Please call "Post" on the http client returned by MakeHttpClient instead +func (c *Consumer) PostForm(url string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) { + return c.PostWithBody(url, "", userParams, token) +} + +// ** DEPRECATED ** +// Please call "Post" on the http client returned by MakeHttpClient instead +func (c *Consumer) Post(url string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) { + return c.PostWithBody(url, "", userParams, token) +} + +// ** DEPRECATED ** +// Please call "Post" on the http client returned by MakeHttpClient instead +func (c *Consumer) PostWithBody(url string, body string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) { + return c.makeAuthorizedRequest("POST", url, LOC_BODY, body, userParams, token) +} + +// ** DEPRECATED ** +// Please call "Do" on the http client returned by MakeHttpClient instead +// (and set the "Content-Type" header explicitly in the http.Request) +func (c *Consumer) PostJson(url string, body string, token *AccessToken) (resp *http.Response, err error) { + return c.makeAuthorizedRequest("POST", url, LOC_JSON, body, nil, token) +} + +// ** DEPRECATED ** +// Please call "Do" on the http client returned by MakeHttpClient instead +// (and set the "Content-Type" header explicitly in the http.Request) +func (c *Consumer) PostXML(url string, body string, token *AccessToken) (resp *http.Response, err error) { + return c.makeAuthorizedRequest("POST", url, LOC_XML, body, nil, token) +} + +// ** DEPRECATED ** +// Please call "Do" on the http client returned by MakeHttpClient instead +// (and setup the multipart data explicitly in the http.Request) +func (c *Consumer) PostMultipart(url, multipartName string, multipartData io.ReadCloser, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) { + return c.makeAuthorizedRequestReader("POST", url, LOC_MULTIPART, 0, multipartName, multipartData, userParams, token) +} + +// ** DEPRECATED ** +// Please call "Delete" on the http client returned by MakeHttpClient instead +func (c *Consumer) Delete(url string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) { + return c.makeAuthorizedRequest("DELETE", url, LOC_URL, "", userParams, token) +} + +// ** DEPRECATED ** +// Please call "Put" on the http client returned by MakeHttpClient instead +func (c *Consumer) Put(url string, body string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) { + return c.makeAuthorizedRequest("PUT", url, LOC_URL, body, userParams, token) +} + +func (c *Consumer) Debug(enabled bool) { + c.debug = enabled + c.signer.Debug(enabled) +} + +type pair struct { + key string + value string +} + +type pairs []pair + +func (p pairs) Len() int { return len(p) } +func (p pairs) Less(i, j int) bool { return p[i].key < p[j].key } +func (p pairs) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +// This function has basically turned into a backwards compatibility layer +// between the old API (where clients explicitly called consumer.Get() +// consumer.Post() etc), and the new API (which takes actual http.Requests) +// +// So, here we construct the appropriate HTTP request for the inputs. +func (c *Consumer) makeAuthorizedRequestReader(method string, urlString string, dataLocation DataLocation, contentLength int, multipartName string, body io.ReadCloser, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) { + urlObject, err := url.Parse(urlString) + if err != nil { + return nil, err + } + + request := &http.Request{ + Method: method, + URL: urlObject, + Header: http.Header{}, + Body: body, + ContentLength: int64(contentLength), + } + + vals := url.Values{} + for k, v := range userParams { + vals.Add(k, v) + } + + if dataLocation != LOC_BODY { + request.URL.RawQuery = vals.Encode() + request.URL.RawQuery = strings.Replace( + request.URL.RawQuery, ";", "%3B", -1) + + } else { + // TODO(mrjones): validate that we're not overrideing an exising body? + request.Body = ioutil.NopCloser(strings.NewReader(vals.Encode())) + request.ContentLength = int64(len(vals.Encode())) + } + + for k, vs := range c.AdditionalHeaders { + for _, v := range vs { + request.Header.Set(k, v) + } + } + + if dataLocation == LOC_BODY { + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + + if dataLocation == LOC_JSON { + request.Header.Set("Content-Type", "application/json") + } + + if dataLocation == LOC_XML { + request.Header.Set("Content-Type", "application/xml") + } + + if dataLocation == LOC_MULTIPART { + pipeReader, pipeWriter := io.Pipe() + writer := multipart.NewWriter(pipeWriter) + if request.URL.Host == "www.mrjon.es" && + request.URL.Path == "/unittest" { + writer.SetBoundary("UNITTESTBOUNDARY") + } + go func(body io.Reader) { + part, err := writer.CreateFormFile(multipartName, "/no/matter") + if err != nil { + writer.Close() + pipeWriter.CloseWithError(err) + return + } + _, err = io.Copy(part, body) + if err != nil { + writer.Close() + pipeWriter.CloseWithError(err) + return + } + writer.Close() + pipeWriter.Close() + }(body) + request.Body = pipeReader + request.Header.Set("Content-Type", writer.FormDataContentType()) + } + + rt := RoundTripper{consumer: c, token: token} + + resp, err = rt.RoundTrip(request) + if err != nil { + return resp, err + } + + if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { + defer resp.Body.Close() + bytes, _ := ioutil.ReadAll(resp.Body) + + return resp, HTTPExecuteError{ + RequestHeaders: "", + ResponseBodyBytes: bytes, + Status: resp.Status, + StatusCode: resp.StatusCode, + } + } + + return resp, nil +} + +// cloneReq clones the src http.Request, making deep copies of the Header and +// the URL but shallow copies of everything else +func cloneReq(src *http.Request) *http.Request { + dst := &http.Request{} + *dst = *src + + dst.Header = make(http.Header, len(src.Header)) + for k, s := range src.Header { + dst.Header[k] = append([]string(nil), s...) + } + + if src.URL != nil { + dst.URL = cloneURL(src.URL) + } + + return dst +} + +// cloneURL shallow clones the src *url.URL +func cloneURL(src *url.URL) *url.URL { + dst := &url.URL{} + *dst = *src + + return dst +} + +func canonicalizeUrl(u *url.URL) string { + var buf bytes.Buffer + buf.WriteString(u.Scheme) + buf.WriteString("://") + buf.WriteString(u.Host) + buf.WriteString(u.Path) + + return buf.String() +} + +func parseBody(request *http.Request) (map[string]string, error) { + userParams := map[string]string{} + + // TODO(mrjones): factor parameter extraction into a separate method + if request.Header.Get("Content-Type") != + "application/x-www-form-urlencoded" { + // Most of the time we get parameters from the query string: + for k, vs := range request.URL.Query() { + if len(vs) != 1 { + return nil, fmt.Errorf("Must have exactly one value per param") + } + + userParams[k] = vs[0] + } + } else { + // x-www-form-urlencoded parameters come from the body instead: + defer request.Body.Close() + originalBody, err := ioutil.ReadAll(request.Body) + if err != nil { + return nil, err + } + + // If there was a body, we have to re-install it + // (because we've ruined it by reading it). + request.Body = ioutil.NopCloser(bytes.NewReader(originalBody)) + + params, err := url.ParseQuery(string(originalBody)) + if err != nil { + return nil, err + } + + for k, vs := range params { + if len(vs) != 1 { + return nil, fmt.Errorf("Must have exactly one value per param") + } + + userParams[k] = vs[0] + } + } + + return userParams, nil +} + +func paramsToSortedPairs(params map[string]string) pairs { + // Sort parameters alphabetically + paramPairs := make(pairs, len(params)) + i := 0 + for key, value := range params { + paramPairs[i] = pair{key: key, value: value} + i++ + } + sort.Sort(paramPairs) + + return paramPairs +} + +func calculateBodyHash(request *http.Request, s signer) (string, error) { + if request.Header.Get("Content-Type") == + "application/x-www-form-urlencoded" { + return "", nil + } + + var originalBody []byte + + if request.Body != nil { + var err error + + defer request.Body.Close() + originalBody, err = ioutil.ReadAll(request.Body) + if err != nil { + return "", err + } + + // If there was a body, we have to re-install it + // (because we've ruined it by reading it). + request.Body = ioutil.NopCloser(bytes.NewReader(originalBody)) + } + + h := s.HashFunc().New() + h.Write(originalBody) + rawSignature := h.Sum(nil) + + return base64.StdEncoding.EncodeToString(rawSignature), nil +} + +func (rt *RoundTripper) RoundTrip(userRequest *http.Request) (*http.Response, error) { + serverRequest := cloneReq(userRequest) + + allParams := rt.consumer.baseParams( + rt.consumer.consumerKey, rt.consumer.AdditionalParams) + + // Do not add the "oauth_token" parameter, if the access token has not been + // specified. By omitting this parameter when it is not specified, allows + // two-legged OAuth calls. + if len(rt.token.Token) > 0 { + allParams.Add(TOKEN_PARAM, rt.token.Token) + } + + if rt.consumer.serviceProvider.BodyHash { + bodyHash, err := calculateBodyHash(serverRequest, rt.consumer.signer) + if err != nil { + return nil, err + } + + if bodyHash != "" { + allParams.Add(BODY_HASH_PARAM, bodyHash) + } + } + + authParams := allParams.Clone() + + // TODO(mrjones): put these directly into the paramPairs below? + userParams, err := parseBody(serverRequest) + if err != nil { + return nil, err + } + paramPairs := paramsToSortedPairs(userParams) + + for i := range paramPairs { + allParams.Add(paramPairs[i].key, paramPairs[i].value) + } + + signingURL := cloneURL(serverRequest.URL) + if host := serverRequest.Host; host != "" { + signingURL.Host = host + } + baseString := rt.consumer.requestString(serverRequest.Method, canonicalizeUrl(signingURL), allParams) + + signature, err := rt.consumer.signer.Sign(baseString, rt.token.Secret) + if err != nil { + return nil, err + } + + authParams.Add(SIGNATURE_PARAM, signature) + + // Set auth header. + oauthHdr := OAUTH_HEADER + for pos, key := range authParams.Keys() { + for innerPos, value := range authParams.Get(key) { + if pos+innerPos > 0 { + oauthHdr += "," + } + oauthHdr += key + "=\"" + value + "\"" + } + } + serverRequest.Header.Add(HTTP_AUTH_HEADER, oauthHdr) + + if rt.consumer.debug { + fmt.Printf("Request: %v\n", serverRequest) + } + + resp, err := rt.consumer.HttpClient.Do(serverRequest) + + if err != nil { + return resp, err + } + + return resp, nil +} + +func (c *Consumer) makeAuthorizedRequest(method string, url string, dataLocation DataLocation, body string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) { + return c.makeAuthorizedRequestReader(method, url, dataLocation, len(body), "", ioutil.NopCloser(strings.NewReader(body)), userParams, token) +} + +type request struct { + method string + url string + oauthParams *OrderedParams + userParams map[string]string +} + +type HttpClient interface { + Do(req *http.Request) (resp *http.Response, err error) +} + +type clock interface { + Seconds() int64 + Nanos() int64 +} + +type nonceGenerator interface { + Int63() int64 +} + +type key interface { + String() string +} + +type signer interface { + Sign(message string, tokenSecret string) (string, error) + Verify(message string, signature string) error + SignatureMethod() string + HashFunc() crypto.Hash + Debug(enabled bool) +} + +type defaultClock struct{} + +func (*defaultClock) Seconds() int64 { + return time.Now().Unix() +} + +func (*defaultClock) Nanos() int64 { + return time.Now().UnixNano() +} + +func (c *Consumer) signRequest(req *request, tokenSecret string) (*request, error) { + baseString := c.requestString(req.method, req.url, req.oauthParams) + + signature, err := c.signer.Sign(baseString, tokenSecret) + if err != nil { + return nil, err + } + + req.oauthParams.Add(SIGNATURE_PARAM, signature) + return req, nil +} + +// Obtains an AccessToken from the response of a service provider. +// - data: +// The response body. +// +// This method returns: +// - atoken: +// The AccessToken generated from the response body. +// +// - err: +// Set if an AccessToken could not be parsed from the given input. +func parseAccessToken(data string) (atoken *AccessToken, err error) { + parts, err := url.ParseQuery(data) + if err != nil { + return nil, err + } + + tokenParam := parts[TOKEN_PARAM] + parts.Del(TOKEN_PARAM) + if len(tokenParam) < 1 { + return nil, errors.New("Missing " + TOKEN_PARAM + " in response. " + + "Full response body: '" + data + "'") + } + tokenSecretParam := parts[TOKEN_SECRET_PARAM] + parts.Del(TOKEN_SECRET_PARAM) + if len(tokenSecretParam) < 1 { + return nil, errors.New("Missing " + TOKEN_SECRET_PARAM + " in response." + + "Full response body: '" + data + "'") + } + + additionalData := parseAdditionalData(parts) + + return &AccessToken{tokenParam[0], tokenSecretParam[0], additionalData}, nil +} + +func parseRequestToken(data string) (*RequestToken, error) { + parts, err := url.ParseQuery(data) + if err != nil { + return nil, err + } + + tokenParam := parts[TOKEN_PARAM] + if len(tokenParam) < 1 { + return nil, errors.New("Missing " + TOKEN_PARAM + " in response. " + + "Full response body: '" + data + "'") + } + tokenSecretParam := parts[TOKEN_SECRET_PARAM] + if len(tokenSecretParam) < 1 { + return nil, errors.New("Missing " + TOKEN_SECRET_PARAM + " in response." + + "Full response body: '" + data + "'") + } + return &RequestToken{tokenParam[0], tokenSecretParam[0]}, nil +} + +func (c *Consumer) baseParams(consumerKey string, additionalParams map[string]string) *OrderedParams { + params := NewOrderedParams() + params.Add(VERSION_PARAM, OAUTH_VERSION) + params.Add(SIGNATURE_METHOD_PARAM, c.signer.SignatureMethod()) + params.Add(TIMESTAMP_PARAM, strconv.FormatInt(c.clock.Seconds(), 10)) + params.Add(NONCE_PARAM, strconv.FormatInt(c.nonceGenerator.Int63(), 10)) + params.Add(CONSUMER_KEY_PARAM, consumerKey) + for key, value := range additionalParams { + params.Add(key, value) + } + return params +} + +func parseAdditionalData(parts url.Values) map[string]string { + params := make(map[string]string) + for key, value := range parts { + if len(value) > 0 { + params[key] = value[0] + } + } + return params +} + +type HMACSigner struct { + consumerSecret string + hashFunc crypto.Hash + debug bool +} + +func (s *HMACSigner) Debug(enabled bool) { + s.debug = enabled +} + +func (s *HMACSigner) Sign(message string, tokenSecret string) (string, error) { + key := escape(s.consumerSecret) + "&" + escape(tokenSecret) + if s.debug { + fmt.Println("Signing:", message) + fmt.Println("Key:", key) + } + + h := hmac.New(s.HashFunc().New, []byte(key)) + h.Write([]byte(message)) + rawSignature := h.Sum(nil) + + base64signature := base64.StdEncoding.EncodeToString(rawSignature) + if s.debug { + fmt.Println("Base64 signature:", base64signature) + } + return base64signature, nil +} + +func (s *HMACSigner) Verify(message string, signature string) error { + if s.debug { + fmt.Println("Verifying Base64 signature:", signature) + } + validSignature, err := s.Sign(message, "") + if err != nil { + return err + } + + if validSignature != signature { + decodedSigniture, _ := url.QueryUnescape(signature) + if validSignature != decodedSigniture { + return fmt.Errorf("signature did not match") + } + } + + return nil +} + +func (s *HMACSigner) SignatureMethod() string { + return SIGNATURE_METHOD_HMAC + HASH_METHOD_MAP[s.HashFunc()] +} + +func (s *HMACSigner) HashFunc() crypto.Hash { + return s.hashFunc +} + +type RSASigner struct { + debug bool + rand io.Reader + privateKey *rsa.PrivateKey + hashFunc crypto.Hash +} + +func (s *RSASigner) Debug(enabled bool) { + s.debug = enabled +} + +func (s *RSASigner) Sign(message string, tokenSecret string) (string, error) { + if s.debug { + fmt.Println("Signing:", message) + } + + h := s.HashFunc().New() + h.Write([]byte(message)) + digest := h.Sum(nil) + + signature, err := rsa.SignPKCS1v15(s.rand, s.privateKey, s.HashFunc(), digest) + if err != nil { + return "", nil + } + + base64signature := base64.StdEncoding.EncodeToString(signature) + if s.debug { + fmt.Println("Base64 signature:", base64signature) + } + + return base64signature, nil +} + +func (s *RSASigner) Verify(message string, base64signature string) error { + if s.debug { + fmt.Println("Verifying:", message) + fmt.Println("Verifying Base64 signature:", base64signature) + } + + h := s.HashFunc().New() + h.Write([]byte(message)) + digest := h.Sum(nil) + + signature, err := base64.StdEncoding.DecodeString(base64signature) + if err != nil { + return err + } + + return rsa.VerifyPKCS1v15(&s.privateKey.PublicKey, s.HashFunc(), digest, signature) +} + +func (s *RSASigner) SignatureMethod() string { + return SIGNATURE_METHOD_RSA + HASH_METHOD_MAP[s.HashFunc()] +} + +func (s *RSASigner) HashFunc() crypto.Hash { + return s.hashFunc +} + +func escape(s string) string { + t := make([]byte, 0, 3*len(s)) + for i := 0; i < len(s); i++ { + c := s[i] + if isEscapable(c) { + t = append(t, '%') + t = append(t, "0123456789ABCDEF"[c>>4]) + t = append(t, "0123456789ABCDEF"[c&15]) + } else { + t = append(t, s[i]) + } + } + return string(t) +} + +func isEscapable(b byte) bool { + return !('A' <= b && b <= 'Z' || 'a' <= b && b <= 'z' || '0' <= b && b <= '9' || b == '-' || b == '.' || b == '_' || b == '~') + +} + +func (c *Consumer) requestString(method string, url string, params *OrderedParams) string { + result := method + "&" + escape(url) + for pos, key := range params.Keys() { + for innerPos, value := range params.Get(key) { + if pos+innerPos == 0 { + result += "&" + } else { + result += escape("&") + } + result += escape(fmt.Sprintf("%s=%s", key, value)) + } + } + return result +} + +func (c *Consumer) getBody(method, url string, oauthParams *OrderedParams) (*string, error) { + resp, err := c.httpExecute(method, url, "", 0, nil, oauthParams) + if err != nil { + return nil, errors.New("httpExecute: " + err.Error()) + } + bodyBytes, err := ioutil.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + return nil, errors.New("ReadAll: " + err.Error()) + } + bodyStr := string(bodyBytes) + if c.debug { + fmt.Printf("STATUS: %d %s\n", resp.StatusCode, resp.Status) + fmt.Println("BODY RESPONSE: " + bodyStr) + } + return &bodyStr, nil +} + +// HTTPExecuteError signals that a call to httpExecute failed. +type HTTPExecuteError struct { + // RequestHeaders provides a stringified listing of request headers. + RequestHeaders string + // ResponseBodyBytes is the response read into a byte slice. + ResponseBodyBytes []byte + // Status is the status code string response. + Status string + // StatusCode is the parsed status code. + StatusCode int +} + +// Error provides a printable string description of an HTTPExecuteError. +func (e HTTPExecuteError) Error() string { + return "HTTP response is not 200/OK as expected. Actual response: \n" + + "\tResponse Status: '" + e.Status + "'\n" + + "\tResponse Code: " + strconv.Itoa(e.StatusCode) + "\n" + + "\tResponse Body: " + string(e.ResponseBodyBytes) + "\n" + + "\tRequest Headers: " + e.RequestHeaders +} + +func (c *Consumer) httpExecute( + method string, urlStr string, contentType string, contentLength int, body io.Reader, oauthParams *OrderedParams) (*http.Response, error) { + // Create base request. + req, err := http.NewRequest(method, urlStr, body) + if err != nil { + return nil, errors.New("NewRequest failed: " + err.Error()) + } + + // Set auth header. + req.Header = http.Header{} + oauthHdr := "OAuth " + for pos, key := range oauthParams.Keys() { + for innerPos, value := range oauthParams.Get(key) { + if pos+innerPos > 0 { + oauthHdr += "," + } + oauthHdr += key + "=\"" + value + "\"" + } + } + req.Header.Add("Authorization", oauthHdr) + + // Add additional custom headers + for key, vals := range c.AdditionalHeaders { + for _, val := range vals { + req.Header.Add(key, val) + } + } + + // Set contentType if passed. + if contentType != "" { + req.Header.Set("Content-Type", contentType) + } + + // Set contentLength if passed. + if contentLength > 0 { + req.Header.Set("Content-Length", strconv.Itoa(contentLength)) + } + + if c.debug { + fmt.Printf("Request: %v\n", req) + } + resp, err := c.HttpClient.Do(req) + if err != nil { + return nil, errors.New("Do: " + err.Error()) + } + + debugHeader := "" + for k, vals := range req.Header { + for _, val := range vals { + debugHeader += "[key: " + k + ", val: " + val + "]" + } + } + + // StatusMultipleChoices is 300, any 2xx response should be treated as success + if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { + defer resp.Body.Close() + bytes, _ := ioutil.ReadAll(resp.Body) + + return resp, HTTPExecuteError{ + RequestHeaders: debugHeader, + ResponseBodyBytes: bytes, + Status: resp.Status, + StatusCode: resp.StatusCode, + } + } + return resp, err +} + +// +// String Sorting helpers +// + +type ByValue []string + +func (a ByValue) Len() int { + return len(a) +} + +func (a ByValue) Swap(i, j int) { + a[i], a[j] = a[j], a[i] +} + +func (a ByValue) Less(i, j int) bool { + return a[i] < a[j] +} + +// +// ORDERED PARAMS +// + +type OrderedParams struct { + allParams map[string][]string + keyOrdering []string +} + +func NewOrderedParams() *OrderedParams { + return &OrderedParams{ + allParams: make(map[string][]string), + keyOrdering: make([]string, 0), + } +} + +func (o *OrderedParams) Get(key string) []string { + sort.Sort(ByValue(o.allParams[key])) + return o.allParams[key] +} + +func (o *OrderedParams) Keys() []string { + sort.Sort(o) + return o.keyOrdering +} + +func (o *OrderedParams) Add(key, value string) { + o.AddUnescaped(key, escape(value)) +} + +func (o *OrderedParams) AddUnescaped(key, value string) { + if _, exists := o.allParams[key]; !exists { + o.keyOrdering = append(o.keyOrdering, key) + o.allParams[key] = make([]string, 1) + o.allParams[key][0] = value + } else { + o.allParams[key] = append(o.allParams[key], value) + } +} + +func (o *OrderedParams) Len() int { + return len(o.keyOrdering) +} + +func (o *OrderedParams) Less(i int, j int) bool { + return o.keyOrdering[i] < o.keyOrdering[j] +} + +func (o *OrderedParams) Swap(i int, j int) { + o.keyOrdering[i], o.keyOrdering[j] = o.keyOrdering[j], o.keyOrdering[i] +} + +func (o *OrderedParams) Clone() *OrderedParams { + clone := NewOrderedParams() + for _, key := range o.Keys() { + for _, value := range o.Get(key) { + clone.AddUnescaped(key, value) + } + } + return clone +} diff --git a/vendor/github.com/mrjones/oauth/pre-commit.sh b/vendor/github.com/mrjones/oauth/pre-commit.sh new file mode 100755 index 00000000000..91b9e882360 --- /dev/null +++ b/vendor/github.com/mrjones/oauth/pre-commit.sh @@ -0,0 +1,21 @@ +#!/bin/bash +# ln -s $PWD/pre-commit.sh .git/hooks/pre-commit +go test *.go +RESULT=$? +if [[ $RESULT != 0 ]]; then + echo "REJECTING COMMIT (test failed with status: $RESULT)" + exit 1; +fi + +go fmt *.go +for e in $(ls examples); do + go build examples/$e/*.go + RESULT=$? + if [[ $RESULT != 0 ]]; then + echo "REJECTING COMMIT (Examples failed to compile)" + exit $RESULT; + fi + go fmt examples/$e/*.go +done + +exit 0 diff --git a/vendor/github.com/mrjones/oauth/provider.go b/vendor/github.com/mrjones/oauth/provider.go new file mode 100644 index 00000000000..3a37e38a1bd --- /dev/null +++ b/vendor/github.com/mrjones/oauth/provider.go @@ -0,0 +1,163 @@ +package oauth + +import ( + "bytes" + "fmt" + "math" + "net/http" + "net/url" + "strconv" + "strings" +) + +// +// OAuth1 2-legged provider +// Contributed by https://github.com/jacobpgallagher +// + +// Provide an buffer reader which implements the Close() interface +type oauthBufferReader struct { + *bytes.Buffer +} + +// So that it implements the io.ReadCloser interface +func (m oauthBufferReader) Close() error { return nil } + +type ConsumerGetter func(key string, header map[string]string) (*Consumer, error) + +// Provider provides methods for a 2-legged Oauth1 provider +type Provider struct { + ConsumerGetter ConsumerGetter + + // For mocking + clock clock +} + +// NewProvider takes a function to get the consumer secret from a datastore. +// Returns a Provider +func NewProvider(secretGetter ConsumerGetter) *Provider { + provider := &Provider{ + secretGetter, + &defaultClock{}, + } + return provider +} + +// Combine a URL and Request to make the URL absolute +func makeURLAbs(url *url.URL, request *http.Request) { + if !url.IsAbs() { + url.Host = request.Host + if request.TLS != nil || request.Header.Get("X-Forwarded-Proto") == "https" { + url.Scheme = "https" + } else { + url.Scheme = "http" + } + } +} + +// IsAuthorized takes an *http.Request and returns a pointer to a string containing the consumer key, +// or nil if not authorized +func (provider *Provider) IsAuthorized(request *http.Request) (*string, error) { + var err error + var userParams map[string]string + + // start with the body/query params + userParams, err = parseBody(request) + if err != nil { + return nil, err + } + + // if the oauth params are in the Authorization header, grab them, and + // let them override what's in userParams + authHeader := request.Header.Get(HTTP_AUTH_HEADER) + if len(authHeader) > 6 && strings.EqualFold(OAUTH_HEADER, authHeader[0:6]) { + authHeader = authHeader[6:] + params := strings.Split(authHeader, ",") + for _, param := range params { + vals := strings.SplitN(param, "=", 2) + k := strings.Trim(vals[0], " ") + v := strings.Trim(strings.Trim(vals[1], "\""), " ") + if strings.HasPrefix(k, "oauth") { + userParams[k], err = url.QueryUnescape(v) + if err != nil { + return nil, err + } + } + } + } + + // pop the request's signature, it's not included in our signature + // calculation + oauthSignature, ok := userParams[SIGNATURE_PARAM] + if !ok { + return nil, fmt.Errorf("no oauth signature") + } + delete(userParams, SIGNATURE_PARAM) + + // get the oauth consumer key + consumerKey, ok := userParams[CONSUMER_KEY_PARAM] + if !ok || consumerKey == "" { + return nil, fmt.Errorf("no consumer key") + } + + // use it to create a consumer object + consumer, err := provider.ConsumerGetter(consumerKey, userParams) + if err != nil { + return nil, err + } + + // Make sure timestamp is no more than 10 digits + timestamp := userParams[TIMESTAMP_PARAM] + if len(timestamp) > 10 { + timestamp = timestamp[0:10] + } + + // Check the timestamp + if !consumer.serviceProvider.IgnoreTimestamp { + oauthTimeNumber, err := strconv.Atoi(timestamp) + if err != nil { + return nil, err + } + + if math.Abs(float64(int64(oauthTimeNumber)-provider.clock.Seconds())) > 5*60 { + return nil, fmt.Errorf("too much clock skew") + } + } + + // Include the query string params in the base string + if consumer.serviceProvider.SignQueryParams { + for k, v := range request.URL.Query() { + userParams[k] = strings.Join(v, "") + } + } + + // if our consumer supports bodyhash, check it + if consumer.serviceProvider.BodyHash { + bodyHash, err := calculateBodyHash(request, consumer.signer) + if err != nil { + return nil, err + } + + sentHash, ok := userParams[BODY_HASH_PARAM] + + if bodyHash == "" && ok { + return nil, fmt.Errorf("body_hash must not be set") + } else if sentHash != bodyHash { + return nil, fmt.Errorf("body_hash mismatch") + } + } + + allParams := NewOrderedParams() + for key, value := range userParams { + allParams.Add(key, value) + } + + makeURLAbs(request.URL, request) + baseString := consumer.requestString(request.Method, canonicalizeUrl(request.URL), allParams) + err = consumer.signer.Verify(baseString, oauthSignature) + if err != nil { + return nil, err + } + + return &consumerKey, nil +} diff --git a/vendor/vendor.json b/vendor/vendor.json index bd809fc7d20..45a60c74712 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -542,20 +542,62 @@ { "checksumSHA1": "O3KUfEXQPfdQ+tCMpP2RAIRJJqY=", "path": "github.com/markbates/goth", - "revision": "450379d2950a65070b23cc93c53436553add4484", - "revisionTime": "2017-02-06T19:46:32Z" + "revision": "90362394a367f9d77730911973462a53d69662ba", + "revisionTime": "2017-02-23T14:12:10Z" }, { "checksumSHA1": "MkFKwLV3icyUo4oP0BgEs+7+R1Y=", "path": "github.com/markbates/goth/gothic", - "revision": "450379d2950a65070b23cc93c53436553add4484", - "revisionTime": "2017-02-06T19:46:32Z" + "revision": "90362394a367f9d77730911973462a53d69662ba", + "revisionTime": "2017-02-23T14:12:10Z" }, { - "checksumSHA1": "ZFqznX3/ZW65I4QeepiHQdE69nA=", + "checksumSHA1": "crNSlQADjX6hcxykON2tFCqY4iw=", + "path": "github.com/markbates/goth/providers/bitbucket", + "revision": "90362394a367f9d77730911973462a53d69662ba", + "revisionTime": "2017-02-23T14:12:10Z" + }, + { + "checksumSHA1": "1Kp4DKkJNVn135Xg8H4a6CFBNy8=", + "path": "github.com/markbates/goth/providers/dropbox", + "revision": "90362394a367f9d77730911973462a53d69662ba", + "revisionTime": "2017-02-23T14:12:10Z" + }, + { + "checksumSHA1": "cGs1da29iOBJh5EAH0icKDbN8CA=", + "path": "github.com/markbates/goth/providers/facebook", + "revision": "90362394a367f9d77730911973462a53d69662ba", + "revisionTime": "2017-02-23T14:12:10Z" + }, + { + "checksumSHA1": "P6nBZ850aaekpOcoXNdRhK86bH8=", "path": "github.com/markbates/goth/providers/github", - "revision": "450379d2950a65070b23cc93c53436553add4484", - "revisionTime": "2017-02-06T19:46:32Z" + "revision": "90362394a367f9d77730911973462a53d69662ba", + "revisionTime": "2017-02-23T14:12:10Z" + }, + { + "checksumSHA1": "o/109paSRy9HqV87gR4zUZMMSzs=", + "path": "github.com/markbates/goth/providers/gitlab", + "revision": "90362394a367f9d77730911973462a53d69662ba", + "revisionTime": "2017-02-23T14:12:10Z" + }, + { + "checksumSHA1": "cX6kR9y94BWFZvI/7UFrsFsP3FQ=", + "path": "github.com/markbates/goth/providers/gplus", + "revision": "90362394a367f9d77730911973462a53d69662ba", + "revisionTime": "2017-02-23T14:12:10Z" + }, + { + "checksumSHA1": "sMYKhqAUZXM1+T/TjlMhWh8Vveo=", + "path": "github.com/markbates/goth/providers/openidConnect", + "revision": "90362394a367f9d77730911973462a53d69662ba", + "revisionTime": "2017-02-23T14:12:10Z" + }, + { + "checksumSHA1": "1w0V6jYXaGlEtZcMeYTOAAucvgw=", + "path": "github.com/markbates/goth/providers/twitter", + "revision": "90362394a367f9d77730911973462a53d69662ba", + "revisionTime": "2017-02-23T14:12:10Z" }, { "checksumSHA1": "9FJUwn3EIgASVki+p8IHgWVC5vQ=", @@ -575,6 +617,12 @@ "revision": "f77f16ffc87a6a58814e64ae72d55f9c41374e6d", "revisionTime": "2016-10-12T08:37:05Z" }, + { + "checksumSHA1": "hQcIDtbilIlkJaYhl2faWIFL8uY=", + "path": "github.com/mrjones/oauth", + "revision": "3f67d9c274355678b2f9844b08d643e2f9213340", + "revisionTime": "2017-02-25T17:57:52Z" + }, { "checksumSHA1": "lfOuMiAdiqc/dalUSBTvD5ZMSzA=", "path": "github.com/msteinert/pam",