security

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2024 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package security provides private security methods.

Index

Constants

View Source
const (
	DialectPostgreSQL = "postgres"
	DialectMySQL      = "mysql"
	DialectSQLite     = "sqlite"
)

Supported SQL dialects.

Variables

This section is empty.

Functions

func CreateUser

func CreateUser(username, password string, roles []string) error

CreateUser creates a new User entry in the database.

func DeleteUser

func DeleteUser(ids ...int) error

DeleteUser deletes users by id from the database.

func GenerateJWT

func GenerateJWT(credentials *Credentials) (string, error)

GenerateJWT generates JSON Web Token (JWT) for the provided credentials. It uses secret key generated once at runtime.

func HasPermissions

func HasPermissions(c *Credentials, requiredRoles []string) bool

HasPermissions reports whether user has permission for the action based on roles.

func InitDB

func InitDB(dsn, dialect string)

InitDB initializes database used to store users.

List of supported dialects:

  • `postgres` for PostgreSQL,
  • `mysql` for MySQL,
  • `sqlite` for SQLite (default).

If database initialization fails, InitDB panics.

func InitDBWithDialector

func InitDBWithDialector(dialector gorm.Dialector)

InitDBWithDialector initializes database used to store users. Unlike InitDB, it accepts GORM dialector, allowing dependency injection.

Types

type Credentials

type Credentials struct {
	Roles    []string
	Username string
}

Credentials represents authorization data. It contains Role and Username.

func Login

func Login(username, password string) (*Credentials, error)

Login retrieves first User with matching username and password. It returns *Credentials of the found user.

If user does not exist, error is returned.

func ParseJWT

func ParseJWT(tokenString string) (*Credentials, error)

ParseJWT returns credentials associated with provided JSON Web Token (JWT). It uses secret key generated once at runtime.

type User

type User struct {
	gorm.Model
	Username string `gorm:"unique"`
	Password string
	Roles    string // Roles are comma-separated.
}

User is a database model of user.

func (*User) Credentials

func (m *User) Credentials() *Credentials

Credentials returns *Credentials associated with the user.

func (User) TableName

func (User) TableName() string

TableName overrides the table name used by User to `hakutest_users`.

Jump to

Keyboard shortcuts

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