2022-02-02 21:46:20 +01:00

44 lines
914 B
Go

package models
import (
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
type Session struct {
ID uint32 `gorm:"primary_key"`
Token string `gorm:"size:36"`
Account *Account `gorm:"constraint:OnDelete:CASCADE,OnUpdate:CASCADE"`
AccountId uint32 `gorm:"not null"`
CreatedAt time.Time
UpdatedAt time.Time
}
func (s *Session) BeforeCreate(tx *gorm.DB) error {
uuid, err := uuid.NewRandom()
if err != nil {
return err
}
s.Token = uuid.String()
return nil
}
func NewSession(tx *gorm.DB, login string, password string) (*Session, error) {
account := NewAccount(login, password)
if err := tx.Where(
"login = ? and encrypted_password = ?",
account.Login,
account.EncryptedPassword,
).First(account).Error; err != nil {
return nil, err
}
session := &Session{Account: account}
if err := tx.Create(session).Error; err != nil {
return nil, err
}
return session, nil
}