Skip to content

Import path: gitlab.soludian.com/soludian/fountain/libs/social_auth

social_auth

go
import "gitlab.soludian.com/soludian/fountain/libs/social_auth"

Index

Constants

go
const KPackageName = "social_auth"

SessionName is the key used to access the session store.

go
const SessionName = "_fountain_session"

Variables

go
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.

go
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
}

go
var GetFountainInstance = Lib.GetFountainInstance

go
var GetFountainManager = Lib.GetFountainManager

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.

go
var GetProviderName = getProviderName

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

go
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()
go
var InstallFountainInstance = Lib.InstallFountainInstance

Sử 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()
go
var InstallFountainInstances = Lib.InstallFountainInstances

Truy cập thẳng tới bộ quản lý thư viện

go
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.

go
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.

go
var Store *session.Store

go
var WithConfigKey = Lib.WithConfigKey

func BeginAuthHandler

go
func BeginAuthHandler(ctx fiber.Ctx) error

BeginAuthHandler 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

go
func ContextForClient(h *http.Client) context.Context

ContextForClient provides a context for use with oauth2.

func CreateSessionStorage

go
func CreateSessionStorage()

func GetAuthURL

go
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

go
func GetContextWithProvider(req *http.Request, provider string) *http.Request

GetContextWithProvider returns a new request context containing the provider

func GetFromSession

go
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

go
func HTTPClientWithFallBack(h *http.Client) *http.Client

HTTPClientWithFallBack to be used in all fetch operations.

func Logout

go
func Logout(ctx fiber.Ctx) error

Logout invalidates a user session.

func RegisterProviders

go
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

go
func StoreInSession(ctx fiber.Ctx, key, value string) error

StoreInSession stores a specified key/value pair in the session.

type Config

go
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

go
func (conf *Config) Validate() error

type 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`.

go
type Params interface {
    Get(string) string
}

type Provider

Provider needs to be implemented for each 3rd party authentication provider e.g. Facebook, Twitter, etc...

go
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

go
func GetProvider(name string) Provider

GetProvider returns a previously created provider. If SocialAuth has not been told to use the named provider it will return an error.

type ProviderParamType

go
type ProviderParamType string

ProviderParamKey can be used as a key in context when passing in a provider

go
const ProviderParamKey ProviderParamType = "provider"

type Providers

Providers is list of known/available providers.

go
type Providers map[string]Provider

func GetProviders

go
func GetProviders() Providers

GetProviders 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.

go
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

go
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