-
Notifications
You must be signed in to change notification settings - Fork 66
/
auth.go
68 lines (58 loc) · 1.77 KB
/
auth.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
package util
import (
"crypto/sha256"
b64 "encoding/base64"
"fmt"
"net/http"
"github.com/labstack/echo/v4"
)
func isEntityOwner(uID, entityID uint, entity string) error {
if uID != entityID {
return HttpError{
Code: http.StatusForbidden,
Reason: ERR_NOT_AUTHORIZED,
Details: fmt.Sprintf("User (%d) is not authorized for %s (%d)", uID, entity, entityID),
}
}
return nil
}
func IsCollectionOwner(uID, entityID uint) error {
return isEntityOwner(uID, entityID, "collection")
}
func IsContentOwner(uID, entityID uint) error {
return isEntityOwner(uID, entityID, "content")
}
func GetPasswordHash(password, salt string, dialector string) string {
switch dialector { // can be "postgres", "sqlite"
case "sqlite": // for sqlite, embedded db.
return GetPasswordHashBase(password, salt)
default: // default (postgres or other rdbms)
return GetPasswordHashBase64(password, salt)
}
}
func GetPasswordHashBase(password, salt string) string {
passHashBytes := sha256.Sum256([]byte(password + "." + salt))
return string(passHashBytes[:])
}
func GetPasswordHashBase64(password, salt string) string {
passHashBytes := sha256.Sum256([]byte(password + "." + salt))
return b64.StdEncoding.EncodeToString(passHashBytes[:])
}
func GetTokenHash(token string) string {
tokenHashBytes := sha256.Sum256([]byte(token))
// needs to be URL-encodable to send revoke token requests by hash
return b64.RawURLEncoding.EncodeToString(tokenHashBytes[:])
}
func WithUser(f func(echo.Context, *User) error) func(echo.Context) error {
return func(c echo.Context) error {
u, ok := c.Get("user").(*User)
if !ok {
return &HttpError{
Code: http.StatusUnauthorized,
Reason: ERR_INVALID_AUTH,
Details: "endpoint not called with proper authentication",
}
}
return f(c, u)
}
}