articles-api/service/auth/model.go

72 lines
1.3 KiB
Go
Raw Normal View History

2019-05-02 18:50:58 +00:00
package auth
import (
"errors"
2019-05-02 18:50:58 +00:00
"time"
)
// Model represents an actual tiny url entry in the database.
type Model struct {
2019-05-02 18:50:58 +00:00
token string
role string
expires int64
}
// storage contains entries
var storage []*Model = make([]*Model, 0)
2019-05-02 18:50:58 +00:00
// NewModel builds a token model from arguments
func NewModel(token, role string, duration time.Duration) *Model {
return &Model{
2019-05-02 18:50:58 +00:00
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
}
2019-05-02 18:50:58 +00:00
if row.token == mod.token {
mod.token = row.token
mod.role = row.role
mod.expires = row.expires
return nil
}
2019-05-02 18:50:58 +00:00
}
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")
}
2019-05-02 18:50:58 +00:00
}
storage = append(storage, mod)
2019-05-02 18:50:58 +00:00
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
}
}
2019-05-02 18:50:58 +00:00
return errors.New("not found")
2019-05-02 18:50:58 +00:00
}