auth

package module
v0.0.0-...-ee09c68 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2020 License: MIT Imports: 16 Imported by: 4

README

Build Status codecov

auth

Authentication package for golang including middleware with generic implementation of Basic HTTP and JWT authentication schemes.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBadAuthorizationHeader = &Error{
		Code:    "AUTH-BAD-AUTHORIZATION-HEADER",
		Status:  http.StatusUnauthorized,
		Message: "Invalid authorization header",
	}
	ErrUnsupportedAuthScheme = &Error{
		Code:    "AUTH-UNSUPPORTED-SCHEME",
		Status:  http.StatusUnauthorized,
		Message: "Unsupported authentication scheme",
	}
	ErrInvalidToken = &Error{
		Code:    "AUTH-INVALID-TOKEN",
		Status:  http.StatusUnauthorized,
		Message: "User token is invalid, please re-authenticate",
	}
	ErrMissingUserID = &Error{
		Code:    "AUTH-INVALID-TOKEN",
		Status:  http.StatusUnauthorized,
		Message: "User token is missing user_id field",
	}
	ErrMissingExp = &Error{
		Code:    "AUTH-INVALID-TOKEN",
		Status:  http.StatusUnauthorized,
		Message: "User token is missing exp field",
	}
	ErrInvalidIssuer = &Error{
		Code:    "AUTH-INVALID-ISSUER",
		Status:  http.StatusUnauthorized,
		Message: "User token was issued from another host",
	}
	ErrInvalidClientIP = &Error{
		Code:    "AUTH-INVALID-CLIENT-IP",
		Status:  http.StatusUnauthorized,
		Message: "User token was issued for another IP address",
	}
	ErrNotAdmin = &Error{
		Code:    "AUTH-NOT-ADMIN",
		Status:  http.StatusForbidden,
		Message: "You need admin privileges to make this API call",
	}
	ErrMalformedContent = &Error{
		Code:    "AUTH-BAD-CONTENT",
		Status:  http.StatusBadRequest,
		Message: "Malformed content",
	}
	ErrBadCredentials = &Error{
		Code:    "AUTH-BAD-CREDENTIALS",
		Status:  http.StatusUnauthorized,
		Message: "Invalid user credentials",
	}
	ErrUserNotFound = &Error{
		Code:    "AUTH-USER-NOT-FOUND",
		Status:  http.StatusUnauthorized,
		Message: "User not found",
	}
	ErrUnsupportedContentType = &Error{
		Code:    "AUTH-UNSUPPORTED-CONTENT-TYPE",
		Status:  http.StatusUnsupportedMediaType,
		Message: "Unrecognized data format",
	}
	ErrEncodeTokenFailed = &Error{
		Code:    "AUTH-ENCODE-TOKEN-FAILED",
		Status:  http.StatusUnauthorized,
		Message: "Cannot encode user token",
	}
	ErrBadState = &Error{
		Code:    "AUTH-INTERNAL-SERVER-ERROR",
		Status:  http.StatusInternalServerError,
		Message: "Internal server error",
	}
)

Functions

func CheckTokenHandler

func CheckTokenHandler(config *Config) http.Handler

func CheckTokenHandlerFunc

func CheckTokenHandlerFunc(config *Config) http.HandlerFunc

func LoginHandler

func LoginHandler(config *Config) http.Handler

func LoginHandlerFunc

func LoginHandlerFunc(config *Config) http.HandlerFunc

func RegisterHandler

func RegisterHandler(config *Config) http.Handler

func RegisterHandlerFunc

func RegisterHandlerFunc(config *Config) http.HandlerFunc

func RequireAdmin

func RequireAdmin(config *Config) func(http.Handler) http.Handler

RequireAdmin creates auth middleware that authenticates only admin users.

func RequireUser

func RequireUser(config *Config) func(http.Handler) http.Handler

RequireUser creates auth middleware with given configuration.

func SendError

func SendError(w http.ResponseWriter, err *Error)

func SendJSON

func SendJSON(w http.ResponseWriter, result interface{})

func WithUser

func WithUser(parent context.Context, user User) context.Context

WithUser returns new context with given user

func WriteLoginResponse

func WriteLoginResponse(w http.ResponseWriter, r *http.Request, config *Config, user User)

Types

type Config

type Config struct {
	// UserStore to validate credentials
	UserStore   UserStore
	UserStoreEx UserStoreEx

	// TokenKey specifies name of token field to extract from query string
	TokenKey string

	// TokenCookie specifies cookie name to extract from cookies
	TokenCookie string

	// SingingMethod specifies JWT signing method
	SingingMethod jwt.SigningMethod

	// SecretKey is key string or function to get secret key for given JWT token
	SecretKey interface{}

	TokenExpiration time.Duration
}

Config defines options for authentication middleware.

func (*Config) SetDefaults

func (c *Config) SetDefaults() *Config

Initializes default handlers if they omitted.

type Credentials

type Credentials struct {
	UserName string `json:"username" schema:"username"`
	Password string `json:"password" schema:"password"`
}

TODO support user defined expiration

type Error

type Error struct {
	Code    string `json:"error_code,omitempty"`
	Message string `json:"error_message,omitempty"`
	Status  int    `json:"status"`
	Cause   error  `json:"cause,omitempty"`
}

func (*Error) Error

func (err *Error) Error() string

func (*Error) WithCause

func (err *Error) WithCause(cause error) *Error

type LoginResponse

type LoginResponse struct {
	Token     string    `json:"token"`
	UserID    string    `json:"user_id"`
	UserName  string    `json:"user_name"`
	ExpiredAt Timestamp `json:"expired_at"`
}

type Timestamp

type Timestamp time.Time

func (Timestamp) MarshalJSON

func (t Timestamp) MarshalJSON() ([]byte, error)

func (Timestamp) Unix

func (t Timestamp) Unix() int64

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(b []byte) error

type Token

type Token struct {
	UserID    string                 `json:"user_id"`
	UserName  string                 `json:"user_name"`
	Domain    string                 `json:"domain"`
	IssuedAt  Timestamp              `json:"issued_at"`
	ExpiredAt Timestamp              `json:"expired_at"`
	Issuer    string                 `json:"issuer"`
	ClientIP  string                 `json:"client_ip"`
	Claims    map[string]interface{} `json:"claims"` // custom claims
}

func MakeToken

func MakeToken(r *http.Request, config *Config, user User) *Token

func (*Token) Encode

func (t *Token) Encode(config *Config) (string, *Error)

type User

type User interface {
	GetID() string
	GetName() string
	GetEmail() string
	IsAdmin() bool
	GetClaims() map[string]interface{}
}

func GetContextUser

func GetContextUser(c context.Context) User

GetContextUser returns authenticated user if it presents in given context

func GetRequestUser

func GetRequestUser(r *http.Request) User

GetRequestUser returns authenticated user for given request

type UserData

type UserData struct {
	RawData           map[string]interface{}
	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
	Role              string
	Password          string
}

type UserInfo

type UserInfo struct {
	ID     string
	Name   string
	Email  string
	Admin  bool
	Claims map[string]interface{}
	Pwd    string // for testing purposes
}

func (*UserInfo) GetClaims

func (u *UserInfo) GetClaims() map[string]interface{}

func (*UserInfo) GetEmail

func (u *UserInfo) GetEmail() string

func (*UserInfo) GetID

func (u *UserInfo) GetID() string

func (*UserInfo) GetName

func (u *UserInfo) GetName() string

func (*UserInfo) IsAdmin

func (u *UserInfo) IsAdmin() bool

type UserStore

type UserStore interface {
	ValidateCredentials(ctx context.Context, username, password string) (User, error)
	FindUserByID(ctx context.Context, userID string) (User, error)
	Close()
}

func NewLdapStore

func NewLdapStore(config ldap.Config) UserStore

type UserStoreEx

type UserStoreEx interface {
	FindUserByEmail(ctx context.Context, userID string) (User, error)
	CreateUser(ctx context.Context, data UserData) (User, error)
	UpdateAccount(ctx context.Context, user User, data UserData) error
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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