tiny-url-ex/service/auth/model.go

72 lines
1.3 KiB
Go

package auth
import (
"errors"
"time"
)
// Model represents an actual tiny url entry in the database.
type Model struct {
token string
role string
expires int64
}
// storage contains entries
var storage []*Model = make([]*Model, 0)
// NewModel builds a token model from arguments
func NewModel(token, role string, duration time.Duration) *Model {
return &Model{
token: token,
role: role,
expires: time.Now().Add(duration).Unix(),
}
}
// Search for model in storage
func (mod *Model) Search() error {
for _, row := range storage {
// silently delete if expired
if row.expires < time.Now().Unix() {
row.Delete()
continue
}
if row.token == mod.token {
mod.token = row.token
mod.role = row.role
mod.expires = row.expires
return nil
}
}
return errors.New("not found")
}
// Create the model in storage
func (mod *Model) Create() error {
// fail if already exists
for _, row := range storage {
if row.token == mod.token {
return errors.New("already exists")
}
}
storage = append(storage, mod)
return nil
}
// Delete the model from storage
func (mod *Model) Delete() error {
for i, row := range storage {
if row.token == mod.token {
storage = append(storage[:i], storage[i+1:]...)
return nil
}
}
return errors.New("not found")
}