authentication

package
v0.0.11 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	UserConvertersData = map[string]func(*User, interface{}, *gorm.DB) error{
		"id": func(u *User, i interface{}, db *gorm.DB) error {
			id, err := common.ConvertToInt(i)
			if err != nil {
				return fmt.Errorf("error convert interface{}[%v] to ID(uint): %w", i, err)
			}
			u.ID = uint(id)
			return nil
		},
		"email": func(u *User, i interface{}, db *gorm.DB) error {
			email, ok := i.(string)
			if !ok {
				return fmt.Errorf("convert interface{}[%v] to Email(string)", i)
			}
			u.Email = email
			return nil
		},
		"is_active": func(u *User, i interface{}, db *gorm.DB) error {
			isActive, ok := i.(bool)
			if !ok {
				return fmt.Errorf("convert interface{}[%v] to IsActive(bool)", i)
			}
			u.IsActive = isActive
			return nil
		},
		"is_superuser": func(u *User, i interface{}, db *gorm.DB) error {
			isSuperuser, ok := i.(bool)
			if !ok {
				return fmt.Errorf("convert interface{}[%v] to IsSuperuser(bool)", i)
			}
			u.IsSuperuser = isSuperuser
			return nil
		},
		"role": func(u *User, i interface{}, db *gorm.DB) error {
			if i == nil {
				return nil
			}

			s := reflect.ValueOf(i)
			if s.Kind() != reflect.Map {
				return fmt.Errorf("interfaceStruct() given a non-struct type")
			}
			if s.IsNil() {
				return nil
			}

			roleMap, isOk := i.(map[string]interface{})
			if !isOk {
				return fmt.Errorf("error convert map to role")
			}

			role := &Role{}

			if err := db.Model(&Role{}).Preload("ModulesPermissions").Where("id = ?", roleMap["id"]).First(role).Error; err == nil {
				u.Role = role
			} else {
				return err
			}
			return nil
		},
	}
)

Functions

func IsAllow

func IsAllow(method string, access AccessLevel) bool

Types

type AccessLevel

type AccessLevel uint
const (
	ADMIN  AccessLevel = 1
	WRITER AccessLevel = 2
	READER AccessLevel = 3
)

type ErrorNotFoundOrganisation

type ErrorNotFoundOrganisation struct {
}

func (*ErrorNotFoundOrganisation) Error

func (e *ErrorNotFoundOrganisation) Error() string

type ErrorNotFoundRole

type ErrorNotFoundRole struct {
}

func (*ErrorNotFoundRole) Error

func (e *ErrorNotFoundRole) Error() string

type ModulesPermissions

type ModulesPermissions struct {
	serializers.Serializer
	models.BaseModel
	ID     uint        `json:"id" serializer:"read_only;" gorm:"primarykey"`
	Name   string      `json:"name" serializer:"read_only;title:Название модуля;" gorm:"column:name;uniqueIndex:idx_name_access"`
	Access AccessLevel `json:"access" serializer:"read_only;title:Уровень доступа;" gorm:"column:access;uniqueIndex:idx_name_access"`
	Roles  []Role      `json:"-" gorm:"many2many:roles_modules;"`
}

ModulesPermissions - модель описывающая связь модуля и уровнем доступа Модуль - это лoгический слой, объединяющий в себе несолько таблиц Модуль и уровни доступа создаются при инициализации приложения, поэтому в апи не предусмотрены методы CUD для этой таблицы

func (ModulesPermissions) Description

func (ModulesPermissions) Description() string

func (ModulesPermissions) TableName

func (ModulesPermissions) TableName() string

type Role

type Role struct {
	serializers.Serializer
	models.BaseModel
	ID                    uint                 `json:"id" serializer:"read_only" gorm:"primarykey"`
	Name                  string               `json:"name" serializer:"required;title:Название роли;" gorm:"column:name;unique;"`
	ModulesPermissionsIDs []uint               `json:"modulesPermissionsIds" serializer:"write_only;referenceTable:module_permissions;referencePk:id;" gorm:"-"`
	ModulesPermissions    []ModulesPermissions `` /* 135-byte string literal not displayed */
}

func (*Role) Create

func (r *Role) Create(db *gorm.DB) error

BaseModelInterface impliments on Role

func (*Role) Delete

func (r *Role) Delete(db *gorm.DB) error

func (Role) Description

func (Role) Description() string

func (*Role) GetPk

func (r *Role) GetPk() uint

func (*Role) SetPK

func (r *Role) SetPK(pk interface{}) error

func (Role) TableName

func (Role) TableName() string

func (*Role) Update

func (r *Role) Update(db *gorm.DB) error

func (*Role) Validate

func (r *Role) Validate() bool

type SessionBase

type SessionBase struct {
}

func (*SessionBase) GenerateKey

func (s *SessionBase) GenerateKey() (string, error)

func (*SessionBase) GetSession

func (s *SessionBase) GetSession(r *http.Request) map[string]interface{}

func (*SessionBase) GetValue

func (s *SessionBase) GetValue(key string, r *http.Request) interface{}

func (*SessionBase) SetValue

func (s *SessionBase) SetValue(key string, v interface{}, r *http.Request)

type SessionInterface

type SessionInterface interface {
	GenerateKey() (string, error)
	GetSession(r *http.Request) map[string]interface{}
	GetValue(key string, r *http.Request) interface{}
	SetValue(key string, v interface{}, r *http.Request)
}

type User

type User struct {
	serializers.Serializer
	models.BaseModel
	ID              uint                 `json:"id" serializer:"read_only" gorm:"primarykey"`
	Email           string               `json:"email" serializer:"required;title:Емайл;" gorm:"type:varchar(100);unique;unique_index;column:email"`
	Lastname        string               `json:"lastname" serializer:"required;title:Фамилия;" gorm:"column:lastname"`
	Firstname       string               `json:"firstname" serializer:"required;title:Имя;" gorm:"column:firstname"`
	Middlename      string               `json:"middlename" serializer:"required;title:Отчество;" gorm:"column:middlename"`
	Phone           string               `json:"phone" serializer:"title:Телефон;" gorm:"type:varchar(15);column:phone"`
	AdditionalPhone string               `` /* 146-byte string literal not displayed */
	Avatar          string               `json:"avatar" serializer:"title:Аватар;" gorm:"column:avatar"`
	Password        []byte               `json:"password" serializer:"write_only;title:Пароль;" gorm:"type:bytea;column:password;"`
	IsActive        bool                 `json:"isActive" serializer:"title:Активен;" gorm:"column:isActive;"`
	IsStaff         bool                 `json:"isStaff" serializer:"title:Персонал;" gorm:"column:isStaff;"`
	IsSuperuser     bool                 `json:"isSuperuser" serializer:"title:Суперпользователь;" gorm:"column:isSuperuser;"`
	IsDelete        bool                 `json:"isDelete" serializer:"title:Удален;" gorm:"bit(1);column:isDelete;default:false"`
	RoleID          typesdb.UintNullable `json:"roleId" serializer:"write_only;referenceTable:roles;referencePk:id;" gorm:"column:roleId;"`
	OrganisationID  typesdb.UintNullable `json:"organisationId" serializer:"referenceTable:organisations;referencePk:id;" gorm:"column:organisationId;"`
	CreatedAt       time.Time            `json:"createdAt" serializer:"read_only"`
	UpdatedAt       time.Time            `json:"updatedAt" serializer:"read_only"`
	Role            *Role                `json:"role" serializer:"read_only,title:Роли;referenceField:name;" gorm:"foreignkey:RoleID;references:ID;"`
}

func GetUserFromContext

func GetUserFromContext(userData interface{}, db *gorm.DB) (*User, error)

func (*User) Clean

func (u *User) Clean(db *gorm.DB) error

func (*User) ComparePassword

func (u *User) ComparePassword(password string) bool

func (*User) Create

func (u *User) Create(db *gorm.DB) error

BaseModelInterface impliments on User

func (*User) Delete

func (u *User) Delete(db *gorm.DB) error

func (User) Description

func (User) Description() string

func (*User) GetPk

func (u *User) GetPk() uint

func (*User) RefreshToken

func (u *User) RefreshToken() (string, error)

func (*User) SetPK

func (u *User) SetPK(pk interface{}) error

func (*User) SetPassword

func (u *User) SetPassword(password string, db *gorm.DB) error

func (User) TableName

func (User) TableName() string

func (*User) Token

func (u *User) Token() (string, error)

func (*User) Update

func (u *User) Update(db *gorm.DB) error

func (*User) Validate

func (u *User) Validate() bool

Jump to

Keyboard shortcuts

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