uauth

package module
v1.0.74 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2021 License: MIT Imports: 23 Imported by: 1

README

Build Status GoDoc codecov

uauth

A simple authentication implementation usable in connection with uhttp. It supports adding/modifying user, permisions and roles. Also additional user attributes can be specified which will then be added to the user model. I have only been using this with mongoDB so many parts could be quite specific.

Documentation

Index

Constants

View Source
const (
	// Context key which allows access to a mongoClient connected to the user db
	CtxKeyUserDbClient uhttp.ContextKey = "uauth.ctxKeyUserDbClient"

	// Context key for getting a ready userService
	CtxKeyUserService uhttp.ContextKey = "uauth.ctxKeyUserService"

	// Context key for getting a ready userService
	CtxKeyRoleService uhttp.ContextKey = "uauth.ctxKeyRoleService"

	// Context key which allows access to the name of the used userDB
	CtxKeyUserDbName uhttp.ContextKey = "uauth.ctxKeyUserDbName"

	// Context key which allows access to the BCrypt secret (for generating and verifying JWT)
	CtxKeyUser uhttp.ContextKey = "uauth.ctxKeyUser"

	// Context key which allows access to a readily parsed and evaluated user-object
	CtxKeyConfig uhttp.ContextKey = "uauth.ctxKeyConfig"

	// Context key which makes the authentication method accessible
	CtxKeyAuthMethod uhttp.ContextKey = "uauth.ctxKeyAuthMethod"
)

Variables

View Source
var ErrInsufficientPermissions error = errors.New("ErrInsufficientPermissions")
View Source
var ErrInvalidRefreshToken error = errors.New("ErrInvalidRefreshToken")
View Source
var ErrInvalidUser error = errors.New("ErrInvalidUser")

Functions

func AuthBasic

func AuthBasic(wantedUsername string, wantedMd5Password string) uhttp.Middleware

func AuthBasicRequestTest added in v1.0.46

func AuthBasicRequestTest(user string, password string, method string, url string, payload io.Reader) *http.Request

Only for testing

func AuthBasicUserResolver

func AuthBasicUserResolver() func(r *http.Request) string

Resolves the userName from a request when using authBasic

func AuthHybrid

func AuthHybrid(
	jwtSecrets map[string]string,
	authBasicCredentials map[string]string,
	userModel jwt.Claims,
) uhttp.Middleware

func AuthJWT

func AuthJWT() uhttp.Middleware

Auth verify JWT token in request header ("Authorization") This method assumes the BCryptSecret already attached to the request context i.e. uauth must have been initialized with uauth.SetConfig(...)

func AuthJWTGet

func AuthJWTGet() uhttp.Middleware

Auth verify JWT token in url ("jwt=...") This method assumes the BCryptSecret already attached to the request context i.e. uauth must have been initialized with uauth.SetConfig(...)

func AuthJWTUserResolver

func AuthJWTUserResolver() func(r *http.Request) string

Resolves the userName from a request when using JWT

func CheckPermissions added in v1.0.63

func CheckPermissions(permissions ...Permission) uhttp.Middleware

Check that the user has the specified permissions

func CreateCustomRolesIfNotExist added in v1.0.46

func CreateCustomRolesIfNotExist(s *mongo.Client, dbName string, wantedRoles []Role, identifier string) error

func CreateInitialRolesIfNotExist added in v1.0.46

func CreateInitialRolesIfNotExist(s *mongo.Client, dbName string) error

CreateInitialRolesIfNotExist roles if non-existant

func CreateInitialUsersIfNotExist added in v1.0.46

func CreateInitialUsersIfNotExist(s *mongo.Client, dbName string) error

CreateInitialUsersIfNotExist creates users if non-existant

func DoRequestTest added in v1.0.46

func DoRequestTest(req *http.Request) *http.Response

Only for testing

func GenerateAccessToken added in v1.0.46

func GenerateAccessToken(
	user *User,
	config *Config,
	ctx context.Context,
) (string, error)

func GenerateRefreshToken added in v1.0.46

func GenerateRefreshToken(
	userName string,
	userService *UserService,
	device string,
	config *Config,
	ctx context.Context,
) (string, error)

func GenericUserFromRequest added in v1.0.46

func GenericUserFromRequest(r *http.Request) interface{}

func GetCustomUserFromRequestGetParams added in v1.0.46

func GetCustomUserFromRequestGetParams(r *http.Request, bCryptSecret string, userModel jwt.Claims, queryParam ...*string) (interface{}, error)

func GetCustomUserFromRequestHeaders added in v1.0.46

func GetCustomUserFromRequestHeaders(r *http.Request, bCryptSecret string, userModel jwt.Claims) (interface{}, error)

func IsAuthBasic

func IsAuthBasic(r *http.Request) bool

func IsAuthJWT

func IsAuthJWT(r *http.Request) bool

func IsAuthMethod

func IsAuthMethod(authMethod string, r *http.Request) bool

func JWTRequestGetTest added in v1.0.46

func JWTRequestGetTest(token string, method string, url string, payload io.Reader) *http.Request

Only for testing

func JWTRequestTest added in v1.0.46

func JWTRequestTest(token string, method string, url string, payload io.Reader) *http.Request

Only for testing

func MachineError added in v1.0.46

func MachineError(readable error, details error) map[string]interface{}

func SetConfig

func SetConfig(_config Config) error

func UserDB

func UserDB(r *http.Request) *mongo.Client

func UserDBName

func UserDBName(r *http.Request) string

Types

type AccessTokenModel added in v1.0.46

type AccessTokenModel struct {
	Claims jwt.MapClaims `json:"claims"` // jwt.MapClaims comes with default validation
	User   *User         `json:"user"`
}

func (AccessTokenModel) Valid added in v1.0.49

func (t AccessTokenModel) Valid() error

type Config

type Config struct {
	// uhttp instance
	UHTTP *uhttp.UHTTP

	// Token secret used for signing and verifying tokens
	BCryptSecret string

	// Connection to the mongo-database
	UserDB                 *mongo.Client
	UserDbConnectionString string
	UserDbName             string

	// Name of the token issue when tokens are created
	TokenIssuer string

	// Which roles should the package create for you
	WantedRoles []Role

	// How long will the refreshToken be valid
	RefreshTokenValidity time.Duration

	// How long will the accessToken be valid
	AccessTokenValidity time.Duration
}

func ConfigFromContext added in v1.0.50

func ConfigFromContext(ctx context.Context) (*Config, error)

func ConfigFromRequest added in v1.0.46

func ConfigFromRequest(r *http.Request) (*Config, error)

type Permission added in v1.0.46

type Permission string

Permission type

const (
	// CanReadUsers Permission for reading all users
	CanReadUsers Permission = "canReadUsers"
	// CanCreateUsers Permission for creating users
	CanCreateUsers Permission = "canCreateUsers"
	// CanUpdateUsers Permission for updating users
	CanUpdateUsers Permission = "canUpdateUsers"
	// CanDeleteUsers Permission for deleting users
	CanDeleteUsers Permission = "canDeleteUsers"
)

func PtrToPermission added in v1.0.46

func PtrToPermission(p Permission) *Permission

type RefreshTokenModel added in v1.0.46

type RefreshTokenModel struct {
	Claims   jwt.MapClaims `json:"claims"` // jwt.MapClaims comes with default validation
	UserName string        `json:"userName"`
	Device   string        `json:"device"`
}

func ParseRefreshToken added in v1.0.50

func ParseRefreshToken(refreshToken string, config *Config) (*RefreshTokenModel, *jwt.Token, error)

Parses a refreshToken into RefreshTokenModel

func ValidateRefreshToken added in v1.0.46

func ValidateRefreshToken(refreshToken string, userService *UserService, config *Config, ctx context.Context) (*RefreshTokenModel, error)

Validates the following - parse token - verify signature - verify validity - check if token is in Database and assigned to the user encoded in the token

func (RefreshTokenModel) Valid added in v1.0.49

func (t RefreshTokenModel) Valid() error

type Role added in v1.0.46

type Role struct {
	Name        string       `bson:"name" json:"name"`
	Permissions []Permission `bson:"permissions" json:"permissions"`
}

type RoleService added in v1.0.46

type RoleService struct {
	umongo.ModelService
}

func GetRoleService added in v1.0.69

func GetRoleService(r *http.Request) *RoleService

func NewRoleService added in v1.0.46

func NewRoleService(db *mongo.Client, dbName string) *RoleService

NewRoleService for creating a RoleService

func (*RoleService) CreateRole added in v1.0.46

func (s *RoleService) CreateRole(role *Role) error

CreateRole creates a user in the db

func (*RoleService) GetMultipleByName added in v1.0.46

func (s *RoleService) GetMultipleByName(roleNames []string) (*[]Role, error)

GetMultipleByName from mongoDB

func (*RoleService) List added in v1.0.46

func (s *RoleService) List() (*[]Role, error)

GetAllRoles from mongoDB

type User

type User struct {
	ID                   *primitive.ObjectID `bson:"_id" json:"id,omitempty"`
	UserName             string              `bson:"userName" json:"userName"`
	FirstName            string              `bson:"firstName,omitempty" json:"firstName,omitempty"`
	LastName             string              `bson:"lastName,omitempty" json:"lastName,omitempty"`
	Password             *string             `bson:"password,omitempty" json:"password,omitempty"`
	Roles                *[]string           `bson:"roles" json:"roles,omitempty"`
	Permissions          *[]Permission       `bson:"-" json:"permissions,omitempty"`
	AdditionalAttributes interface{}         `bson:"additionalAttributes,omitempty" json:"additionalAttributes,omitempty"`
	RefreshTokens        *[]string           `bson:"refreshTokens,omitempty" json:"refreshTokens,omitempty"`
}

func GetUserFromRequestGetParams added in v1.0.46

func GetUserFromRequestGetParams(r *http.Request, queryParam ...*string) (*User, error)

GetUserFromRequest tries to get the userModel from a request using a token attribute from the get params

func GetUserFromRequestHeaders added in v1.0.46

func GetUserFromRequestHeaders(r *http.Request) (*User, error)

GetUserFromRequestHeaders tries to get the userModel from a request using the "Authorization" header and "Bearer" scheme

func UserFromContext added in v1.0.48

func UserFromContext(ctx context.Context, additionalAttributes ...interface{}) (*User, error)

func UserFromRequest added in v1.0.46

func UserFromRequest(r *http.Request, additionalAttributes ...interface{}) (*User, error)

func ValidateAccessToken added in v1.0.46

func ValidateAccessToken(
	accessToken string,
	config *Config,
	ctx context.Context,
) (*User, error)

Validates the following - parse token - verify signature - verify validity

func (*User) CheckPassword added in v1.0.46

func (u *User) CheckPassword(plainTextPassword string) bool

CheckPassword checks a password hash of a user

func (*User) CheckPermission added in v1.0.46

func (u *User) CheckPermission(permission Permission) bool

CheckPermission check if user has a permission

func (*User) CleanForUI added in v1.0.46

func (u *User) CleanForUI(resolvedRoles *[]Role) (*User, error)

type UserService added in v1.0.46

type UserService struct {
	umongo.ModelService
	// contains filtered or unexported fields
}

UserService datastructure

func GetUserService added in v1.0.69

func GetUserService(r *http.Request) *UserService

func NewUserService added in v1.0.46

func NewUserService(db *mongo.Client, dbName string) *UserService

NewUserService for creating a UserService

func (*UserService) AddRefreshToken added in v1.0.46

func (s *UserService) AddRefreshToken(userName string, refreshToken string, ctx context.Context) error

func (*UserService) CreateUser added in v1.0.46

func (s *UserService) CreateUser(user *User) error

CreateUser creates a user in the db

func (*UserService) Delete added in v1.0.46

func (s *UserService) Delete(userID primitive.ObjectID) error

func (*UserService) DeleteExpiredRefreshTokens added in v1.0.50

func (s *UserService) DeleteExpiredRefreshTokens(userName string, ctx context.Context) error

func (*UserService) FindRefreshToken added in v1.0.46

func (s *UserService) FindRefreshToken(userName string, refreshToken string, ctx context.Context) error

func (*UserService) Get added in v1.0.46

func (s *UserService) Get(ID primitive.ObjectID) (*User, error)

func (*UserService) GetUIUserByUserNameAndCheckPassword added in v1.0.66

func (s *UserService) GetUIUserByUserNameAndCheckPassword(userName string, plainTextPassword string) (*User, error)

func (*UserService) GetUiUserByUserID added in v1.0.70

func (s *UserService) GetUiUserByUserID(ID primitive.ObjectID) (*User, error)

func (*UserService) GetUiUserByUserName added in v1.0.70

func (s *UserService) GetUiUserByUserName(userName string) (*User, error)

GetUiUserByUserName from mongoDB

func (*UserService) List added in v1.0.46

func (s *UserService) List() (*[]User, error)

func (*UserService) ListRefreshTokens added in v1.0.46

func (s *UserService) ListRefreshTokens(userName string, ctx context.Context) ([]string, error)

func (*UserService) RemoveRefreshToken added in v1.0.46

func (s *UserService) RemoveRefreshToken(userName string, refreshToken string, ctx context.Context) error

func (*UserService) Update added in v1.0.46

func (s *UserService) Update(user User) error

func (*UserService) UpdateAdditionalAttributes added in v1.0.46

func (s *UserService) UpdateAdditionalAttributes(userName string, additionalAttributes interface{}, ctx context.Context) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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