1
|
|
|
package routes |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"fmt" |
5
|
|
|
"github.com/gofiber/fiber/v2" |
6
|
|
|
"github.com/memnix/memnixrest/app/auth" |
7
|
|
|
"github.com/memnix/memnixrest/pkg/logger" |
8
|
|
|
"github.com/memnix/memnixrest/pkg/models" |
9
|
|
|
"github.com/memnix/memnixrest/pkg/queries" |
10
|
|
|
"strings" |
11
|
|
|
) |
12
|
|
|
|
13
|
|
|
func IsConnectedMiddleware() func(c *fiber.Ctx) error { |
14
|
|
|
return func(c *fiber.Ctx) error { |
15
|
|
|
|
16
|
|
|
path := strings.TrimLeft(c.Path(), "/v1") |
17
|
|
|
path = strings.TrimRight(path, "/") |
18
|
|
|
|
19
|
|
|
p := routesMap["/"+path].Permission |
20
|
|
|
|
21
|
|
|
if p == models.PermNone { |
22
|
|
|
return c.Next() |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
statusCode, response := auth.IsConnected(c) // Check if connected |
26
|
|
|
|
27
|
|
|
// Check statusCode |
28
|
|
|
if statusCode != fiber.StatusOK { |
29
|
|
|
c.Status(statusCode) |
30
|
|
|
// Return response |
31
|
|
|
return queries.AuthError(c, &response) |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
user := response.User // Get user from response |
35
|
|
|
|
36
|
|
|
// Check permission |
37
|
|
|
if user.Permissions < p { |
38
|
|
|
// Log permission error |
39
|
|
|
log := logger.CreateLog(fmt.Sprintf("Permission error: %s | had %s but tried %s", user.Email, user.Permissions.ToString(), p.ToString()), logger.LogPermissionForbidden).SetType(logger.LogTypeWarning).AttachIDs(user.ID, 0, 0) |
40
|
|
|
_ = log.SendLog() // Send log |
41
|
|
|
c.Status(fiber.StatusUnauthorized) // Unauthorized Status |
42
|
|
|
// Return response |
43
|
|
|
return queries.AuthError(c, &models.ResponseAuth{ |
44
|
|
|
Success: false, |
45
|
|
|
Message: "You don't have the right permissions to perform this request.", |
46
|
|
|
}) |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
// Validate permissions |
50
|
|
|
c.Locals("user", user) // Set user in locals |
51
|
|
|
return c.Next() |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|