blasphem/pkg/auth/session.go
2022-11-13 12:03:58 -05:00

208 lines
5.1 KiB
Go

package auth
import (
"encoding/json"
"net/http"
"time"
"github.com/labstack/echo/v4"
"dynatron.me/x/blasphem/internal/common"
"dynatron.me/x/blasphem/internal/generate"
"dynatron.me/x/blasphem/pkg/auth/provider"
)
type (
TokenType string
RefreshTokenID string
)
type RefreshToken struct {
ID RefreshTokenID `json:"id"`
UserID UserID `json:"user_id"`
ClientID *ClientID `json:"client_id"`
ClientName *string `json:"client_name"`
ClientIcon *string `json:"client_icon"`
TokenType TokenType `json:"token_type"`
CreatedAt *common.PyTimestamp `json:"created_at"`
AccessTokenExpiration common.KeepZero `json:"access_token_expiration"`
Token string `json:"token"`
JWTKey string `json:"jwt_key"`
LastUsedAt *common.PyTimestamp `json:"last_used_at"`
LastUsedIP *string `json:"last_used_ip"`
CredentialID *CredID `json:"credential_id"`
Version *string `json:"version"`
}
type AccessSessionStore struct {
s map[AccessTokenID]*AccessToken
lastCull time.Time
}
type AccessTokenID string
func (t *AccessTokenID) IsValid() bool {
// TODO: more validation than this
return *t != ""
}
type AccessToken struct { // TODO: jwt bro
ID AccessTokenID
Ctime time.Time
Expires time.Time
Addr string
user provider.ProviderUser `json:"-"`
}
func (ss *AccessSessionStore) init() {
ss.s = make(map[AccessTokenID]*AccessToken)
}
const cullInterval = 5 * time.Minute
func (ss *AccessSessionStore) cull() {
if now := time.Now(); now.Sub(ss.lastCull) > cullInterval {
for k, v := range ss.s {
if now.After(v.Expires) {
delete(ss.s, k)
}
}
}
}
func (ss *AccessSessionStore) register(t *AccessToken) {
ss.cull()
ss.s[t.ID] = t
}
func (ss *AccessSessionStore) verify(tr *TokenRequest, r *http.Request) (provider.ProviderUser, bool) {
if t, hasToken := ss.s[tr.Code]; hasToken {
// TODO: JWT
if t.Expires.After(time.Now()) {
return t.user, true
} else {
delete(ss.s, t.ID)
}
}
return nil, false
}
type Credential struct {
ID CredID `json:"id"`
UserID UserID `json:"user_id"`
AuthProviderType string `json:"auth_provider_type"`
AuthProviderID *string `json:"auth_provider_id"`
DataRaw *json.RawMessage `json:"data,omitempty"`
user provider.ProviderUser `json:"-"`
}
func (cred *Credential) MarshalJSON() ([]byte, error) {
type CredAlias Credential // alias so ø method set and we don't recurse
nCd := (*CredAlias)(cred)
if cred.user != nil {
providerData := cred.user.UserData()
if providerData != nil {
b, err := json.Marshal(providerData)
if err != nil {
return nil, err
}
dr := json.RawMessage(b)
nCd.DataRaw = &dr
}
}
return json.Marshal(nCd)
}
func (a *Authenticator) verifyAndGetCredential(tr *TokenRequest, r *http.Request) *Credential {
user, success := a.sessions.verify(tr, r)
if !success {
return nil
}
cred := &Credential{
user: user,
}
return cred
}
const defaultExpiration = 15 * time.Minute
func (a *Authenticator) NewAccessToken(r *http.Request, user provider.ProviderUser, f *Flow) AccessTokenID {
id := AccessTokenID(generate.UUID())
now := time.Now()
t := &AccessToken{
ID: id,
Ctime: now,
Expires: now.Add(defaultExpiration),
Addr: r.RemoteAddr,
user: user,
}
a.sessions.register(t)
return id
}
type GrantType string
const (
GTAuthorizationCode GrantType = "authorization_code"
GTRefreshToken GrantType = "refresh_token"
)
type ClientID string
func (c *ClientID) IsValid() bool {
// TODO: || !indieauth.VerifyClientID(rq.ClientID)?
return *c != ""
}
type TokenRequest struct {
ClientID ClientID `form:"client_id"`
Code AccessTokenID `form:"code"`
GrantType GrantType `form:"grant_type"`
}
func (a *Authenticator) TokenHandler(c echo.Context) error {
rq := new(TokenRequest)
err := c.Bind(rq)
if err != nil {
return err
}
switch rq.GrantType {
case GTAuthorizationCode:
if !rq.ClientID.IsValid() {
return c.JSON(http.StatusBadRequest, AuthError{Error: "invalid_request", Description: "invalid client ID"})
}
if !rq.Code.IsValid() {
return c.JSON(http.StatusBadRequest, AuthError{Error: "invalid_request", Description: "invalid code"})
}
if cred := a.verifyAndGetCredential(rq, c.Request()); cred != nil {
// TODO: success
user, err := a.getOrCreateUser(cred)
if err != nil {
return c.JSON(http.StatusUnauthorized, AuthError{Error: "access_denied", Description: err.Error()})
}
if err := user.allowedToAuth(); err != nil {
return c.JSON(http.StatusUnauthorized, AuthError{Error: "access_denied", Description: err.Error()})
}
return c.String(http.StatusOK, "token good I guess")
}
case GTRefreshToken:
return c.String(http.StatusNotImplemented, "not implemented")
}
return c.String(http.StatusUnauthorized, "token bad I guess")
}