forked from ryyst/kalzu-value-store
First proto type for issue #3, initial root account.
This commit is contained in:
27
auth/auth.go
27
auth/auth.go
@@ -39,7 +39,7 @@ func NewAuthService(db *badger.DB, logger *logrus.Logger) *AuthService {
|
||||
// StoreAPIToken stores an API token in BadgerDB with TTL
|
||||
func (s *AuthService) StoreAPIToken(tokenString string, userUUID string, scopes []string, expiresAt int64) error {
|
||||
tokenHash := utils.HashToken(tokenString)
|
||||
|
||||
|
||||
apiToken := types.APIToken{
|
||||
TokenHash: tokenHash,
|
||||
UserUUID: userUUID,
|
||||
@@ -55,13 +55,13 @@ func (s *AuthService) StoreAPIToken(tokenString string, userUUID string, scopes
|
||||
|
||||
return s.db.Update(func(txn *badger.Txn) error {
|
||||
entry := badger.NewEntry([]byte(TokenStorageKey(tokenHash)), tokenData)
|
||||
|
||||
|
||||
// Set TTL to the token expiration time
|
||||
ttl := time.Until(time.Unix(expiresAt, 0))
|
||||
if ttl > 0 {
|
||||
entry = entry.WithTTL(ttl)
|
||||
}
|
||||
|
||||
|
||||
return txn.SetEntry(entry)
|
||||
})
|
||||
}
|
||||
@@ -69,7 +69,7 @@ func (s *AuthService) StoreAPIToken(tokenString string, userUUID string, scopes
|
||||
// GetAPIToken retrieves an API token from BadgerDB by hash
|
||||
func (s *AuthService) GetAPIToken(tokenHash string) (*types.APIToken, error) {
|
||||
var apiToken types.APIToken
|
||||
|
||||
|
||||
err := s.db.View(func(txn *badger.Txn) error {
|
||||
item, err := txn.Get([]byte(TokenStorageKey(tokenHash)))
|
||||
if err != nil {
|
||||
@@ -202,4 +202,21 @@ func GetAuthContext(ctx context.Context) *AuthContext {
|
||||
return authCtx
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// HasUsers checks if any users exist in the database
|
||||
func (s *AuthService) HasUsers() (bool, error) {
|
||||
var has bool
|
||||
err := s.db.View(func(txn *badger.Txn) error {
|
||||
opts := badger.DefaultIteratorOptions
|
||||
opts.PrefetchValues = false // Only need keys
|
||||
it := txn.NewIterator(opts)
|
||||
defer it.Close()
|
||||
|
||||
prefix := []byte("user:") // Adjust if UserStorageKey uses a different prefix
|
||||
it.Seek(prefix)
|
||||
has = it.ValidForPrefix(prefix)
|
||||
return nil
|
||||
})
|
||||
return has, err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user