/
authMiddleware.go
79 lines (66 loc) 路 1.64 KB
/
authMiddleware.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
package middleware
import (
"log"
"net/http"
"time"
"github.com/franpog859/cleanaux-backend/content-service/internal/model"
"github.com/gin-gonic/gin"
)
const (
authURL = "http://auth-service-internal/authorize"
requestTimeout = 10
)
// Auth calls auth-service to authorize user
func Auth(context *gin.Context) {
authHeader := context.GetHeader(model.AuthHeaderKey)
if authHeader == "" {
log.Printf("No Authorization header provided")
context.AbortWithStatus(http.StatusUnauthorized)
return
}
status, err := authorize(authHeader)
if err != nil {
log.Printf("Error while authorizing user: %v", err)
context.AbortWithStatus(http.StatusUnauthorized)
return
}
if status != http.StatusOK {
log.Printf("Status: %d, retrying...", status)
status, err = authorize(authHeader)
if err != nil {
log.Printf("Error while authorizing user: %v", err)
context.AbortWithStatus(http.StatusUnauthorized)
return
}
if status != http.StatusOK {
log.Printf("User is not authorized. Status: %d", status)
context.AbortWithStatus(status)
return
}
}
context.Next()
}
func authorize(header string) (int, error) {
status, err := post(
authURL,
map[string]string{
model.AuthHeaderKey: header,
},
)
return status, err
}
func post(postURL string, headers map[string]string) (int, error) {
req, _ := http.NewRequest("POST", postURL, nil)
for key, value := range headers {
req.Header.Add(key, value)
}
client := &http.Client{
Timeout: time.Second * requestTimeout,
}
resp, err := client.Do(req)
if err != nil {
return http.StatusInternalServerError, err
}
defer resp.Body.Close()
return resp.StatusCode, nil
}