Import path:
gitlab.soludian.com/soludian/fountain/libs/social_auth
social_auth
import "gitlab.soludian.com/soludian/fountain/libs/social_auth"Index
- Constants
- Variables
- func BeginAuthHandler(ctx fiber.Ctx) error
- func ContextForClient(h *http.Client) context.Context
- func CreateSessionStorage()
- func GetAuthURL(ctx fiber.Ctx) (string, error)
- func GetContextWithProvider(req *http.Request, provider string) *http.Request
- func GetFromSession(ctx fiber.Ctx, key string) (string, error)
- func HTTPClientWithFallBack(h *http.Client) *http.Client
- func Logout(ctx fiber.Ctx) error
- func RegisterProviders(providers ...Provider)
- func StoreInSession(ctx fiber.Ctx, key, value string) error
- type Config
- type Params
- type Provider
- type ProviderParamType
- type Providers
- type Session
- type User
Constants
const KPackageName = "social_auth"SessionName is the key used to access the session store.
const SessionName = "_fountain_session"Variables
var (
NoAuthUrlError = fmt.Errorf("an AuthURL has not been set")
InvalidTokenFromProviderError = fmt.Errorf("invalid token received from provider")
)CompleteUserAuth does what it says on the tin. It completes the authentication process and fetches all of the basic information about the user from the provider.
It expects to be able to get the name of the provider from the query parameters as either "provider" or ":provider".
See https://github.com/markbates/goth/examples/main.go to see this in action.
var CompleteUserAuth = func(ctx fiber.Ctx) (User, error) {
if !keySet && Store == nil {
fmt.Println("goth/fountain auth: no SESSION_SECRET environment variable is set. The default cookie store is not available and any calls will fail. Ignore this warning if you are using a different store.")
}
providerName, err := GetProviderName(ctx)
if err != nil {
return User{}, err
}
provider := GetProvider(providerName)
value, err := GetFromSession(ctx, providerName)
if err != nil {
return User{}, err
}
defer Logout(ctx)
sess, err := provider.UnmarshalSession(value)
if err != nil {
return User{}, err
}
err = validateState(ctx, sess)
if err != nil {
return User{}, err
}
user, err := provider.FetchUser(sess)
if err == nil {
return user, err
}
params := url.Values{}
queries := ctx.Queries()
if len(queries) == 0 && ctx.Method() == "POST" {
if err := ctx.Bind().Body(&queries); err != nil {
return User{}, err
}
}
for k, v := range queries {
params.Add(k, v)
}
_, err = sess.Authorize(provider, params)
if err != nil {
return User{}, err
}
err = StoreInSession(ctx, providerName, sess.Marshal())
if err != nil {
return User{}, err
}
gu, err := provider.FetchUser(sess)
return gu, err
}var GetFountainInstance = Lib.GetFountainInstancevar GetFountainManager = Lib.GetFountainManagerGetProviderName 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 GetProviderName = getProviderNameGetState 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 GetState = func(ctx fiber.Ctx) string {
if string(ctx.Request().Header.Method()) == http.MethodPost {
return ctx.FormValue("state")
}
return ctx.Query("state")
}Sử dụng khi config instance ở dạng key:value; Nếu config instance ở dạng key:array thì sử dụng hàm InstallFountainInstances Nếu config ở dạng key:array thì sẽ chỉ install config phần tử đầu tiên mà thôi
Install with config format <key>:<value>; eg: social_auth:<value>
Usage:
config.yaml:
social_auth:
name: default_name
...
code.go
social_auth.InstallFountainInstance()
social_auth.WithConfigKey("social_auth").InstallFountainInstance()var InstallFountainInstance = Lib.InstallFountainInstanceSử dụng khi config instance ở dạng key:array<value>; Sẽ luôn cố gắng khởi tạo kể cả khi config ở dạng key:value
Install with config format <key>:array<value>; eg: social_auth:array<value>
Usage:
config.yaml:
social_auth:
- name: default_name
...
code.go
social_auth.InstallFountainInstances()
social_auth.WithConfigKey("social_auth").InstallFountainInstances()var InstallFountainInstances = Lib.InstallFountainInstancesTruy cập thẳng tới bộ quản lý thư viện
var Lib = lib_3rd.NewLib(NewOAuthClient, lib_3rd.WithDefaultConfigsFunc[Config, client](defaultConfigs))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.
var SetState = func(ctx fiber.Ctx) string {
state := ctx.Query("state")
if len(state) > 0 {
return state
}
nonceBytes := make([]byte, 64)
_, err := io.ReadFull(rand.Reader, nonceBytes)
if err != nil {
panic("fountain auth: source of randomness unavailable: " + err.Error())
}
return base64.URLEncoding.EncodeToString(nonceBytes)
}Store can/should be set by applications using fountain auth. The default is a cookie store.
var Store *session.Storevar WithConfigKey = Lib.WithConfigKeyfunc BeginAuthHandler
func BeginAuthHandler(ctx fiber.Ctx) errorBeginAuthHandler is a convenience handler for starting the authentication process. It expects to be able to get the name of the provider from the query parameters as either "provider" or ":provider".
BeginAuthHandler will redirect the user to the appropriate authentication end-point for the requested provider.
See https://github.com/markbates/goth/examples/main.go to see this in action.
func ContextForClient
func ContextForClient(h *http.Client) context.ContextContextForClient provides a context for use with oauth2.
func CreateSessionStorage
func CreateSessionStorage()func GetAuthURL
func GetAuthURL(ctx fiber.Ctx) (string, error)GetAuthURL starts the authentication process with the requested provided. It will return a URL that should be used to send users to.
It expects to be able to get the name of the provider from the query parameters as either "provider" or ":provider".
I would recommend using the BeginAuthHandler instead of doing all of these steps yourself, but that's entirely up to you.
func GetContextWithProvider
func GetContextWithProvider(req *http.Request, provider string) *http.RequestGetContextWithProvider returns a new request context containing the provider
func GetFromSession
func GetFromSession(ctx fiber.Ctx, key string) (string, error)GetFromSession retrieves a previously-stored value from the session. If no value has previously been stored at the specified key, it will return an error.
func HTTPClientWithFallBack
func HTTPClientWithFallBack(h *http.Client) *http.ClientHTTPClientWithFallBack to be used in all fetch operations.
func Logout
func Logout(ctx fiber.Ctx) errorLogout invalidates a user session.
func RegisterProviders
func RegisterProviders(providers ...Provider)RegisterProviders adds a list of available providers for use with SocialAuth. Can be called multiple times. If you pass the same provider more than once, the last will be used.
func StoreInSession
func StoreInSession(ctx fiber.Ctx, key, value string) errorStoreInSession stores a specified key/value pair in the session.
type Config
type Config struct {
lib_3rd.BaseConfig `conf:",squash"`
Provider string `conf:"provider" json:"provider,omitempty"`
ClientKey string `conf:"client_key" json:"client_key,omitempty"`
Secret string `conf:"secret" json:"secret,omitempty"`
CallbackURL string `conf:"callback_url" json:"callback_url,omitempty"`
Scopes []string `conf:"scopes" json:"scopes,omitempty"`
}func (*Config) Validate
func (conf *Config) Validate() errortype Params
Params is used to pass data to sessions for authorization. An existing implementation, and the one most likely to be used, is `url.Values`.
type Params interface {
Get(string) string
}type Provider
Provider needs to be implemented for each 3rd party authentication provider e.g. Facebook, Twitter, etc...
type Provider interface {
InstallOAuth(*Config)
Name() string
SetName(name string)
BeginAuth(state string) (Session, error)
UnmarshalSession(string) (Session, error)
FetchUser(Session) (User, error)
Debug(bool)
RefreshToken(refreshToken string) (*oauth2.Token, error) //Get new access token based on the refresh token
RefreshTokenAvailable() bool //Refresh token is provided by auth provider or not
}func GetProvider
func GetProvider(name string) ProviderGetProvider returns a previously created provider. If SocialAuth has not been told to use the named provider it will return an error.
type ProviderParamType
type ProviderParamType stringProviderParamKey can be used as a key in context when passing in a provider
const ProviderParamKey ProviderParamType = "provider"type Providers
Providers is list of known/available providers.
type Providers map[string]Providerfunc GetProviders
func GetProviders() ProvidersGetProviders returns a list of all the providers currently in use.
type Session
Session needs to be implemented as part of the provider package. It will be marshaled and persisted between requests to "tie" the start and the end of the authorization process with a 3rd party provider.
type Session interface {
// GetAuthURL returns the URL for the authentication end-point for the provider.
GetAuthURL() (string, error)
// Marshal generates a string representation of the Session for storing between requests.
Marshal() string
// Authorize should validate the data from the provider and return an access token
// that can be stored for later access to the provider.
Authorize(Provider, Params) (string, error)
}type User
type User struct {
RawData map[string]any
Provider string
Email string
Name string
FirstName string
LastName string
NickName string
Description string
UserID string
AvatarURL string
Location string
AccessToken string
AccessTokenSecret string
RefreshToken string
ExpiresAt time.Time
IDToken string
}Generated by gomarkdoc