-
Notifications
You must be signed in to change notification settings - Fork 0
/
api-keys.go
87 lines (68 loc) · 2 KB
/
api-keys.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
package usersvc
import (
"context"
"fmt"
"github.com/sisukasco/commons/crypto"
"github.com/sisukasco/henki/pkg/db"
"log"
"strings"
"time"
)
func (usvc *UserService) GetAPIKeys(ctx context.Context, userID string) ([]db.GetAPIKeysRow, error) {
return usvc.svc.DB.Q.GetAPIKeys(ctx, userID)
}
func makeKey(secret string, userID string) string {
created := time.Date(2020, time.December, 28, 10, 20, 0, 0, time.UTC)
timestamp := fmt.Sprintf("%v", time.Now().Unix()-created.Unix())
key, err := crypto.EncryptAES(userID+","+timestamp, secret)
if err != nil {
log.Printf("Error encrypting API Key %v ", err)
return ""
}
return key
}
func (usvc *UserService) createAPIKey(ctx context.Context, userID string) string {
secret := usvc.svc.Konf.String("api.api_key.secret")
key := makeKey(secret, userID)
t := 0
for ; t < 100; t++ {
if len(key) > 8 {
exists, err := usvc.svc.DB.Q.DoesAPIKeyExist(ctx, key)
if exists == false && err == nil {
break
}
}
key = makeKey(secret, userID)
}
return key
}
func (usvc *UserService) NewAPIKey(ctx context.Context, userID string) (string, error) {
key := usvc.createAPIKey(ctx, userID)
_, err := usvc.svc.DB.Q.NewApiKey(ctx, db.NewApiKeyParams{Key: key, UserID: userID})
if err != nil {
return "", err
}
return key, nil
}
func (usvc *UserService) DeleteAPIKey(ctx context.Context, apiKey string, userID string) error {
return usvc.svc.DB.Q.DeleteAPIKey(ctx, db.DeleteAPIKeyParams{Key: apiKey, UserID: userID})
}
func (usvc *UserService) GetUserFromAPIKey(ctx context.Context, apiKey string) (*db.User, error) {
user, err := usvc.svc.DB.Q.GetUserFromAPIKey(ctx, apiKey)
if err != nil {
return nil, err
}
return &user, nil
}
func (usvc *UserService) GetUserIDFromAPIKey(apiKey string) (string, error) {
secret := usvc.svc.Konf.String("api.api_key.secret")
strKey, err := crypto.DecryptAES(apiKey, secret)
if err != nil {
return "", err
}
parts := strings.Split(strKey, ",")
if len(parts) == 2 {
return parts[0], nil
}
return "", nil
}