-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
service.go
94 lines (74 loc) · 1.9 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Copyright (c) 2021 - 2024, Ludvig Lundgren and the autobrr contributors.
// SPDX-License-Identifier: GPL-2.0-or-later
package api
import (
"context"
"crypto/rand"
"encoding/hex"
"github.com/autobrr/autobrr/internal/domain"
"github.com/autobrr/autobrr/internal/logger"
"github.com/rs/zerolog"
)
type Service interface {
List(ctx context.Context) ([]domain.APIKey, error)
Store(ctx context.Context, key *domain.APIKey) error
Update(ctx context.Context, key *domain.APIKey) error
Delete(ctx context.Context, key string) error
ValidateAPIKey(ctx context.Context, token string) bool
}
type service struct {
log zerolog.Logger
repo domain.APIRepo
keyCache []domain.APIKey
}
func NewService(log logger.Logger, repo domain.APIRepo) Service {
return &service{
log: log.With().Str("module", "api").Logger(),
repo: repo,
keyCache: []domain.APIKey{},
}
}
func (s *service) List(ctx context.Context) ([]domain.APIKey, error) {
if len(s.keyCache) > 0 {
return s.keyCache, nil
}
return s.repo.GetKeys(ctx)
}
func (s *service) Store(ctx context.Context, key *domain.APIKey) error {
key.Key = GenerateSecureToken(16)
if err := s.repo.Store(ctx, key); err != nil {
return err
}
if len(s.keyCache) > 0 {
// set new key
s.keyCache = append(s.keyCache, *key)
}
return nil
}
func (s *service) Update(ctx context.Context, key *domain.APIKey) error {
return nil
}
func (s *service) Delete(ctx context.Context, key string) error {
// reset
s.keyCache = []domain.APIKey{}
return s.repo.Delete(ctx, key)
}
func (s *service) ValidateAPIKey(ctx context.Context, key string) bool {
keys, err := s.repo.GetKeys(ctx)
if err != nil {
return false
}
for _, k := range keys {
if k.Key == key {
return true
}
}
return false
}
func GenerateSecureToken(length int) string {
b := make([]byte, length)
if _, err := rand.Read(b); err != nil {
return ""
}
return hex.EncodeToString(b)
}