-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
108 lines (89 loc) · 2.21 KB
/
helper.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
Raffael Rot
V0.1.1
*/
package helper
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
"net/http"
"strings"
)
type SessionResponse struct {
Code int `json:"code"`
Status string `json:"status"`
Data struct {
Token string `json:"token"`
} `json:"data"`
}
type WebResponse struct {
Code int `json:"code"`
Status string `json:"status"`
Data interface{} `json:"data,omitempty"`
}
func PanicIfError(err error) {
if err != nil {
panic(err)
}
}
func ReadRequestBody(r *http.Request, result interface{}) {
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(result)
PanicIfError(err)
}
func ReadResponseBody(r *http.Response, result interface{}) {
decode := json.NewDecoder(r.Body)
err := decode.Decode(result)
PanicIfError(err)
}
func WriteResponseBody(write http.ResponseWriter, response interface{}) {
write.Header().Add("Content-Type", "application/json")
encoder := json.NewEncoder(write)
err := encoder.Encode(response)
PanicIfError(err)
}
func CommitOrRollback(tx *sql.Tx) {
err := recover()
if err != nil {
errRollback := tx.Rollback()
PanicIfError(errRollback)
panic(err)
} else {
errCommit := tx.Commit()
PanicIfError(errCommit)
}
}
type JWTClaims struct {
UserId uuid.UUID `json:"user_id"`
jwt.RegisteredClaims
}
func ParseToken(authorizationToken string, secret string) (*JWTClaims, error) {
encodedToken := strings.TrimPrefix(authorizationToken, "Bearer ")
token, err := jwt.ParseWithClaims(encodedToken, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
PanicIfError(err)
if claims, ok := token.Claims.(*JWTClaims); ok && token.Valid {
return claims, nil
} else {
return nil, fmt.Errorf("invalid token")
}
}
func VerifySession(url string) *JWTClaims {
response, err := http.Get(url)
PanicIfError(err)
session := new(SessionResponse)
ReadResponseBody(response, &session)
token, err := jwt.ParseWithClaims(session.Data.Token, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte("my-secret-key"), nil
})
PanicIfError(err)
if claims, ok := token.Claims.(*JWTClaims); ok && token.Valid {
return claims
} else {
return nil
}
}