auth

package
v0.0.0-...-d4303dc Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 30, 2024 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const AuthCookieKey = "GLRY_JWT"

AuthCookieKey is the key used to store the auth token in the cookie

View Source
const NoncePrepend = "Gallery uses this cryptographic signature in place of a password: "

NoncePrepend is prepended to a nonce to make our default signing message

View Source
const RefreshCookieKey = "GLRY_REFRESH_JWT"

RefreshCookieKey is the key used to store the refresh token in the cookie

Variables

View Source
var ErrEmailAlreadyUsed = errors.New("email already in use")
View Source
var ErrEmailUnverified = errors.New("The email address you provided is unverified. Login with QR code instead, or verify your email at gallery.so/settings.")

TODO: Figure out a better scheme for handling user-facing errors

View Source
var ErrInvalidJWT = errors.New("invalid or expired auth token")

ErrInvalidJWT is returned when the JWT is invalid

View Source
var ErrInvalidMagicLink = errors.New("invalid magic link")
View Source
var ErrMessageDoesNotContainNonce = errors.New("message does not contain nonce")

ErrMessageDoesNotContainNonce is returned when a nonce authenticator's message does not contain its nonce

View Source
var ErrNoCookie = errors.New("no jwt passed as cookie")

ErrNoCookie is returned when there is no JWT in the request

View Source
var ErrNonceMismatch = errors.New("incorrect nonce input")

ErrNonceMismatch is returned when the nonce does not match the expected nonce

View Source
var ErrSessionInvalidated = errors.New("session has been invalidated")
View Source
var ErrSignatureInvalid = errors.New("signature invalid")

ErrSignatureInvalid is returned when the signed nonce's signature is invalid

Functions

func ConsumeAuthNonce

func ConsumeAuthNonce(ctx context.Context, queries *db.Queries, nonce string) error

func ContinueSession

func ContinueSession(c *gin.Context, queries *db.Queries, authRefreshCache *redis.Cache) error

ContinueSession checks the request cookies for an existing auth session and continues it if possible. If the request is for an expired or invalid session, the user will be logged out. After calling ContinueSession, the current auth state can be queried with functions like GetUserAuthedFromCtx(), GetUserIDFromCtx(), etc.

func EndSession

func EndSession(c *gin.Context, queries *db.Queries, authRefreshCache *redis.Cache)

EndSession invalidates the current session and clears the user's cookies

func ForceAuthTokenRefresh

func ForceAuthTokenRefresh(ctx context.Context, authRefreshCache *redis.Cache, userID persist.DBID) error

ForceAuthTokenRefresh should be called whenever something happens that would result in existing auth tokens being out-of-date. For example, when a user's roles are changed, or a user logs out of a session, existing otherwise-valid auth tokens should be refreshed so they have the latest session state.

func GenerateAuthNonce

func GenerateAuthNonce(ctx context.Context, queries *db.Queries) (nonce string, message string, err error)

func GenerateAuthToken

func GenerateAuthToken(ctx context.Context, userID persist.DBID, sessionID persist.DBID, refreshID string, roles []persist.Role) (string, error)

func GenerateEmailVerificationToken

func GenerateEmailVerificationToken(ctx context.Context, userID persist.DBID, email string) (string, error)

func GenerateNonce

func GenerateNonce() (string, error)

GenerateNonce generates a random nonce to be signed by a wallet

func GenerateOneTimeLoginToken

func GenerateOneTimeLoginToken(ctx context.Context, userID persist.DBID, source string, validFor time.Duration) (string, error)

func GenerateRefreshToken

func GenerateRefreshToken(ctx context.Context, ID string, parentID string, userID persist.DBID, sessionID persist.DBID) (string, time.Time, error)

func GetAuthErrorFromCtx

func GetAuthErrorFromCtx(c *gin.Context) error

func GetRolesFromCtx

func GetRolesFromCtx(c *gin.Context) []persist.Role

func GetSessionIDFromCtx

func GetSessionIDFromCtx(c *gin.Context) persist.DBID

GetSessionIDFromCtx returns the session ID from the context

func GetUserAuthedFromCtx

func GetUserAuthedFromCtx(c *gin.Context) bool

GetUserAuthedFromCtx queries the context to determine whether the user is authenticated

func GetUserIDFromCtx

func GetUserIDFromCtx(c *gin.Context) persist.DBID

GetUserIDFromCtx returns the user ID from the context

func Login

func Login(ctx context.Context, queries *db.Queries, authenticator Authenticator) (persist.DBID, error)

Login logs in a user with a given authentication scheme

func Logout

func Logout(ctx context.Context, queries *db.Queries, authRefreshCache *redis.Cache)

func NewMagicLinkClient

func NewMagicLinkClient() *magicclient.API

func ParseEmailVerificationToken

func ParseEmailVerificationToken(ctx context.Context, token string) (persist.DBID, string, error)

func ParseOneTimeLoginToken

func ParseOneTimeLoginToken(ctx context.Context, token string) (persist.DBID, time.Time, error)

func RolesByUserID

func RolesByUserID(ctx context.Context, queries *db.Queries, userID persist.DBID) ([]persist.Role, error)

func ScrubEventCookies

func ScrubEventCookies(event *sentry.Event, hint *sentry.EventHint) *sentry.Event

func SetAuthContext

func SetAuthContext(scope *sentry.Scope, gc *gin.Context)

func StartSession

func StartSession(c *gin.Context, queries *db.Queries, userID persist.DBID) error

StartSession begins a new session for the specified user. After calling StartSession, the current auth state can be queried with functions like GetUserAuthedFromCtx(), GetUserIDFromCtx(), etc.

Types

type AuthResult

type AuthResult struct {
	User      *db.User
	Addresses []AuthenticatedAddress
	Email     *persist.Email
	PrivyDID  *string
}

func (*AuthResult) GetAuthenticatedAddress

func (a *AuthResult) GetAuthenticatedAddress(chainAddress persist.ChainAddress) (AuthenticatedAddress, bool)

type AuthTokenClaims

type AuthTokenClaims struct {
	UserID    persist.DBID   `json:"user_id"`
	SessionID persist.DBID   `json:"session_id"` // The session this auth token belongs to
	RefreshID string         `json:"refresh_id"` // The refresh token this auth token was generated from
	Roles     []persist.Role `json:"roles"`
	GalleryClaims
}

func ParseAuthToken

func ParseAuthToken(ctx context.Context, token string) (AuthTokenClaims, error)

type AuthenticatedAddress

type AuthenticatedAddress struct {
	// A ChainAddress that has had its ownership successfully verified by an authenticator
	ChainAddress persist.ChainAddress

	// The WalletType of the verified ChainAddress
	WalletType persist.WalletType
}

AuthenticatedAddress contains address information that has been successfully verified by an authenticator.

type Authenticator

type Authenticator interface {
	// GetDescription returns information about the authenticator for error and logging purposes.
	// NOTE: GetDescription should NOT include any sensitive data (passwords, auth tokens, etc)
	// that we wouldn't want showing up in logs!
	GetDescription() string

	Authenticate(context.Context) (*AuthResult, error)
}

type ErrAuthenticationFailed

type ErrAuthenticationFailed struct {
	WrappedErr error
}

func (ErrAuthenticationFailed) Error

func (e ErrAuthenticationFailed) Error() string

func (ErrAuthenticationFailed) Unwrap

func (e ErrAuthenticationFailed) Unwrap() error

type ErrDoesNotOwnRequiredNFT

type ErrDoesNotOwnRequiredNFT struct {
	// contains filtered or unexported fields
}

func (ErrDoesNotOwnRequiredNFT) Error

func (e ErrDoesNotOwnRequiredNFT) Error() string

type ErrNonceNotFound

type ErrNonceNotFound struct {
	L1ChainAddress persist.L1ChainAddress
}

func (ErrNonceNotFound) Error

func (e ErrNonceNotFound) Error() string

type ErrSignatureVerificationFailed

type ErrSignatureVerificationFailed struct {
	WrappedErr error
}

func (ErrSignatureVerificationFailed) Error

func (ErrSignatureVerificationFailed) Unwrap

type GalleryClaims

type GalleryClaims struct {
	TokenType TokenType `json:"token_type"`
	jwt.RegisteredClaims
}

type MagicLinkAuthenticator

type MagicLinkAuthenticator struct {
	Token       token.Token
	MagicClient *magicclient.API
	Queries     *db.Queries
}

func (MagicLinkAuthenticator) Authenticate

func (e MagicLinkAuthenticator) Authenticate(pCtx context.Context) (*AuthResult, error)

func (MagicLinkAuthenticator) GetDescription

func (e MagicLinkAuthenticator) GetDescription() string

type NeynarAuthenticator

type NeynarAuthenticator struct {
	CustodyAuth    NonceAuthenticator
	PrimaryAddress *persist.ChainPubKey
	NeynarClient   *farcaster.NeynarAPI
	Queries        *db.Queries
}

func (NeynarAuthenticator) Authenticate

func (e NeynarAuthenticator) Authenticate(ctx context.Context) (*AuthResult, error)

func (NeynarAuthenticator) GetDescription

func (e NeynarAuthenticator) GetDescription() string

type NonceAuthenticator

type NonceAuthenticator struct {
	ChainPubKey        persist.ChainPubKey
	Nonce              string
	Message            string
	Signature          string
	WalletType         persist.WalletType
	EthClient          *ethclient.Client
	MultichainProvider *multichain.Provider
	Queries            *db.Queries
}

func (NonceAuthenticator) Authenticate

func (e NonceAuthenticator) Authenticate(ctx context.Context) (*AuthResult, error)

func (NonceAuthenticator) GetDescription

func (e NonceAuthenticator) GetDescription() string

type OneTimeLoginTokenAuthenticator

type OneTimeLoginTokenAuthenticator struct {
	ConsumedTokenCache *redis.Cache
	Queries            *db.Queries
	LoginToken         string
}

func (OneTimeLoginTokenAuthenticator) Authenticate

func (OneTimeLoginTokenAuthenticator) GetDescription

func (a OneTimeLoginTokenAuthenticator) GetDescription() string

type RefreshTokenClaims

type RefreshTokenClaims struct {
	ID        string       `json:"id"`        // The refresh token's ID
	ParentID  string       `json:"parent_id"` // The parent refresh token this child refresh token was generated from
	UserID    persist.DBID `json:"user_id"`
	SessionID persist.DBID `json:"session_id"` // The session this refresh token belongs to
	GalleryClaims
}

func ParseRefreshToken

func ParseRefreshToken(ctx context.Context, token string) (RefreshTokenClaims, error)

type TokenType

type TokenType string
const (
	TokenTypeAuth              TokenType = "auth"
	TokenTypeRefresh           TokenType = "refresh"
	TokenTypeOneTimeLogin      TokenType = "one_time_login"
	TokenTypeEmailVerification TokenType = "email_verification"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL