session

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2024 License: Apache-2.0 Imports: 42 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RouteCollection                  = "/sessions"
	RouteExchangeCodeForSessionToken = RouteCollection + "/token-exchange" // #nosec G101
	RouteWhoami                      = RouteCollection + "/whoami"
	RouteSession                     = RouteCollection + "/:id"
)
View Source
const (
	AdminRouteIdentity           = "/identities"
	AdminRouteIdentitiesSessions = AdminRouteIdentity + "/:id/sessions"
	AdminRouteSessionExtendId    = RouteSession + "/extend"
)

Variables

View Source
var ErrIdentityDisabled = herodot.ErrUnauthorized.WithError("identity is disabled").WithReason("This account was disabled.")
View Source
var ErrNoSessionFound = herodot.ErrUnauthorized.WithReasonf("No valid session credentials found in the request.")

ExpandDefault expands the default fields of a session - Associated Identity

ExpandEverything expands all the fields of a session.

Functions

func RedirectOnAuthenticated

func RedirectOnAuthenticated(d interface{ config.Provider }) httprouter.Handle

func RedirectOnUnauthenticated

func RedirectOnUnauthenticated(to string) httprouter.Handle

func RespondWithJSONErrorOnAuthenticated

func RespondWithJSONErrorOnAuthenticated(h herodot.Writer, err error) httprouter.Handle

func RespondWitherrorGenericOnAuthenticated added in v0.11.0

func RespondWitherrorGenericOnAuthenticated(h herodot.Writer, err error) httprouter.Handle

func UpsertAAL added in v1.1.0

func UpsertAAL(opts *options)

UpsertAAL will update the available AAL of the identity if it was previoulsy unset. This is used to migrate identities from older versions of Ory Kratos.

Types

type AuthenticationMethod

type AuthenticationMethod struct {
	// The method used in this authenticator.
	Method identity.CredentialsType `json:"method"`

	// The AAL this method introduced.
	AAL identity.AuthenticatorAssuranceLevel `json:"aal"`

	// When the authentication challenge was completed.
	CompletedAt time.Time `json:"completed_at"`

	// OIDC or SAML provider id used for authentication
	Provider string `json:"provider,omitempty"`

	// The Organization id used for authentication
	Organization string `json:"organization,omitempty"`
}

AuthenticationMethod identifies an authentication method

A singular authenticator used during authentication / login.

swagger:model sessionAuthenticationMethod

func (*AuthenticationMethod) Scan

func (n *AuthenticationMethod) Scan(value interface{}) error

Scan implements the Scanner interface.

func (AuthenticationMethod) Value

func (n AuthenticationMethod) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type AuthenticationMethods

type AuthenticationMethods []AuthenticationMethod

List of (Used) AuthenticationMethods

A list of authenticators which were used to authenticate the session.

swagger:model sessionAuthenticationMethods

func (*AuthenticationMethods) Scan

func (n *AuthenticationMethods) Scan(value interface{}) error

Scan implements the Scanner interface.

func (AuthenticationMethods) Value

func (n AuthenticationMethods) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type CodeExchangeResponse added in v1.0.0

type CodeExchangeResponse struct {
	// The Session Token
	//
	// A session token is equivalent to a session cookie, but it can be sent in the HTTP Authorization
	// Header:
	//
	// 		Authorization: bearer ${session-token}
	//
	// The session token is only issued for API flows, not for Browser flows!
	Token string `json:"session_token,omitempty"`

	// The Session
	//
	// The session contains information about the user, the session device, and so on.
	// This is only available for API flows, not for Browser flows!
	//
	// required: true
	Session *Session `json:"session"`
}

The Response for Registration Flows via API

swagger:model successfulCodeExchangeResponse

type Device

type Device struct {
	// Device record ID
	//
	// required: true
	ID uuid.UUID `json:"id" faker:"-" db:"id"`

	// SessionID is a helper struct field for gobuffalo.pop.
	SessionID uuid.UUID `json:"-" faker:"-" db:"session_id"`

	// IPAddress of the client
	IPAddress *string `json:"ip_address" faker:"ptr_ipv4" db:"ip_address"`

	// UserAgent of the client
	UserAgent *string `json:"user_agent" faker:"-" db:"user_agent"`

	// Geo Location corresponding to the IP Address
	Location *string `json:"location" faker:"ptr_geo_location" db:"location"`

	// Time of capture
	CreatedAt time.Time `json:"-" faker:"-" db:"created_at"`

	// Last updated at
	UpdatedAt time.Time `json:"-" faker:"-" db:"updated_at"`

	NID uuid.UUID `json:"-"  faker:"-" db:"nid"`
}

Device corresponding to a Session

swagger:model sessionDevice

func (Device) TableName added in v0.11.0

func (m Device) TableName(ctx context.Context) string

type DevicePersister added in v0.13.0

type DevicePersister interface {
	CreateDevice(ctx context.Context, d *Device) error
}

type ErrAALNotSatisfied

type ErrAALNotSatisfied struct {
	*herodot.DefaultError `json:"error"`
	RedirectTo            string `json:"redirect_browser_to"`
}

ErrAALNotSatisfied is returned when an active session was found but the requested AAL is not satisfied.

func NewErrAALNotSatisfied

func NewErrAALNotSatisfied(redirectTo string) *ErrAALNotSatisfied

NewErrAALNotSatisfied creates a new ErrAALNotSatisfied.

func (*ErrAALNotSatisfied) EnhanceJSONError

func (e *ErrAALNotSatisfied) EnhanceJSONError() interface{}

func (*ErrAALNotSatisfied) PassReturnToAndLoginChallengeParameters added in v0.11.0

func (e *ErrAALNotSatisfied) PassReturnToAndLoginChallengeParameters(requestURL string) error

type ErrNoActiveSessionFound

type ErrNoActiveSessionFound struct {
	*herodot.DefaultError `json:"error"`
	// contains filtered or unexported fields
}

ErrNoActiveSessionFound is returned when no active cookie session could be found in the request.

func NewErrNoActiveSessionFound

func NewErrNoActiveSessionFound() *ErrNoActiveSessionFound

NewErrNoActiveSessionFound creates a new ErrNoActiveSessionFound

func NewErrNoCredentialsForSession added in v0.11.0

func NewErrNoCredentialsForSession() *ErrNoActiveSessionFound

NewErrNoCredentialsForSession creates a new NewErrNoCredentialsForSession

func (*ErrNoActiveSessionFound) EnhanceJSONError

func (e *ErrNoActiveSessionFound) EnhanceJSONError() interface{}

type Expandable added in v0.11.0

type Expandable = sqlxx.Expandable

Expandable controls what fields to expand for sessions.

const (
	// ExpandSessionDevices expands devices related to the session
	ExpandSessionDevices Expandable = "Devices"
	// ExpandSessionIdentity expands Identity related to the session
	ExpandSessionIdentity                  Expandable = "Identity"
	ExpandSessionIdentityRecoveryAddress   Expandable = "Identity.RecoveryAddresses"
	ExpandSessionIdentityVerifiableAddress Expandable = "Identity.VerifiableAddresses"
)

func ParseExpandable added in v0.11.0

func ParseExpandable(in string) (Expandable, bool)

type Expandables added in v0.11.0

type Expandables = sqlxx.Expandables

Expandables is a list of Expandable values.

var ExpandNothing Expandables

ExpandNothing expands nothing

type Handler

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

func NewHandler

func NewHandler(
	r handlerDependencies,
) *Handler

func (*Handler) IsAuthenticated

func (h *Handler) IsAuthenticated(wrap httprouter.Handle, onUnauthenticated httprouter.Handle) httprouter.Handle

func (*Handler) IsNotAuthenticated

func (h *Handler) IsNotAuthenticated(wrap httprouter.Handle, onAuthenticated httprouter.Handle) httprouter.Handle

func (*Handler) RegisterAdminRoutes

func (h *Handler) RegisterAdminRoutes(admin *x.RouterAdmin)

func (*Handler) RegisterPublicRoutes

func (h *Handler) RegisterPublicRoutes(public *x.RouterPublic)

type HandlerProvider

type HandlerProvider interface {
	SessionHandler() *Handler
}

type ManagementProvider

type ManagementProvider interface {
	SessionManager() Manager
}

type Manager

type Manager interface {
	// UpsertAndIssueCookie stores a session in the database and issues a cookie by calling IssueCookie.
	//
	// Also regenerates CSRF tokens due to assumed principal change.
	UpsertAndIssueCookie(context.Context, http.ResponseWriter, *http.Request, *Session) error

	// IssueCookie issues a cookie for the given session.
	//
	// Also regenerates CSRF tokens due to assumed principal change.
	IssueCookie(context.Context, http.ResponseWriter, *http.Request, *Session) error

	// RefreshCookie checks if the request uses an outdated cookie and refreshes the cookie if needed.
	RefreshCookie(context.Context, http.ResponseWriter, *http.Request, *Session) error

	// FetchFromRequest creates an HTTP session using cookies.
	FetchFromRequest(context.Context, *http.Request) (*Session, error)

	// PurgeFromRequest removes an HTTP session.
	PurgeFromRequest(context.Context, http.ResponseWriter, *http.Request) error

	// DoesSessionSatisfy answers if a session is satisfying the AAL.
	DoesSessionSatisfy(r *http.Request, sess *Session, requestedAAL string, opts ...ManagerOptions) error

	// SessionAddAuthenticationMethods adds one or more authentication method to the session.
	SessionAddAuthenticationMethods(ctx context.Context, sid uuid.UUID, methods ...AuthenticationMethod) error

	// MaybeRedirectAPICodeFlow for API+Code flows redirects the user to the return_to URL and adds the code query parameter.
	// `handled` is true if the request a redirect was written, false otherwise.
	MaybeRedirectAPICodeFlow(w http.ResponseWriter, r *http.Request, f flow.Flow, sessionID uuid.UUID, uiNode node.UiNodeGroup) (handled bool, err error)
}

Manager handles identity sessions.

type ManagerHTTP

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

func NewManagerHTTP

func NewManagerHTTP(r managerHTTPDependencies) *ManagerHTTP

func (*ManagerHTTP) DoesSessionSatisfy

func (s *ManagerHTTP) DoesSessionSatisfy(r *http.Request, sess *Session, requestedAAL string, opts ...ManagerOptions) (err error)

func (*ManagerHTTP) FetchFromRequest

func (s *ManagerHTTP) FetchFromRequest(ctx context.Context, r *http.Request) (_ *Session, err error)

func (*ManagerHTTP) IssueCookie

func (s *ManagerHTTP) IssueCookie(ctx context.Context, w http.ResponseWriter, r *http.Request, session *Session) (err error)

func (*ManagerHTTP) MaybeRedirectAPICodeFlow added in v1.0.0

func (s *ManagerHTTP) MaybeRedirectAPICodeFlow(w http.ResponseWriter, r *http.Request, f flow.Flow, sessionID uuid.UUID, uiNode node.UiNodeGroup) (handled bool, err error)

func (*ManagerHTTP) PurgeFromRequest

func (s *ManagerHTTP) PurgeFromRequest(ctx context.Context, w http.ResponseWriter, r *http.Request) (err error)

func (*ManagerHTTP) RefreshCookie added in v0.11.0

func (s *ManagerHTTP) RefreshCookie(ctx context.Context, w http.ResponseWriter, r *http.Request, session *Session) (err error)

func (*ManagerHTTP) SessionAddAuthenticationMethods

func (s *ManagerHTTP) SessionAddAuthenticationMethods(ctx context.Context, sid uuid.UUID, ams ...AuthenticationMethod) (err error)

func (*ManagerHTTP) UpsertAndIssueCookie

func (s *ManagerHTTP) UpsertAndIssueCookie(ctx context.Context, w http.ResponseWriter, r *http.Request, ss *Session) (err error)

type ManagerOptions added in v1.0.0

type ManagerOptions func(*options)

func WithRequestURL added in v1.0.0

func WithRequestURL(requestURL string) ManagerOptions

WithRequestURL passes along query parameters from the requestURL to the new URL (if any exist)

type PersistenceProvider

type PersistenceProvider interface {
	SessionPersister() Persister
}

type Persister

type Persister interface {
	GetConnection(ctx context.Context) *pop.Connection

	// GetSession retrieves a session from the store.
	GetSession(ctx context.Context, sid uuid.UUID, expandables Expandables) (*Session, error)

	// ListSessions retrieves all sessions.
	ListSessions(ctx context.Context, active *bool, paginatorOpts []keysetpagination.Option, expandables Expandables) ([]Session, int64, *keysetpagination.Paginator, error)

	// ListSessionsByIdentity retrieves sessions for an identity from the store.
	ListSessionsByIdentity(ctx context.Context, iID uuid.UUID, active *bool, page, perPage int, except uuid.UUID, expandables Expandables) ([]Session, int64, error)

	// UpsertSession inserts or updates a session into / in the store.
	UpsertSession(ctx context.Context, s *Session) error

	// DeleteSession removes a session from the store.
	DeleteSession(ctx context.Context, id uuid.UUID) error

	// DeleteSessionsByIdentity removes all active session from the store for the given identity.
	DeleteSessionsByIdentity(ctx context.Context, identity uuid.UUID) error

	// GetSessionByToken gets the session associated with the given token.
	//
	// Functionality is similar to GetSession but accepts a session token
	// instead of a session ID.
	GetSessionByToken(ctx context.Context, token string, expandables Expandables, identityExpandables identity.Expandables) (*Session, error)

	// DeleteExpiredSessions deletes sessions that expired before the given time.
	DeleteExpiredSessions(context.Context, time.Time, int) error

	// DeleteSessionByToken deletes a session associated with the given token.
	//
	// Functionality is similar to DeleteSession but accepts a session token
	// instead of a session ID.
	DeleteSessionByToken(context.Context, string) error

	// RevokeSessionByToken marks a session inactive with the given token.
	RevokeSessionByToken(ctx context.Context, token string) error

	// RevokeSessionById marks a session inactive with the specified uuid
	RevokeSessionById(ctx context.Context, sID uuid.UUID) error

	// RevokeSession marks a given session inactive.
	RevokeSession(ctx context.Context, iID, sID uuid.UUID) error

	// RevokeSessionsIdentityExcept marks all except the given session of an identity inactive. It returns the number of sessions that were revoked.
	RevokeSessionsIdentityExcept(ctx context.Context, iID, sID uuid.UUID) (int, error)
}

type Session

type Session struct {
	// Session ID
	//
	// required: true
	ID uuid.UUID `json:"id" faker:"-" db:"id"`

	// Active state. If false the session is no longer active.
	Active bool `json:"active" db:"active"`

	// The Session Expiry
	//
	// When this session expires at.
	ExpiresAt time.Time `json:"expires_at" db:"expires_at" faker:"time_type"`

	// The Session Authentication Timestamp
	//
	// When this session was authenticated at. If multi-factor authentication was used this
	// is the time when the last factor was authenticated (e.g. the TOTP code challenge was completed).
	AuthenticatedAt time.Time `json:"authenticated_at" db:"authenticated_at" faker:"time_type"`

	// AuthenticationMethod Assurance Level (AAL)
	//
	// The authenticator assurance level can be one of "aal1", "aal2", or "aal3". A higher number means that it is harder
	// for an attacker to compromise the account.
	//
	// Generally, "aal1" implies that one authentication factor was used while AAL2 implies that two factors (e.g.
	// password + TOTP) have been used.
	//
	// To learn more about these levels please head over to: https://www.ory.sh/kratos/docs/concepts/credentials
	AuthenticatorAssuranceLevel identity.AuthenticatorAssuranceLevel `faker:"len=4" db:"aal" json:"authenticator_assurance_level"`

	// Authentication Method References (AMR)
	//
	// A list of authentication methods (e.g. password, oidc, ...) used to issue this session.
	AMR AuthenticationMethods `db:"authentication_methods" json:"authentication_methods"`

	// The Session Issuance Timestamp
	//
	// When this session was issued at. Usually equal or close to `authenticated_at`.
	IssuedAt time.Time `json:"issued_at" db:"issued_at" faker:"time_type"`

	// The Logout Token
	//
	// Use this token to log out a user.
	LogoutToken string `json:"-" db:"logout_token"`

	// The Session Identity
	//
	// The identity that authenticated this session.
	//
	// If 2FA is required for the user, and the authentication process only solved the first factor, this field will be
	// null until the session has been fully authenticated with the second factor.
	Identity *identity.Identity `json:"identity" faker:"identity" db:"-" belongs_to:"identities" fk_id:"IdentityID"`

	// Devices has history of all endpoints where the session was used
	Devices []Device `json:"devices" faker:"-" has_many:"session_devices" fk_id:"session_id"`

	// IdentityID is a helper struct field for gobuffalo.pop.
	IdentityID uuid.UUID `json:"-" faker:"-" db:"identity_id"`

	// CreatedAt is a helper struct field for gobuffalo.pop.
	CreatedAt time.Time `json:"-" faker:"-" db:"created_at"`

	// UpdatedAt is a helper struct field for gobuffalo.pop.
	UpdatedAt time.Time `json:"-" faker:"-" db:"updated_at"`

	// Tokenized is the tokenized (e.g. JWT) version of the session.
	//
	// It is only set when the `tokenize` query parameter was set to a valid tokenize template during calls to `/session/whoami`.
	Tokenized string `json:"tokenized,omitempty" faker:"-" db:"-"`

	// The Session Token
	//
	// The token of this session.
	Token string    `json:"-" db:"token"`
	NID   uuid.UUID `json:"-"  faker:"-" db:"nid"`
}

A Session

swagger:model session

func NewActiveSession

func NewActiveSession(r *http.Request, i *identity.Identity, c lifespanProvider, authenticatedAt time.Time, completedLoginFor identity.CredentialsType, completedLoginAAL identity.AuthenticatorAssuranceLevel) (*Session, error)

func NewInactiveSession

func NewInactiveSession() *Session

func (*Session) Activate

func (s *Session) Activate(r *http.Request, i *identity.Identity, c lifespanProvider, authenticatedAt time.Time) error

func (*Session) AuthenticatedVia added in v1.0.0

func (s *Session) AuthenticatedVia(method identity.CredentialsType) bool

func (*Session) CanBeRefreshed

func (s *Session) CanBeRefreshed(ctx context.Context, c refreshWindowProvider) bool

func (*Session) CompletedLoginFor

func (s *Session) CompletedLoginFor(method identity.CredentialsType, aal identity.AuthenticatorAssuranceLevel)

func (*Session) CompletedLoginForMethod added in v1.1.0

func (s *Session) CompletedLoginForMethod(method AuthenticationMethod)

func (*Session) CompletedLoginForWithProvider added in v1.0.0

func (s *Session) CompletedLoginForWithProvider(method identity.CredentialsType, aal identity.AuthenticatorAssuranceLevel, providerID string, organizationID string)

func (Session) Declassified added in v0.13.0

func (s Session) Declassified() *Session

func (Session) DefaultPageToken added in v0.11.1

func (m Session) DefaultPageToken() keysetpagination.PageToken

func (*Session) IsActive

func (s *Session) IsActive() bool

func (*Session) MarshalJSON added in v0.11.0

func (s *Session) MarshalJSON() ([]byte, error)

func (Session) PageToken added in v0.11.0

func (s Session) PageToken() keysetpagination.PageToken

func (*Session) Refresh

func (s *Session) Refresh(ctx context.Context, c lifespanProvider) *Session

func (*Session) SetAuthenticatorAssuranceLevel

func (s *Session) SetAuthenticatorAssuranceLevel()

func (*Session) SetSessionDeviceInformation added in v0.13.0

func (s *Session) SetSessionDeviceInformation(r *http.Request)

func (Session) TableName

func (s Session) TableName(ctx context.Context) string

type Tokenizer added in v1.1.0

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

func NewTokenizer added in v1.1.0

func NewTokenizer(r tokenizerDependencies) *Tokenizer

func (*Tokenizer) SetNowFunc added in v1.1.0

func (s *Tokenizer) SetNowFunc(t func() time.Time)

func (*Tokenizer) TokenizeSession added in v1.1.0

func (s *Tokenizer) TokenizeSession(ctx context.Context, template string, session *Session) (err error)

type TokenizerProvider added in v1.1.0

type TokenizerProvider interface {
	SessionTokenizer() *Tokenizer
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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