-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
232 lines (195 loc) · 6.21 KB
/
auth.go
File metadata and controls
232 lines (195 loc) · 6.21 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package fiberoapi
import (
"fmt"
"reflect"
"strings"
"github.com/gofiber/fiber/v2"
)
// AuthContext contains user authentication details
type AuthContext struct {
UserID string `json:"user_id"`
Roles []string `json:"roles"`
Scopes []string `json:"scopes"`
Claims map[string]interface{} `json:"claims"`
}
// ResourcePermission defines permissions on a resource
type ResourcePermission struct {
ResourceType string `json:"resource_type"`
ResourceID string `json:"resource_id"`
Actions []string `json:"actions"` // ["read", "write", "delete", "share"]
}
// AuthorizationService interface for permission checks
type AuthorizationService interface {
// Authentication
ValidateToken(token string) (*AuthContext, error)
// Global authorization (roles/scopes)
HasRole(ctx *AuthContext, role string) bool
HasScope(ctx *AuthContext, scope string) bool
// Dynamic authorization on resources
CanAccessResource(ctx *AuthContext, resourceType, resourceID, action string) (bool, error)
GetUserPermissions(ctx *AuthContext, resourceType, resourceID string) (*ResourcePermission, error)
}
// SecurityScheme for OpenAPI
type SecurityScheme struct {
Type string `json:"type"`
Scheme string `json:"scheme,omitempty"`
BearerFormat string `json:"bearerFormat,omitempty"`
In string `json:"in,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Flows map[string]interface{} `json:"flows,omitempty"`
}
// GetAuthContext extracts the authentication context from Fiber
func GetAuthContext(c *fiber.Ctx) (*AuthContext, error) {
auth, ok := c.Locals("auth").(*AuthContext)
if !ok {
return nil, fmt.Errorf("no authentication context found")
}
return auth, nil
}
// RequireResourceAccess checks permissions in handlers
func RequireResourceAccess(c *fiber.Ctx, authService AuthorizationService, resourceType, resourceID, action string) error {
authCtx, err := GetAuthContext(c)
if err != nil {
return c.Status(401).JSON(fiber.Map{
"error": "Authentication required",
})
}
canAccess, err := authService.CanAccessResource(authCtx, resourceType, resourceID, action)
if err != nil {
return c.Status(500).JSON(fiber.Map{
"error": "Authorization check failed",
"details": err.Error(),
})
}
if !canAccess {
return c.Status(403).JSON(fiber.Map{
"error": "Insufficient permissions",
"resource": resourceType,
"action": action,
})
}
return nil
}
// BearerTokenMiddleware creates a JWT/Bearer middleware
func BearerTokenMiddleware(validator AuthorizationService) fiber.Handler {
return func(c *fiber.Ctx) error {
authHeader := c.Get("Authorization")
if authHeader == "" {
return c.Status(401).JSON(fiber.Map{
"error": "Authorization header required",
})
}
if !strings.HasPrefix(authHeader, "Bearer ") {
return c.Status(401).JSON(fiber.Map{
"error": "Bearer token required",
})
}
token := strings.TrimPrefix(authHeader, "Bearer ")
authCtx, err := validator.ValidateToken(token)
if err != nil {
return c.Status(401).JSON(fiber.Map{
"error": "Invalid token",
"details": err.Error(),
})
}
// Store auth context for later use
c.Locals("auth", authCtx)
return c.Next()
}
}
// RoleGuard middleware for role verification
func RoleGuard(validator AuthorizationService, requiredRoles ...string) fiber.Handler {
return func(c *fiber.Ctx) error {
authCtx, err := GetAuthContext(c)
if err != nil {
return c.Status(401).JSON(fiber.Map{
"error": "Authentication required",
})
}
for _, role := range requiredRoles {
if !validator.HasRole(authCtx, role) {
return c.Status(403).JSON(fiber.Map{
"error": "Insufficient permissions",
"required_role": role,
})
}
}
return c.Next()
}
}
// validateAuthorization validates permissions based on tags
func validateAuthorization(c *fiber.Ctx, input interface{}, authService AuthorizationService) error {
if authService == nil {
return nil
}
// Extract and validate the token directly
authHeader := c.Get("Authorization")
if authHeader == "" {
return fmt.Errorf("authentication required")
}
// Check Bearer format
if !strings.HasPrefix(authHeader, "Bearer ") {
return fmt.Errorf("invalid authorization header format")
}
token := strings.TrimPrefix(authHeader, "Bearer ")
// Validate the token
authCtx, err := authService.ValidateToken(token)
if err != nil {
return fmt.Errorf("invalid token: %v", err)
}
// Store auth context for later use
c.Locals("auth", authCtx)
// Analyze authorization tags in the struct
return validateResourceAccess(c, authCtx, input, authService)
}
// validateResourceAccess validates resource access based on tags
func validateResourceAccess(c *fiber.Ctx, authCtx *AuthContext, input interface{}, authService AuthorizationService) error {
inputValue := reflect.ValueOf(input)
inputType := reflect.TypeOf(input)
if isPointerType(inputType) {
inputValue = inputValue.Elem()
inputType = inputType.Elem()
}
if inputType.Kind() != reflect.Struct {
return nil
}
for i := 0; i < inputType.NumField(); i++ {
field := inputType.Field(i)
// New tags for authorization
if resourceTag := field.Tag.Get("resource"); resourceTag != "" {
actionTag := field.Tag.Get("action")
if actionTag == "" {
actionTag = inferActionFromMethod(c.Method())
}
// Get the resource ID field value
fieldValue := inputValue.Field(i)
if fieldValue.Kind() == reflect.String {
resourceID := fieldValue.String()
canAccess, err := authService.CanAccessResource(authCtx, resourceTag, resourceID, actionTag)
if err != nil {
return fmt.Errorf("authorization check failed: %w", err)
}
if !canAccess {
return fmt.Errorf("insufficient permissions for %s %s on %s", actionTag, resourceTag, resourceID)
}
}
}
}
return nil
}
// inferActionFromMethod infers the action from the HTTP method
func inferActionFromMethod(method string) string {
switch method {
case "GET":
return "read"
case "POST":
return "create"
case "PUT", "PATCH":
return "write"
case "DELETE":
return "delete"
default:
return "read"
}
}