2022-12-30 06:51:51 +00:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
// Copyright © 2022 Roberto Hidalgo <nidito@un.rob.mx>
|
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math/rand"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2023-01-04 04:21:49 +00:00
|
|
|
"git.rob.mx/nidito/puerta/internal/user"
|
2022-12-30 06:51:51 +00:00
|
|
|
"github.com/upper/db/v4"
|
|
|
|
)
|
|
|
|
|
|
|
|
var letterSrc = rand.NewSource(time.Now().UnixNano())
|
|
|
|
|
|
|
|
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
|
|
const (
|
|
|
|
// 6 bits to represent a letter index
|
|
|
|
letterIdxBits = 6
|
|
|
|
// All 1-bits, as many as letterIdxBits
|
|
|
|
letterIdxMask = 1<<letterIdxBits - 1
|
|
|
|
// # of letter indices fitting in 63 bits
|
|
|
|
letterIdxMax = 63 / letterIdxBits
|
|
|
|
)
|
|
|
|
|
|
|
|
func NewToken() string {
|
|
|
|
sb := strings.Builder{}
|
|
|
|
n := 32
|
|
|
|
sb.Grow(n)
|
|
|
|
|
|
|
|
for i, cache, remain := n-1, letterSrc.Int63(), letterIdxMax; i >= 0; {
|
|
|
|
if remain == 0 {
|
|
|
|
cache, remain = letterSrc.Int63(), letterIdxMax
|
|
|
|
}
|
|
|
|
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
|
|
|
|
sb.WriteByte(letterBytes[idx])
|
|
|
|
i--
|
|
|
|
}
|
|
|
|
cache >>= letterIdxBits
|
|
|
|
remain--
|
|
|
|
}
|
|
|
|
|
|
|
|
return sb.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
type Session struct {
|
|
|
|
Token string `db:"token"`
|
|
|
|
UserID int `db:"user"`
|
|
|
|
Expires time.Time `db:"expires"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Session) Store(sess db.Session) db.Store {
|
|
|
|
return sess.Collection("session")
|
|
|
|
}
|
|
|
|
|
2023-01-04 04:21:49 +00:00
|
|
|
type SessionUser struct {
|
|
|
|
Token string `db:"token"`
|
|
|
|
UserID int `db:"user"`
|
|
|
|
Expires time.Time `db:"expires"`
|
|
|
|
user.User `db:",inline"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SessionUser) Expired() bool {
|
|
|
|
return s.Expires.After(time.Now())
|
2022-12-30 06:51:51 +00:00
|
|
|
}
|
|
|
|
|
2023-01-04 04:21:49 +00:00
|
|
|
func NewSession(user *user.User, table db.Collection) (*Session, error) {
|
2022-12-30 06:51:51 +00:00
|
|
|
sess := &Session{
|
|
|
|
Token: NewToken(),
|
|
|
|
UserID: user.ID,
|
|
|
|
Expires: user.TTL.FromNow(),
|
|
|
|
}
|
|
|
|
|
|
|
|
// delete previous sessions
|
|
|
|
table.Find(db.Cond{"user": user.ID}).Delete()
|
|
|
|
// insert new one
|
|
|
|
_, err := table.Insert(sess)
|
|
|
|
return sess, err
|
|
|
|
}
|