Passport/pkg/services/auth.go

136 lines
3.4 KiB
Go
Raw Normal View History

2024-02-20 13:46:15 +00:00
package services
import (
"fmt"
"time"
2024-03-20 12:56:43 +00:00
2024-04-13 05:48:19 +00:00
"git.solsynth.dev/hydrogen/passport/pkg/database"
"git.solsynth.dev/hydrogen/passport/pkg/models"
2024-02-20 13:46:15 +00:00
"github.com/gofiber/fiber/v2"
jsoniter "github.com/json-iterator/go"
"github.com/rs/zerolog/log"
"go.etcd.io/bbolt"
2024-02-20 13:46:15 +00:00
)
const authContextBucket = "AuthContext"
2024-05-17 09:13:11 +00:00
func Authenticate(access, refresh string, depth int) (user models.Account, perms map[string]any, newAccess, newRefresh string, err error) {
2024-04-20 11:04:33 +00:00
var claims PayloadClaims
claims, err = DecodeJwt(access)
2024-02-20 13:46:15 +00:00
if err != nil {
if len(refresh) > 0 && depth < 1 {
// Auto refresh and retry
2024-04-20 11:04:33 +00:00
newAccess, newRefresh, err = RefreshToken(refresh)
2024-02-20 13:46:15 +00:00
if err == nil {
return Authenticate(newAccess, newRefresh, depth+1)
2024-02-20 13:46:15 +00:00
}
}
err = fiber.NewError(fiber.StatusUnauthorized, fmt.Sprintf("invalid auth key: %v", err))
return
2024-02-20 13:46:15 +00:00
}
newAccess = access
newRefresh = refresh
var ctx models.AuthContext
ctx, lookupErr := GetAuthContext(claims.ID)
if lookupErr == nil {
log.Debug().Str("jti", claims.ID).Msg("Hit auth context cache once!")
2024-05-17 09:13:11 +00:00
perms = FilterPermNodes(ctx.Account.PermNodes, ctx.Ticket.Claims)
user = ctx.Account
return
}
ctx, err = GrantAuthContext(claims.ID)
if err == nil {
log.Debug().Str("jti", claims.ID).Err(lookupErr).Msg("Missed auth context cache once!")
2024-05-17 09:13:11 +00:00
perms = FilterPermNodes(ctx.Account.PermNodes, ctx.Ticket.Claims)
user = ctx.Account
return
}
err = fiber.NewError(fiber.StatusUnauthorized, err.Error())
return
}
func GetAuthContext(jti string) (models.AuthContext, error) {
var err error
var ctx models.AuthContext
err = database.B.View(func(tx *bbolt.Tx) error {
bucket := tx.Bucket([]byte(authContextBucket))
if bucket == nil {
return fmt.Errorf("unable to find auth context bucket")
}
raw := bucket.Get([]byte(jti))
if raw == nil {
return fmt.Errorf("unable to find auth context")
} else if err := jsoniter.Unmarshal(raw, &ctx); err != nil {
return fmt.Errorf("unable to unmarshal auth context: %v", err)
}
return nil
})
if err == nil && time.Now().Unix() >= ctx.ExpiredAt.Unix() {
2024-04-20 11:04:33 +00:00
_ = RevokeAuthContext(jti)
return ctx, fmt.Errorf("auth context has been expired")
}
return ctx, err
}
func GrantAuthContext(jti string) (models.AuthContext, error) {
var ctx models.AuthContext
// Query data from primary database
2024-04-21 04:20:06 +00:00
ticket, err := GetTicketWithToken(jti)
2024-02-20 13:46:15 +00:00
if err != nil {
2024-04-21 04:20:06 +00:00
return ctx, fmt.Errorf("invalid auth ticket: %v", err)
} else if err := ticket.IsAvailable(); err != nil {
return ctx, fmt.Errorf("unavailable auth ticket: %v", err)
2024-02-20 13:46:15 +00:00
}
2024-04-21 04:20:06 +00:00
user, err := GetAccount(ticket.AccountID)
2024-02-20 13:46:15 +00:00
if err != nil {
return ctx, fmt.Errorf("invalid account: %v", err)
}
2024-05-17 09:13:11 +00:00
// Every context should expire in some while
// Once user update their account info, this will have delay to update
ctx = models.AuthContext{
2024-04-21 04:20:06 +00:00
Ticket: ticket,
Account: user,
ExpiredAt: time.Now().Add(5 * time.Minute),
2024-02-20 13:46:15 +00:00
}
// Save data into KV cache
return ctx, database.B.Update(func(tx *bbolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte(authContextBucket))
if err != nil {
return err
}
raw, err := jsoniter.Marshal(ctx)
if err != nil {
return err
}
return bucket.Put([]byte(jti), raw)
})
}
func RevokeAuthContext(jti string) error {
return database.B.Update(func(tx *bbolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte(authContextBucket))
if err != nil {
return err
}
return bucket.Delete([]byte(jti))
})
2024-02-20 13:46:15 +00:00
}