77 lines
1.6 KiB
Go
77 lines
1.6 KiB
Go
package user
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/speps/go-hashids"
|
|
|
|
"code.chrissexton.org/cws/happy/db"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
// lol
|
|
|
|
type UserFactory struct {
|
|
db *db.Database
|
|
salt string
|
|
h *hashids.HashID
|
|
}
|
|
|
|
func NewFactory(db *db.Database, salt string, h *hashids.HashID) *UserFactory {
|
|
return &UserFactory{
|
|
db: db,
|
|
salt: salt,
|
|
h: h,
|
|
}
|
|
}
|
|
|
|
func (uf *UserFactory) NewUser() (User, error) {
|
|
uid := New(uf.db, uf.salt, uf.h)
|
|
q := `insert into users (verification,dateCreated) values (?, ?)`
|
|
res, err := uf.db.Exec(q, uid.Verification, uid.DateCreated)
|
|
if err != nil {
|
|
return uid, err
|
|
}
|
|
id, err := res.LastInsertId()
|
|
if err != nil {
|
|
return uid, err
|
|
}
|
|
uid.ID = id
|
|
return uid, nil
|
|
}
|
|
|
|
func (uf *UserFactory) FromStr(uid, verification string) (User, error) {
|
|
id := New(uf.db, uf.salt, uf.h)
|
|
if uid == "" || verification == "" {
|
|
return id, fmt.Errorf("user ID and verification not given.")
|
|
}
|
|
idInt, err := uf.h.DecodeInt64WithError(uid)
|
|
if err != nil {
|
|
return id, err
|
|
}
|
|
q := `select id,email,verification,datecreated,lastlogin from users where id=?`
|
|
if err := uf.db.Get(&id, q, idInt[0]); err != nil {
|
|
log.Error().
|
|
Err(err).
|
|
Msg("unable to select")
|
|
return id, err
|
|
}
|
|
verify, err := uf.h.EncodeInt64([]int64{id.Verification})
|
|
if err != nil {
|
|
log.Error().
|
|
Err(err).
|
|
Str("verify", verify).
|
|
Str("id.Verification", verification).
|
|
Msg("unable to encode")
|
|
return id, err
|
|
}
|
|
if verify != verification {
|
|
log.Debug().
|
|
Str("verify", verify).
|
|
Str("id.Verification", verification).
|
|
Msg("verification mismatch")
|
|
return id, fmt.Errorf("Invalid verification token")
|
|
}
|
|
return id, nil
|
|
}
|