forked from 39george/authpher
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthpher.go
More file actions
79 lines (71 loc) · 2.02 KB
/
Copy pathauthpher.go
File metadata and controls
79 lines (71 loc) · 2.02 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
71
72
73
74
75
76
77
78
79
package authpher
import (
"context"
mapset "github.com/deckarep/golang-set/v2"
)
const AuthContextString = "userLoginAuthSession"
// Authenticating user type.
type AuthUser interface {
// Returns some identifying feature of the user.
UserId() any
// Returns a hash that's used by the session to verify the session is
// valid.
//
// For example, if users have passwords, this method might return a
// cryptographically secure hash of that password.
SessionAuthHash() []byte
}
// A backend which can authenticate users.
//
// Backends must implement:
//
// 1. [AuthnBackend.Authenticate], a method for authenticating
// users with credentials and,
// 2. [AuthnBackend.GetUser] a method for getting a user by an
// identifying feature.
//
// With these two methods, users may be authenticated and later retrieved via
// the backend.
type AuthnBackend[C any] interface {
// Authenticates the given credentials with the backend.
Authenticate(ctx context.Context, creds C) (AuthUser, error)
// Gets the user by provided ID from the backend.
GetUser(ctx context.Context, userId any) (AuthUser, error)
}
// A backend which can authorize users.
//
// Backends must implement [AuthnBackend].
type AuthzBackend[P comparable, C any] interface {
AuthnBackend[C]
// Gets the permissions for the provided user.
GetUserPermissions(
ctx context.Context,
user AuthUser,
) (mapset.Set[P], error)
// Gets the group permissions for the provided user.
GetGroupPermissions(
ctx context.Context,
user AuthUser,
) (mapset.Set[P], error)
}
// Returns a result which is `true` when the provided user has the provided
// permission and otherwise is `false`.
//
// `b`: can't be nil
// `user`: can't be nil
func hasPerm[P comparable, C any](
ctx context.Context,
b AuthzBackend[P, C],
user AuthUser,
perm P,
) (bool, error) {
group, err := b.GetGroupPermissions(ctx, user)
if err != nil {
return false, err
}
usr, err := b.GetUserPermissions(ctx, user)
if err != nil {
return false, err
}
return group.Union(usr).Contains(perm), nil
}