-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrepository.go
72 lines (57 loc) · 1.84 KB
/
repository.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
package repository
import (
"fmt"
"log/slog"
"strings"
"golang.org/x/crypto/bcrypt"
)
// UserRole represents a user role.
type UserRole string
// UserDetails represents user details.
type UserDetails struct {
UserName string
UserRole UserRole
}
// RequestDetails represents request details.
type RequestDetails struct {
Method string `yaml:"method"`
URI string `yaml:"uri"`
}
// String implements the fmt.Stringer interface.
func (r RequestDetails) String() string {
return fmt.Sprintf("%s %s", r.Method, r.URI)
}
// A Repository acts as a gateway to the authentication and authorization
// operations, facilitating secure access to resources.
type Repository interface {
// AuthenticateBasic validates the basic username and password before issuing a JWT.
AuthenticateBasic(username string, password string) *UserDetails
// AuthorizeRequest checks if the role has permissions to access the endpoint.
AuthorizeRequest(userRole UserRole, request RequestDetails) bool
}
func isAuthorizedRequest(scopes []map[string]string, request RequestDetails) bool {
for _, scope := range scopes {
if (scope["method"] == "*" || scope["method"] == request.Method) &&
(scope["uri"] == "*" || strings.HasPrefix(request.URI, scope["uri"])) {
slog.Debug("Request authorized", "request", request)
return true
}
}
slog.Debug("Authorization failed for the request", "request", request)
return false
}
func HashAndSalt(pwd string) ([]byte, error) {
bytePwd := []byte(pwd)
// use bcrypt.GenerateFromPassword to hash and salt the password
hash, err := bcrypt.GenerateFromPassword(bytePwd, bcrypt.MinCost)
if err != nil {
return nil, err
}
return hash, nil
}
func pwdMatch(hashed string, plain string) bool {
hashedBytes := []byte(hashed)
plainBytes := []byte(plain)
err := bcrypt.CompareHashAndPassword(hashedBytes, plainBytes)
return err == nil
}