57 lines
1.5 KiB
Go
57 lines
1.5 KiB
Go
package gorm
|
|
|
|
import (
|
|
"github.com/jinzhu/gorm"
|
|
"src.dualinventive.com/go/authentication-service/internal/domain"
|
|
"src.dualinventive.com/go/authentication-service/internal/storage"
|
|
|
|
//Driver to MariaDB
|
|
_ "github.com/jinzhu/gorm/dialects/mysql"
|
|
)
|
|
|
|
//CredentialsRepository contains functions to interact with MariaDB
|
|
type CredentialsRepository struct {
|
|
DB *gorm.DB
|
|
}
|
|
|
|
//NewDatabaseCredentialsRepository returns new instance of repository
|
|
func NewDatabaseCredentialsRepository(host, port, name, user, pass string) (storage.CredentialsRepository, error) {
|
|
db, err := openDB(host, port, name, user, pass)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
repo := &CredentialsRepository{
|
|
DB: db,
|
|
}
|
|
return repo, nil
|
|
}
|
|
|
|
//GetUserByUserName retrieves credentials from MariaDB
|
|
func (cr *CredentialsRepository) GetUserByUserName(userName string, companyCode string) (*domain.User, error) {
|
|
var user domain.User
|
|
var company domain.Company
|
|
err := cr.DB.First(&company, domain.Company{Code: companyCode}).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err = cr.DB.
|
|
Preload("Roles").
|
|
Preload("Roles.Rights").
|
|
Preload("Company").
|
|
Preload("Company.Roles").
|
|
Preload("Company.Roles.Rights").
|
|
First(&user, domain.User{Name: userName, CompanyID: company.ID}).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &user, nil
|
|
}
|
|
|
|
//SetPassword overwrites the user password hash with the given password hash
|
|
func (cr *CredentialsRepository) SetPassword(user *domain.User, passwordHash []byte) error {
|
|
err := cr.DB.Model(&user).Update("password", passwordHash).Error
|
|
return err
|
|
}
|