Documentation ¶
Overview ¶
Copyright 2016 Wenhui Shen <www.webx.top>
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright 2016 Wenhui Shen <www.webx.top>
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright 2016 Wenhui Shen <www.webx.top>
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Index ¶
- Constants
- Variables
- func BeginAuthHandler(ctx echo.Context) error
- func GetAuthURL(ctx echo.Context) (string, error)
- func MiddlewareVerifyProvider(config *Config) echo.MiddlewareFuncd
- type Account
- type Config
- func (c *Config) AddAccount(accounts ...*Account) *Config
- func (c *Config) CallbackURL(providerName string) string
- func (c *Config) ClearAccounts()
- func (c *Config) ClearProviders() *Config
- func (c *Config) DeleteAccount(name string)
- func (c *Config) DeleteProvider(names ...string) *Config
- func (c *Config) GenerateProviders() *Config
- func (c *Config) GetAccount(name string) (account *Account)
- func (c *Config) LoginURL(providerName string) string
- func (c *Config) MergeSingle(cfg *Config) (config Config)
- func (c *Config) NewProvider(account *Account) goth.Provider
- func (c *Config) RangeAccounts(cb func(*Account) bool) (ok bool)
- func (c *Config) SetAccount(newAccount *Account) *Config
- type OAuth
- func (p *OAuth) AddSuccessHandler(handlersFn ...interface{}) *OAuth
- func (p *OAuth) MiddlewareAuth(h echo.Handler) echo.Handler
- func (p *OAuth) SetBeginAuthHandler(handler echo.Handler) *OAuth
- func (p *OAuth) SetCompleteAuthHandler(handler func(ctx echo.Context) (goth.User, error)) *OAuth
- func (p *OAuth) SetFailHandler(handler echo.HTTPErrorHandler) *OAuth
- func (p *OAuth) SetSuccessHandler(handlersFn ...interface{}) *OAuth
- func (p *OAuth) User(ctx echo.Context) (u goth.User)
- func (p *OAuth) Wrapper(e *echo.Echo, middlewares ...interface{})
Constants ¶
const ( // DefaultPath /oauth DefaultPath = "/oauth" // DefaultContextKey oauth_user DefaultContextKey = "oauth_user" )
const SessionName = "EchoGothSession"
SessionName is the key used to access the session store. we could use the echo's sessions default, but this session should be not confict with the cookie session name defined by the sessions manager
Variables ¶
var CompleteUserAuth = func(ctx echo.Context) (goth.User, error) { providerName, err := GetProviderName(ctx) if err != nil { return EmptyUser, err } provider, err := goth.GetProvider(providerName) if err != nil { return EmptyUser, err } errorDescription := ctx.Query(`error_description`) if len(errorDescription) > 0 { return EmptyUser, errors.New(providerName + `: ` + errorDescription) } sv, ok := ctx.Session().Get(SessionName).(string) if !ok || len(sv) == 0 { return EmptyUser, errors.New("could not find a matching session for this request") } defer func() { if err != nil { ctx.Session().Delete(SessionName).Save() } }() var sess goth.Session sess, err = provider.UnmarshalSession(sv) if err != nil { return EmptyUser, err } err = validateState(ctx, sess) if err != nil { return EmptyUser, err } if cr, ok := sess.(echo.ContextRegister); ok { cr.SetContext(ctx) } var user goth.User user, err = provider.FetchUser(sess) if err == nil { return user, err } params := ctx.Queries() if len(params) == 0 && ctx.IsPost() { params = ctx.Request().PostForm().All() } _, err = sess.Authorize(provider, url.Values(params)) if err != nil { return EmptyUser, err } err = ctx.Session().Set(SessionName, sess.Marshal()).Save() if err != nil { return EmptyUser, err } user, err = provider.FetchUser(sess) return user, err }
CompleteUserAuth does what it says on the tin. It completes the authentication process and fetches all of the basic information about the user from the provider. It expects to be able to get the name of the provider from the named parameters as either "provider" or url query parameter ":provider".
var (
EmptyUser = goth.User{}
)
var ErrStateTokenMismatch = errors.New("state token mismatch")
var GetProviderName = getProviderName
GetProviderName is a function used to get the name of a provider for a given request. By default, this provider is fetched from the URL query string. If you provide it in a different way, assign your own function to this variable that returns the provider name for your request.
var GetState = func(ctx echo.Context) string { state := ctx.Query("state") if len(state) == 0 && ctx.IsPost() { state = ctx.Request().FormValue("state") } return state }
GetState gets the state returned by the provider during the callback. This is used to prevent CSRF attacks, see http://tools.ietf.org/html/rfc6749#section-10.12
var SetState = func(ctx echo.Context) (string, error) { state := ctx.Query("state") if len(state) > 0 { return state, nil } nonceBytes := make([]byte, 64) _, err := io.ReadFull(rand.Reader, nonceBytes) if err != nil { err = errors.New("gothic: source of randomness unavailable: " + err.Error()) return state, err } return base64.URLEncoding.EncodeToString(nonceBytes), nil }
SetState sets the state string associated with the given request. If no state string is associated with the request, one will be generated. This state is sent to the provider and can be retrieved during the callback.
Functions ¶
func BeginAuthHandler ¶
BeginAuthHandler is a convienence handler for starting the authentication process. It expects to be able to get the name of the provider from the named parameters as either "provider" or url query parameter ":provider". BeginAuthHandler will redirect the user to the appropriate authentication end-point for the requested provider.
func GetAuthURL ¶
GetAuthURL starts the authentication process with the requested provided. It will return a URL that should be used to send users to. It expects to be able to get the name of the provider from the query parameters as either "provider" or url query parameter ":provider". I would recommend using the BeginAuthHandler instead of doing all of these steps yourself, but that's entirely up to you.
func MiddlewareVerifyProvider ¶ added in v1.6.0
func MiddlewareVerifyProvider(config *Config) echo.MiddlewareFuncd
Types ¶
type Account ¶ added in v1.3.5
type Config ¶
type Config struct {
Host, Path string
// defaults to 'oauth_user' used by plugin to give you the goth.User, but you can take this manually also by `context.Get(ContextKey).(goth.User)`
ContextKey string
// contains filtered or unexported fields
}
Config the configs for the gothic oauth/oauth2 authentication for third-party websites All Key and Secret values are empty by default strings. Non-empty will be registered as Goth Provider automatically, by Iris the users can still register their own providers using goth.UseProviders contains the providers' keys (& secrets) and the relative auth callback url path(ex: "/auth" will be registered as /auth/:provider/callback)
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns OAuth config, the fields of the iteral are zero-values ( empty strings)
func (*Config) AddAccount ¶ added in v1.3.5
func (*Config) CallbackURL ¶ added in v1.3.5
func (*Config) ClearAccounts ¶ added in v1.6.0
func (c *Config) ClearAccounts()
func (*Config) ClearProviders ¶ added in v1.6.0
func (*Config) DeleteAccount ¶ added in v1.6.0
func (*Config) DeleteProvider ¶ added in v1.6.0
func (*Config) GenerateProviders ¶
GenerateProviders returns the valid goth providers and the relative url paths (because the goth.Provider doesn't have a public method to get the Auth path...) we do the hard-core/hand checking here at the configs.
receives one parameter which is the host from the server,ex: http://localhost:3000, will be used as prefix for the oauth callback
func (*Config) GetAccount ¶ added in v1.6.0
func (*Config) MergeSingle ¶
MergeSingle merges the default with the given config and returns the result
func (*Config) NewProvider ¶ added in v1.3.5
func (*Config) RangeAccounts ¶ added in v1.6.0
func (*Config) SetAccount ¶ added in v1.3.5
type OAuth ¶
OAuth is a plugin which helps you to use OAuth/OAuth2 apis from famous websites
func (*OAuth) AddSuccessHandler ¶ added in v1.3.5
AddSuccessHandler registers handler(s) which fires when the user logged in successfully
func (*OAuth) MiddlewareAuth ¶ added in v1.6.0
func (*OAuth) SetBeginAuthHandler ¶ added in v1.3.5
func (*OAuth) SetCompleteAuthHandler ¶ added in v1.3.5
func (*OAuth) SetFailHandler ¶ added in v1.3.5
func (p *OAuth) SetFailHandler(handler echo.HTTPErrorHandler) *OAuth
SetFailHandler registers handler which fires when the user failed to logged in underhood it justs registers an error handler to the StatusUnauthorized(400 status code), same as 'iris.OnError(400,handler)'
func (*OAuth) SetSuccessHandler ¶ added in v1.3.5
SetSuccessHandler registers handler(s) which fires when the user logged in successfully