-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
user.go
92 lines (77 loc) · 2.29 KB
/
user.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
88
89
90
91
92
package permission
import (
"github.com/gofiber/fiber/v2"
"github.com/th0th/poeticmetric/backend/pkg/pointer"
"github.com/th0th/poeticmetric/backend/pkg/restapi/helpers"
"github.com/th0th/poeticmetric/backend/pkg/restapi/middleware/authentication"
)
type userPermissionMiddlewareConfig struct {
AuthKind *authentication.AuthKind
IsAuthenticated *bool
IsEmailVerified *bool
IsOrganizationOwner *bool
}
func User(cfg *userPermissionMiddlewareConfig) fiber.Handler {
return func(c *fiber.Ctx) error {
auth := c.Locals("auth").(*authentication.Auth)
// IsAuthenticated
if cfg.IsAuthenticated != nil {
if *cfg.IsAuthenticated && auth.User == nil {
return fiber.ErrUnauthorized
}
if !*cfg.IsAuthenticated && auth.User != nil {
return fiber.ErrForbidden
}
}
// AuthKind
if cfg.AuthKind != nil {
if *auth.Kind != *cfg.AuthKind {
return fiber.ErrForbidden
}
}
// IsEmailVerified
if cfg.IsEmailVerified != nil {
if auth.User == nil || auth.User.IsEmailVerified != *cfg.IsEmailVerified {
return c.
Status(fiber.StatusForbidden).
JSON(helpers.Detail("You need to verify your e-mail address."))
}
}
// IsOwner
if cfg.IsOrganizationOwner != nil {
if auth.User == nil || auth.User.IsOrganizationOwner != *cfg.IsOrganizationOwner {
return c.
Status(fiber.StatusForbidden).
JSON(helpers.Detail("You need to be the organization owner."))
}
}
return c.Next()
}
}
func UserAccessTokenAuthenticated(c *fiber.Ctx) error {
return User(&userPermissionMiddlewareConfig{
IsAuthenticated: pointer.Get(true),
AuthKind: pointer.Get(authentication.AuthKindRestApiUserAccessToken),
})(c)
}
func UserAuthenticated(c *fiber.Ctx) error {
return User(&userPermissionMiddlewareConfig{
IsAuthenticated: pointer.Get(true),
})(c)
}
func UserBasicAuthenticated(c *fiber.Ctx) error {
return User(&userPermissionMiddlewareConfig{
IsAuthenticated: pointer.Get(true),
AuthKind: pointer.Get(authentication.AuthKindRestApiUserBasic),
})(c)
}
func UserOwner(c *fiber.Ctx) error {
return User(&userPermissionMiddlewareConfig{
IsOrganizationOwner: pointer.Get(true),
})(c)
}
func UserUnauthenticated(c *fiber.Ctx) error {
return User(&userPermissionMiddlewareConfig{
IsAuthenticated: pointer.Get(false),
})(c)
}