-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
70 lines (55 loc) · 1.53 KB
/
auth.go
File metadata and controls
70 lines (55 loc) · 1.53 KB
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
package mfa
import (
"fmt"
"log"
"net/http"
"strings"
)
const (
HeaderAPIKey = "x-mfa-apikey"
HeaderAPISecret = "x-mfa-apisecret"
)
type User any
// AuthenticateRequest checks the provided API key against the keys stored in the database. If the key is active and
// valid, an authentication user (e.g. Webauthn user and client) is created and returned.
func AuthenticateRequest(r *http.Request) (User, error) {
if r.Method == http.MethodGet && r.RequestURI == "/status" {
return nil, nil
}
// get key and secret from headers
key := r.Header.Get(HeaderAPIKey)
secret := r.Header.Get(HeaderAPISecret)
if key == "" || secret == "" {
return nil, fmt.Errorf("x-mfa-apikey and x-mfa-apisecret are required")
}
log.Printf("API called by key: %s. %s %s", key, r.Method, r.RequestURI)
localStorage, err := NewStorage(envConfig.AWSConfig)
if err != nil {
return nil, fmt.Errorf("error initializing storage: %w", err)
}
apiKey := ApiKey{
Key: key,
Secret: secret,
Store: localStorage,
}
err = apiKey.Load()
if err != nil {
return nil, fmt.Errorf("failed to load api key: %w", err)
}
err = apiKey.IsCorrect(secret)
if err != nil {
return nil, fmt.Errorf("failed to validate api key: %w", err)
}
path := r.URL.Path
segments := strings.Split(strings.TrimPrefix(path, "/"), "/")
switch segments[0] {
case "webauthn":
return authWebauthnUser(r, localStorage, apiKey)
case "totp":
return authTOTP(apiKey)
case "api-key":
return apiKey, nil
default:
return nil, fmt.Errorf("invalid URL: %s", r.URL)
}
}