/
basicAuth.go
64 lines (50 loc) 路 1.68 KB
/
basicAuth.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
package auth
import (
"encoding/base64"
"fmt"
"regexp"
"strings"
"github.com/franpog859/cleanaux-backend/auth-service/internal/database"
)
const (
basicBearer = "Basic"
)
// ExtractCredentialsFromHeader provides username, password provided
// in the Basic Auth header and eventually an error
func ExtractCredentialsFromHeader(basicAuthHeader string) (string, string, error) {
splittedAuthHeader := strings.SplitN(basicAuthHeader, " ", 2)
if len(splittedAuthHeader) != 2 || splittedAuthHeader[0] != basicBearer {
return "", "", fmt.Errorf("invalid Basic Auth header structure: %s", basicAuthHeader)
}
authPayload, _ := base64.StdEncoding.DecodeString(splittedAuthHeader[1])
basicCredentials := strings.SplitN(string(authPayload), ":", 2)
if len(basicCredentials) != 2 {
return "", "", fmt.Errorf("invalid Basic Auth credentials structure: %s", authPayload)
}
username, password := basicCredentials[0], basicCredentials[1]
return username, password, nil
}
// AreCredentialsValid validates user credentials checking users from the database
func AreCredentialsValid(username, password string, dbClient database.Client) (bool, error) {
if valid := validateCredentials(username, password); !valid {
return false, nil
}
users, err := dbClient.GetAuthorizedUsers(username, password)
if err != nil {
return false, fmt.Errorf("failed to get all users from database: %v", err)
}
if len(users) < 1 {
return false, nil
}
return true, nil
}
func validateCredentials(username, password string) bool {
regexPattern := regexp.MustCompile("^([a-zA-Z0-9]+)$")
if !regexPattern.MatchString(username) {
return false
}
if !regexPattern.MatchString(password) {
return false
}
return true
}