access

package module
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2025 License: MIT Imports: 17 Imported by: 0

README

��# Package "Access"

[!NOTE] This package use "github.com/golang-jwt/jwt/v4", "golang.org/x/crypto", "github.com/go-chi/chi/v5" for routing endpoints, and "github.com/stretchr/testify" for tests.

Provides authentication and authorization of users in the system and transmits the URL depending on the user's role.

Work start

For correct work, you need to create 2 .yml files:
  1. In the first file write jwt characteristics:
  • JWT:start secret, rotation period, TTL for jwt-secret, how many old kays to keep in memory;
  • System path for your file with permisiion map;
  • Cost (number of iterarion) for hash-function;
  • Cache: token TTL, password TTL and permission TTL.
  1. In the second file write your permission map for every role of user:
  • Name of the role;
  • Can this role interact with own records only;
  • All avaliable sections for this role (name, URL, can this role read and/or write this section).

Examples of filling .yml are given in the tests.

Documentation

Index

Constants

View Source
const (
	UserClaimsKey contextKey = "GOMusic_contextKey"
)

Variables

This section is empty.

Functions

func NewCache

func NewCache(ttl time.Duration) *memoryCache

Types

type Authenticator

type Authenticator struct {
	JwtService     *JWTService
	PasswordHasher *PasswordHasher

	// Кэши
	TokenCache *memoryCache
	// contains filtered or unexported fields
}

func NewAuthenticator

func NewAuthenticator(configPath string) (*Authenticator, error)

func (*Authenticator) CheckOwnRecords

func (a *Authenticator) CheckOwnRecords(next http.Handler) http.Handler

func (*Authenticator) CheckPermissions

func (a *Authenticator) CheckPermissions(next http.Handler) http.Handler

func (*Authenticator) LoadPermissions

func (a *Authenticator) LoadPermissions(path string) error

type Config

type Config struct {
	JWT struct {
		Secret         string        `yaml:"secret"`           // Начальный (резервный) JWT-secret
		RotationPeriod time.Duration `yaml:"rotation_period"`  // Период ротации ключей
		TTL            time.Duration `yaml:"ttl"`              // Время жизни токена
		OldKeysToKeep  int           `yaml:"old_keys_to_keep"` // Сколько старых ключей оставлять
	} `yaml:"jwt"`

	Permissions struct {
		Path string `yaml:"path"` //Путь до файла с мапой ролей и их разрешениями
	} `yaml:"permissions"`

	Password struct {
		Cost int `yaml:"cost"` //Сложность хэширования пароля, оптимальное значение - 12. Больше информации в тестах
	} `yaml:"password"`

	Cache struct {
		TokenTTL      time.Duration `yaml:"token_ttl"`
		PasswordTTL   time.Duration `yaml:"password_ttl"`
		PermissionTTL time.Duration `yaml:"permission_ttl"`
	} `yaml:"cache"`
}

func LoadConfig

func LoadConfig(path string) (*Config, error)

type JWTService

type JWTService struct {
	CurrentSecret []byte
	OldSecrets    [][]byte
	// contains filtered or unexported fields
}

func NewJWTService

func NewJWTService(secret string, cfg *Config, auth *Authenticator) *JWTService

func (*JWTService) GenerateJWT

func (j *JWTService) GenerateJWT(userID int, username, role string) (string, error)

func (*JWTService) ParseJWT

func (j *JWTService) ParseJWT(tokenString string) (jwt.MapClaims, error)

func (*JWTService) RotateSecret

func (j *JWTService) RotateSecret(newSecret string)

type PasswordHasher

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

func NewPasswordHasher

func NewPasswordHasher(cost int, auth *Authenticator) *PasswordHasher

func (*PasswordHasher) CheckPasswordHash

func (p *PasswordHasher) CheckPasswordHash(password, hash string) bool

func (*PasswordHasher) HashPassword

func (p *PasswordHasher) HashPassword(password string) (string, error)

type PermissionsConfig

type PermissionsConfig struct {
	Roles map[string]RolePermissions `yaml:"roles"`
}

func GetPermissions

func GetPermissions(path string) (*PermissionsConfig, error)

func LoadPermissions

func LoadPermissions(path string) (*PermissionsConfig, error)

type RolePermissions

type RolePermissions struct {
	Role           string    `yaml:"role"`             // Роль пользователя
	Sections       []Section `yaml:"sections"`         // Доступные секции (URL)
	OwnRecordsOnly bool      `yaml:"own_records_only"` //Доступ к записям только по своему ID
}

type Section

type Section struct {
	Name     string `yaml:"name"` // Название секции
	URL      string `yaml:"url"`  // URL секции
	CanRead  bool   `yaml:"can_read"`
	CanWrite bool   `yaml:"can_write"`
}

Jump to

Keyboard shortcuts

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