auth

package
v0.0.0-...-e7c744b Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2023 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RoleAdmin  = "admin"
	RoleMember = "member"
)
View Source
const BanzaiCLIClient = "banzai-cli"
View Source
const ClusterToken auth.TokenType = "cluster"

ClusterToken is the token given to clusters to manage themselves.

View Source
const ErrOrganizationConflict = errors.Sentinel("organization already exists, but with mismatching parameters")

ErrOrganizationConflict is returned when an organization exists, but with mismatching parameters.

View Source
const PipelineSessionCookie = "_banzai_session"

PipelineSessionCookie holds the name of the Cookie Pipeline sets in the browser

View Source
const SessionCookieHTTPOnly = true

SessionCookieHTTPOnly describes if the cookies should be accessible from HTTP requests only (no JS)

View Source
const SessionCookieMaxAge = 30 * 24 * 60 * 60

SessionCookieMaxAge holds long an authenticated session should be valid in seconds

View Source
const SessionCookieName = "Pipeline session token"

SessionCookieName is the name of the token that is stored in the session cookie

View Source
const UserTokenType pkgAuth.TokenType = "user"

UserTokenType is the token type used for API sessions

View Source
const VirtualUserTokenType pkgAuth.TokenType = "hook"

VirtualUserTokenType is the token type used for API sessions by external services Used by PKE at the moment Legacy token type (used by CICD build hook originally)

Variables

View Source
var (
	Auth *AuthHandler

	// CookieDomain is the domain field for cookies
	CookieDomain string

	// Handler is the Gin authentication middleware
	Handler gin.HandlerFunc

	// InternalHandler is the Gin authentication middleware for internal clients
	InternalHandler gin.HandlerFunc
)

Init authorization nolint: gochecknoglobals

View Source
var ErrInvalidAccount = errors.New("invalid account")

ErrInvalidAccount invalid account error

Functions

func DelCookie

func DelCookie(w http.ResponseWriter, r *http.Request, name string)

DelCookie deletes a cookie.

func GetCurrentOrganizationID

func GetCurrentOrganizationID(ctx context.Context) (uint, bool)

GetCurrentOrganizationID return the user's organization ID.

func GetCurrentUserID

func GetCurrentUserID(req *http.Request) uint

GetCurrentUserID returns the current user ID.

func GetOrgNameFromVirtualUser

func GetOrgNameFromVirtualUser(virtualUser string) string

GetOrgNameFromVirtualUser returns the organization name for which the virtual user has access

func GetUserNickNameById

func GetUserNickNameById(userId uint) (userName string)

GetUserNickNameById returns user's login name

func GormErrorToStatusCode

func GormErrorToStatusCode(err error) int

GormErrorToStatusCode translates GORM errors to HTTP status codes

func Init

func Init(db *gorm.DB, config Config, tokenStore bauth.TokenStore, tokenManager TokenManager, orgSyncer OIDCOrganizationSyncer, serviceAccountService ServiceAccountService)

Init initializes the auth

func Install

func Install(engine *gin.Engine)

Install the whole OAuth and JWT Token based authn/authz mechanism to the specified Gin Engine.

func Migrate

func Migrate(db *gorm.DB, logger logrus.FieldLogger) error

Migrate executes the table migrations for the auth module.

func NewBanzaiDeregisterHandler

func NewBanzaiDeregisterHandler(db *gorm.DB, tokenStore bauth.TokenStore) func(*Context)

NewBanzaiDeregisterHandler returns a handler that deletes the user and all his/her tokens from the database

func SetCookie

func SetCookie(w http.ResponseWriter, r *http.Request, name, value string)

SetCookie writes the cookie value.

func SetCurrentOrganizationID

func SetCurrentOrganizationID(ctx context.Context, orgID uint) context.Context

SetCurrentOrganizationID returns a context with the organization ID set

func SyncOrgsForUser

func SyncOrgsForUser(
	organizationSyncer OIDCOrganizationSyncer,
	refreshTokenStore RefreshTokenStore,
	user *User,
	request *http.Request,
) error

func TLSConfigForClientAuth

func TLSConfigForClientAuth(caCertFile string) (*tls.Config, error)

Types

type AuthHandler

type AuthHandler struct {
	*AuthHandlerConfig
	SessionStorer SessionStorerInterface
	Provider      Provider
}

AuthHandler auth struct

func New

func New(config *AuthHandlerConfig) *AuthHandler

New initialize Auth

func (*AuthHandler) AuthURL

func (auth *AuthHandler) AuthURL(pth string) string

AuthURL generate URL for auth

func (*AuthHandler) GetCurrentUser

func (auth *AuthHandler) GetCurrentUser(req *http.Request) interface{}

GetCurrentUser get current user from request

func (*AuthHandler) HandlerFunc

func (auth *AuthHandler) HandlerFunc() gin.HandlerFunc

HandlerFunc generate gin.HandlerFunc for auth

func (*AuthHandler) Login

func (auth *AuthHandler) Login(w http.ResponseWriter, req *http.Request, claims *Claims) error

Login sign user in

type AuthHandlerConfig

type AuthHandlerConfig struct {
	// Default Database, which will be used in Auth when do CRUD, you can change a request's DB isntance by setting request Context's value
	DB *gorm.DB

	// Mount Auth into router with URLPrefix's value as prefix, default value is `/auth`.
	URLPrefix string

	// UserStorer is an interface that defined how to get/save user, Auth provides a default one based on AuthIdentityModel, UserModel's definition
	UserStorer BanzaiUserStorer
	// SessionStorer is an interface that defined how to encode/validate/save/destroy session data between requests, Auth provides a default method do the job, to use the default value, don't forgot to mount SessionManager's middleware into your router to save session data correctly.
	SessionStorer SessionStorerInterface
	// Redirector redirect user to a new page after registered, logged, confirmed...
	Redirector Redirector

	// LoginHandler defined behaviour when request `{Auth Prefix}/login`
	LoginHandler func(*Context, func(*Context) (*Claims, error))
	// RegisterHandler defined behaviour when request `{Auth Prefix}/register`
	RegisterHandler func(*Context, func(*Context) (*Claims, error))
	// LogoutHandler defined behaviour when request `{Auth Prefix}/logout`
	LogoutHandler func(*Context)
	// DeregisterHandler defined behaviour when request `{Auth Prefix}/deregister`
	DeregisterHandler func(*Context)

	Provider Provider
}

AuthHandlerConfig auth config

type AuthIdentity

type AuthIdentity struct {
	ID        uint      `gorm:"primary_key" json:"id"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
	BasicIdentity
}

AuthIdentity auth identity session model

type AuthorizeHandler

type AuthorizeHandler func(*Context) (*Claims, error)

type Authorizer

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

Authorizer checks if a context has permission to execute an action.

func NewAuthorizer

func NewAuthorizer(db *gorm.DB, roleSource RoleSource) Authorizer

NewAuthorizer returns a new Authorizer.

func (Authorizer) Authorize

func (a Authorizer) Authorize(ctx context.Context, action string, object interface{}) (bool, error)

Authorize authorizes a context to execute an action on an object.

type BanzaiSessionStorer

type BanzaiSessionStorer struct {
	SessionStorer
	// contains filtered or unexported fields
}

BanzaiSessionStorer stores the banzai session

func (*BanzaiSessionStorer) Update

func (sessionStorer *BanzaiSessionStorer) Update(w http.ResponseWriter, req *http.Request, claims *Claims) error

Update updates the BanzaiSessionStorer

type BanzaiUserStorer

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

BanzaiUserStorer struct

func (BanzaiUserStorer) Get

func (bus BanzaiUserStorer) Get(Claims *Claims, context *Context) (user interface{}, err error)

func (BanzaiUserStorer) Save

func (bus BanzaiUserStorer) Save(schema *Schema, authCtx *Context) (user interface{}, userID string, err error)

Save differs from the default UserStorer.Save() in that it extracts Token and Login

func (BanzaiUserStorer) Update

func (bus BanzaiUserStorer) Update(schema *Schema, authCtx *Context) (err error)

Update updates the user's group mmeberships from the OIDC ID token at every login

type BasicIdentity

type BasicIdentity struct {
	Provider          string // phone, email, wechat, github...
	UID               string `gorm:"column:uid"`
	EncryptedPassword string
	UserID            string
	ConfirmedAt       *time.Time
}

func (BasicIdentity) ToClaims

func (basic BasicIdentity) ToClaims() *Claims

ToClaims convert to auth Claims

type CLIConfig

type CLIConfig struct {
	ClientID string
}

CLIConfig contains cli auth configuration.

func (CLIConfig) Validate

func (c CLIConfig) Validate() error

Validate validates the configuration.

type Claims

type Claims struct {
	Provider                         string         `json:"provider,omitempty"`
	UserID                           string         `json:"userid,omitempty"`
	LastLoginAt                      *time.Time     `json:"last_login,omitempty"`
	LastActiveAt                     *time.Time     `json:"last_active,omitempty"`
	LongestDistractionSinceLastLogin *time.Duration `json:"distraction_time,omitempty"`
	jwt.Claims
}

Claims auth claims

func (*Claims) ToClaims

func (claims *Claims) ToClaims() *Claims

ToClaims implement ClaimerInterface

type ClusterTokenGenerator

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

ClusterTokenGenerator looks up or generates and stores a token for a cluster.

func NewClusterTokenGenerator

func NewClusterTokenGenerator(tokenManager TokenManager, tokenStore bauth.TokenStore) ClusterTokenGenerator

NewClusterTokenGenerator returns a new ClusterTokenGenerator.

func (ClusterTokenGenerator) GenerateClusterToken

func (g ClusterTokenGenerator) GenerateClusterToken(orgID uint, clusterID uint) (string, string, error)

GenerateClusterToken looks up or generates and stores a token for a cluster.

type Config

type Config struct {
	OIDC        OIDCConfig
	CLI         CLIConfig
	RedirectURL RedirectURLConfig
	Cookie      CookieConfig
	Token       TokenConfig
	Role        RoleConfig
}

Config contains auth configuration.

func (*Config) Process

func (c *Config) Process() error

Process post-processes the configuration after loading (before validation).

func (Config) Validate

func (c Config) Validate() error

Validate validates the configuration.

type Context

type Context struct {
	Auth    *AuthHandler
	Claims  *Claims
	Request *http.Request
	Writer  http.ResponseWriter
}

Context context

type ContextKey

type ContextKey string
const (
	// CurrentOrganization denotes the current organization in context
	CurrentOrganization ContextKey = "org"

	// CurrentUser denotes the current user in context
	CurrentUser ContextKey = "current_user"

	// SignUp is present if the current request is a signing up
	SignUp ContextKey = "signUp"

	// OAuthRefreshTokenID denotes the tokenID for the user's OAuth refresh token, there can be only one
	OAuthRefreshTokenID = "oauth_refresh"
)

type CookieConfig

type CookieConfig struct {
	Secure    bool
	Domain    string
	SetDomain bool
}

CookieConfig contains auth cookie configuration.

func (CookieConfig) Validate

func (c CookieConfig) Validate() error

Validate validates the configuration.

type EventBus

type EventBus interface {
	// Publish sends an event to the underlying message bus.
	Publish(ctx context.Context, event interface{}) error
}

EventBus is a generic event bus.

type IDTokenClaims

type IDTokenClaims struct {
	Subject           string            `json:"sub"`
	Name              string            `json:"name"`
	PreferredUsername string            `json:"preferred_username"`
	Email             string            `json:"email"`
	Verified          bool              `json:"email_verified"`
	Groups            []string          `json:"groups"`
	FederatedClaims   map[string]string `json:"federated_claims"`
}

type Logger

type Logger = common.Logger

Logger is the fundamental interface for all log operations.

type OIDCConfig

type OIDCConfig struct {
	Issuer       string
	Insecure     bool
	ClientID     string
	ClientSecret string
}

OIDCConfig contains OIDC auth configuration.

func (OIDCConfig) Validate

func (c OIDCConfig) Validate() error

Validate validates the configuration.

type OIDCOrganizationSyncer

type OIDCOrganizationSyncer interface {
	SyncOrganizations(ctx gocontext.Context, user User, idTokenClaims *IDTokenClaims) error
}

OIDCOrganizationSyncer synchronizes organizations of a user from an OIDC ID token.

func NewOIDCOrganizationSyncer

func NewOIDCOrganizationSyncer(organizationSyncer OrganizationSyncer, roleBinder RoleBinder) OIDCOrganizationSyncer

NewOIDCOrganizationSyncer returns a new OIDCOrganizationSyncer.

type OIDCProvider

type OIDCProvider struct {
	*OIDCProviderConfig
	// contains filtered or unexported fields
}

OIDCProvider provide login with OIDC auth method

func (OIDCProvider) Callback

func (provider OIDCProvider) Callback(context *Context)

Callback implement Callback with dex provider

func (OIDCProvider) Deregister

func (provider OIDCProvider) Deregister(context *Context)

Deregister implemented deregister with dex provider

func (OIDCProvider) Login

func (provider OIDCProvider) Login(context *Context)

Login implemented login with dex provider

func (OIDCProvider) Logout

func (OIDCProvider) Logout(context *Context)

Logout implemented logout with dex provider

func (OIDCProvider) OAuthConfig

func (provider OIDCProvider) OAuthConfig(context *Context) *oauth2.Config

OAuthConfig return oauth config based on configuration

func (OIDCProvider) RedeemRefreshToken

func (provider OIDCProvider) RedeemRefreshToken(context *Context, refreshToken string) (*IDTokenClaims, *oauth2.Token, error)

RedeemRefreshToken plays an OAuth redeem refresh token flow https://www.oauth.com/oauth2-servers/access-tokens/refreshing-access-tokens/

func (OIDCProvider) Register

func (provider OIDCProvider) Register(context *Context)

Register implemented register with dex provider

func (OIDCProvider) ServeHTTP

func (OIDCProvider) ServeHTTP(*Context)

ServeHTTP implement ServeHTTP with dex provider

type OIDCProviderConfig

type OIDCProviderConfig struct {
	PublicClientID     string
	ClientID           string
	ClientSecret       string
	IssuerURL          string
	InsecureSkipVerify bool
	RedirectURL        string
	Scopes             []string
	AuthorizeHandler   AuthorizeHandler
}

OIDCProviderConfig holds the oidc configuration parameters

type Organization

type Organization struct {
	ID             uint      `gorm:"primary_key" json:"id"`
	CreatedAt      time.Time `json:"createdAt"`
	UpdatedAt      time.Time `json:"updatedAt"`
	Name           string    `gorm:"unique;not null" json:"name"`
	Provider       string    `gorm:"not null" json:"provider"`
	NormalizedName string    `gorm:"unique" json:"normalizedName"`
	Users          []User    `gorm:"many2many:user_organizations" json:"users,omitempty"`
	Role           string    `json:"-" gorm:"-"` // Used only internally
}

Organization represents a unit of users and resources.

func GetCurrentOrganization

func GetCurrentOrganization(req *http.Request) *Organization

GetCurrentOrganization return the user's organization

func GetOrganizationById

func GetOrganizationById(orgID uint) (*Organization, error)

GetOrganizationById returns an organization from database by ID

func (*Organization) BeforeCreate

func (o *Organization) BeforeCreate(tx *gorm.DB) error

func (*Organization) IDString

func (o *Organization) IDString() string

IDString returns the ID as string.

type OrganizationCreated

type OrganizationCreated struct {
	// ID is the created organization ID.
	ID uint

	// UserID is the ID of the user whose login triggered the organization being created.
	UserID uint
}

OrganizationCreated event is triggered when an organization is created in the system.

type OrganizationEventDispatcher

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

OrganizationEventDispatcher dispatches events through the underlying generic event bus.

func NewOrganizationEventDispatcher

func NewOrganizationEventDispatcher(bus EventBus) OrganizationEventDispatcher

NewOrganizationEventDispatcher returns a new OrganizationEventDispatcher instance.

func (OrganizationEventDispatcher) OrganizationCreated

func (d OrganizationEventDispatcher) OrganizationCreated(ctx context.Context, event OrganizationCreated) error

OrganizationCreated dispatches a(n) OrganizationCreated event.

type OrganizationEvents

type OrganizationEvents interface {
	// OrganizationCreated dispatches an OrganizationCreated event.
	OrganizationCreated(ctx context.Context, event OrganizationCreated) error
}

OrganizationEvents dispatches organization events.

type OrganizationStore

type OrganizationStore interface {
	// EnsureOrganizationExists ensures that an organization exists.
	// If one already exists with the same parameters it succeeds.
	// If one already exists with different parameters (eg. different provider),
	// it returns with an ErrOrganizationConflict error.
	// The function returns whether an organization was created or not, as well as it's ID.
	EnsureOrganizationExists(ctx context.Context, name string, provider string) (bool, uint, error)

	// GetOrganizationMembershipsOf returns the list of organization memberships for a user.
	GetOrganizationMembershipsOf(ctx context.Context, userID uint) ([]UserOrganization, error)

	// RemoveUserFromOrganization removes a user from an organization.
	RemoveUserFromOrganization(ctx context.Context, organizationID uint, userID uint) error

	// ApplyUserMembership ensures that a user is a member of an organization with the necessary role.
	ApplyUserMembership(ctx context.Context, organizationID uint, userID uint, role string) error
}

OrganizationStore is a persistence layer for organizations.

type OrganizationSyncer

type OrganizationSyncer interface {
	SyncOrganizations(ctx context.Context, user User, upstreamMemberships []UpstreamOrganizationMembership) error
}

OrganizationSyncer synchronizes organization membership for a user. It creates missing organizations, adds user to and removes from existing organizations, updates organization role. Note: it never deletes organizations, only creates them if they are missing.

func NewOrganizationSyncer

func NewOrganizationSyncer(store OrganizationStore, events OrganizationEvents, logger Logger) OrganizationSyncer

NewOrganizationSyncer returns a new OrganizationSyncer.

type Provider

type Provider interface {
	Login(*Context)
	Logout(*Context)
	Register(*Context)
	Deregister(*Context)
	Callback(*Context)
	ServeHTTP(*Context)
}

Provider define Provider interface

type RbacEnforcer

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

RbacEnforcer makes authorization decisions based on user roles.

func NewRbacEnforcer

func NewRbacEnforcer(roleSource RoleSource, serviceAccountService ServiceAccountService, logger Logger) RbacEnforcer

NewRbacEnforcer returns a new RbacEnforcer.

func (RbacEnforcer) Enforce

func (e RbacEnforcer) Enforce(org *Organization, user *User, path, method string, query url.Values) (bool, error)

Enforce makes authorization decisions.

type RedirectURLConfig

type RedirectURLConfig struct {
	Login  string
	Signup string
}

RedirectURLConfig contains the URLs the user is redirected to after certain authentication events.

func (*RedirectURLConfig) Process

func (c *RedirectURLConfig) Process() error

Process post-processes the configuration after loading (before validation).

func (RedirectURLConfig) Validate

func (c RedirectURLConfig) Validate() error

Validate validates the configuration.

type Redirector

type Redirector interface {
	Redirect(http.ResponseWriter, *http.Request, string)
}

type RefreshTokenStore

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

RefreshTokenStore stores refresh tokens in the underlying store.

func NewRefreshTokenStore

func NewRefreshTokenStore(tokenStore auth.TokenStore) RefreshTokenStore

NewRefreshTokenStore returns a new RefreshTokenStore.

func (RefreshTokenStore) GetRefreshToken

func (s RefreshTokenStore) GetRefreshToken(userID string) (string, error)

GetRefreshToken returns the refresh token from the token store.

func (RefreshTokenStore) SaveRefreshToken

func (s RefreshTokenStore) SaveRefreshToken(userID string, refreshToken string) error

SaveRefreshToken saves the refresh token in the token store.

type RoleBinder

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

RoleBinder binds groups from an OIDC ID token to Pipeline roles.

func NewRoleBinder

func NewRoleBinder(defaultRole string, rawBindings map[string]string) (RoleBinder, error)

NewRoleBinder returns a new RoleBinder.

func (RoleBinder) BindRole

func (rb RoleBinder) BindRole(groups []string) string

BindRole binds the highest possible role to the list of provided groups.

type RoleConfig

type RoleConfig struct {
	Default string
	Binding map[string]string
}

RoleConfig contains role based authorization configuration.

func (RoleConfig) Validate

func (c RoleConfig) Validate() error

Validate validates the configuration.

type RoleSource

type RoleSource interface {
	// FindUserRole returns the user's role in a given organization.
	// Returns false as the second parameter if the user is not a member of the organization.
	FindUserRole(ctx context.Context, organizationID uint, userID uint) (string, bool, error)
}

RoleSource returns the user's role in a given organization.

type Schema

type Schema struct {
	Provider string
	UID      string

	Name      string
	Email     string
	FirstName string
	LastName  string
	Location  string
	Image     string
	Phone     string
	URL       string

	RawInfo interface{}
}

type ServiceAccountService

type ServiceAccountService interface {
	ExtractServiceAccount(*http.Request) *User
	IsAdminServiceAccount(*User) bool
}

func NewServiceAccountService

func NewServiceAccountService() ServiceAccountService

type SessionManager

type SessionManager struct {
	SessionName string
	Store       sessions.Store
}

SessionManager session manager struct for gorilla/sessions

func NewSessionManager

func NewSessionManager(sessionName string, store sessions.Store) *SessionManager

NewSessionManager initialize session manager based on gorilla/sessions

func (SessionManager) Add

func (sm SessionManager) Add(w http.ResponseWriter, req *http.Request, key string, value string) error

Add value to session data, if value is not string, will marshal it into JSON encoding and save it into session data.

func (SessionManager) Get

func (sm SessionManager) Get(req *http.Request, key string) string

Get value from session data

type SessionManagerInterface

type SessionManagerInterface interface {
	// Add value to session data, if value is not string, will marshal it into JSON encoding and save it into session data.
	Add(w http.ResponseWriter, req *http.Request, key, value string) error
	// Get value from session data
	Get(req *http.Request, key string) string
}

SessionManagerInterface session manager interface

type SessionStorer

type SessionStorer struct {
	SessionName    string
	SigningMethod  jose.SignatureAlgorithm
	SignedString   string
	SessionManager SessionManagerInterface
}

SessionStorer default session storer

func (*SessionStorer) Get

func (sessionStorer *SessionStorer) Get(req *http.Request) (*Claims, error)

Get get claims from request

func (*SessionStorer) SignedToken

func (sessionStorer *SessionStorer) SignedToken(claims *Claims) (string, error)

SignedToken generate signed token with Claims

func (*SessionStorer) Update

func (sessionStorer *SessionStorer) Update(w http.ResponseWriter, req *http.Request, claims *Claims) error

Update update claims with session manager

func (*SessionStorer) ValidateClaims

func (sessionStorer *SessionStorer) ValidateClaims(tokenString string) (*Claims, error)

ValidateClaims validate auth token

type SessionStorerInterface

type SessionStorerInterface interface {
	// Get get claims from request
	Get(req *http.Request) (*Claims, error)
	// Update update claims with session manager
	Update(w http.ResponseWriter, req *http.Request, claims *Claims) error

	// SignedToken generate signed token with Claims
	SignedToken(claims *Claims) (string, error)
	// ValidateClaims validate auth token
	ValidateClaims(tokenString string) (*Claims, error)
}

SessionStorerInterface session storer interface for Auth

type TokenConfig

type TokenConfig struct {
	SigningKey string
	Issuer     string
	Audience   string
}

TokenConfig contains auth configuration.

func (TokenConfig) Validate

func (c TokenConfig) Validate() error

Validate validates the configuration.

type TokenManager

type TokenManager interface {
	// GenerateToken generates a token and stores it in the token store.
	GenerateToken(
		sub string,
		expiresAt time.Time,
		tokenType auth.TokenType,
		tokenText string,
		tokenName string,
		storeSecret bool,
	) (string, string, error)
}

TokenManager manages tokens.

type UpstreamOrganization

type UpstreamOrganization struct {
	Name     string
	Provider string
}

UpstreamOrganization represents an organization from the upstream authentication source.

type UpstreamOrganizationMembership

type UpstreamOrganizationMembership struct {
	Organization UpstreamOrganization
	Role         string
}

UpstreamOrganizationMembership represents an organization membership of a user from the upstream authentication source.

type User

type User struct {
	ID             uint           `gorm:"primary_key" json:"id"`
	CreatedAt      *time.Time     `json:"createdAt,omitempty"`
	UpdatedAt      *time.Time     `json:"updatedAt,omitempty"`
	Name           string         `form:"name" json:"name,omitempty"`
	Email          string         `form:"email" json:"email,omitempty"`
	Login          string         `gorm:"unique;not null" form:"login" json:"login"`
	Image          string         `form:"image" json:"image,omitempty"`
	Organizations  []Organization `gorm:"many2many:user_organizations" json:"organizations,omitempty"`
	Virtual        bool           `json:"-" gorm:"-"` // Used only internally
	APIToken       string         `json:"-" gorm:"-"` // Used only internally
	ServiceAccount bool           `json:"-" gorm:"-"` // Used only internally
}

User struct

func GetCurrentUser

func GetCurrentUser(req *http.Request) *User

GetCurrentUser returns the current user

func GetUserById

func GetUserById(userId uint) (*User, error)

GetUserById returns user

func (*User) IDString

func (user *User) IDString() string

IDString returns the ID as string

type UserExtractor

type UserExtractor struct{}

func (UserExtractor) GetUserID

func (e UserExtractor) GetUserID(ctx context.Context) (uint, bool)

func (UserExtractor) GetUserLogin

func (e UserExtractor) GetUserLogin(ctx context.Context) (string, bool)

type UserOrganization

type UserOrganization struct {
	User   User
	UserID uint

	Organization   Organization
	OrganizationID uint

	Role string `gorm:"default:'member'"`
}

UserOrganization describes a user organization membership.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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