blasphem/pkg/auth/session.go

93 lines
1.6 KiB
Go
Raw Normal View History

2022-10-26 19:13:50 -04:00
package auth
import (
"net/http"
"time"
2022-10-26 19:43:51 -04:00
"github.com/labstack/echo/v4"
2022-10-26 19:13:50 -04:00
)
type SessionStore struct {
s map[TokenID]*Token
lastCull time.Time
}
type TokenID string
2022-10-26 19:43:51 -04:00
type Token struct { // TODO: jwt bro
2022-10-26 19:13:50 -04:00
ID TokenID
Ctime time.Time
2022-10-26 19:43:51 -04:00
Expires time.Time
2022-10-26 19:13:50 -04:00
Addr string
}
func (ss *SessionStore) init() {
ss.s = make(map[TokenID]*Token)
}
const cullInterval = 5 * time.Minute
func (ss *SessionStore) cull() {
if now := time.Now(); now.Sub(ss.lastCull) > cullInterval {
for k, v := range ss.s {
2022-10-26 19:43:51 -04:00
if now.After(v.Expires) {
2022-10-26 19:13:50 -04:00
delete(ss.s, k)
}
}
}
}
func (ss *SessionStore) register(t *Token) {
ss.cull()
ss.s[t.ID] = t
}
2022-10-26 19:43:51 -04:00
func (ss *SessionStore) verify(tr *TokenRequest, r *http.Request) bool {
if t, hasToken := ss.s[tr.Code]; hasToken {
// TODO: JWT
if t.Expires.After(time.Now()) {
return true
}
}
return false
}
const defaultExpiration = 2 * time.Hour
2022-10-26 19:13:50 -04:00
func (a *Authenticator) NewToken(r *http.Request, f *Flow) TokenID {
id := TokenID(genUUID())
t := &Token{
2022-10-26 19:43:51 -04:00
ID: id,
Ctime: time.Now(),
Expires: time.Now().Add(defaultExpiration),
Addr: r.RemoteAddr,
2022-10-26 19:13:50 -04:00
}
2022-10-27 09:51:11 -04:00
a.sessions.register(t)
2022-10-26 19:13:50 -04:00
return id
}
2022-10-26 19:43:51 -04:00
type TokenRequest struct {
ClientID string `query:"client_id"` // TODO: validate this?
Code TokenID `query:"code"`
GrantType string `query:"grant_type"`
}
func (a *Authenticator) TokenHandler(c echo.Context) error {
var rq TokenRequest
err := c.Bind(&rq)
if err != nil {
return err
}
2022-10-27 09:51:11 -04:00
if a.sessions.verify(&rq, c.Request()) {
2022-10-26 19:43:51 -04:00
// TODO: success
return c.String(http.StatusOK, "token good I guess")
}
return c.String(http.StatusUnauthorized, "token bad I guess")
}