50 lines
1.2 KiB
Go
50 lines
1.2 KiB
Go
package useCases
|
|
|
|
import (
|
|
"RenewCMS/internal/domain/apikey"
|
|
"time"
|
|
)
|
|
|
|
type CreateAPIKeyUseCase struct {
|
|
apiKeyRepository apikey.Repository
|
|
keyGenerator apikey.KeyGenerator
|
|
now func() time.Time
|
|
}
|
|
|
|
type CreateAPIKeyCommand struct {
|
|
UserID uint32
|
|
Name string
|
|
ExpiresAt *time.Time
|
|
}
|
|
|
|
type CreatedAPIKey struct {
|
|
Key apikey.APIKey
|
|
RawKey string
|
|
}
|
|
|
|
func NewCreateAPIKeyUseCase(apiKeyRepository apikey.Repository, keyGenerator apikey.KeyGenerator, now func() time.Time) *CreateAPIKeyUseCase {
|
|
return &CreateAPIKeyUseCase{apiKeyRepository, keyGenerator, now}
|
|
}
|
|
|
|
func (c *CreateAPIKeyUseCase) CreateAPIKey(command CreateAPIKeyCommand) (CreatedAPIKey, error) {
|
|
now := c.now()
|
|
if command.ExpiresAt != nil && !command.ExpiresAt.After(now) {
|
|
return CreatedAPIKey{}, apikey.ErrExpiryNotInFuture
|
|
}
|
|
|
|
rawKey, prefix, hashedKey := c.keyGenerator.Generate()
|
|
stored, err := c.apiKeyRepository.Create(apikey.APIKey{
|
|
UserID: command.UserID,
|
|
Name: command.Name,
|
|
Prefix: prefix,
|
|
HashedKey: hashedKey,
|
|
ExpiresAt: command.ExpiresAt,
|
|
CreatedAt: now,
|
|
})
|
|
if err != nil {
|
|
return CreatedAPIKey{}, err
|
|
}
|
|
|
|
return CreatedAPIKey{Key: stored, RawKey: rawKey}, nil
|
|
}
|