-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
79 lines (65 loc) · 2.99 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
69
70
71
72
73
74
75
76
77
78
79
package app
import (
"../models"
u "../utils"
"context"
"fmt"
jwt "github.com/dgrijalva/jwt-go"
"net/http"
"os"
"strings"
)
var JwtAuthentication = func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
notAuth := []string{"/api/user/new", "/api/user/login"} // Список эндпоинтов, для которых не требуется авторизация
requestPath := r.URL.Path // текущий путь запроса
// проверяем, не требует ли запрос аутентификации, обслуживаем запрос, если он не нужен
for _, value := range notAuth {
if value == requestPath {
next.ServeHTTP(w, r)
return
}
}
response := make(map[string]interface{})
tokenHeader := r.Header.Get("Authorization") // Получение токена
if tokenHeader == "" { // Токен отсутствует, возвращаем 403 http-код Unauthorized
response = u.Message(false, "Missing auth token")
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json") // not necessary??
u.Respond(w, response)
return
}
splitted := strings.Split(tokenHeader, " ") // Токен обычно поставляется в формате `Bearer {token-body}`, мы проверяем, соответствует ли полученный токен этому требованию
if len(splitted) != 2 {
response = u.Message(false, "Invalid/Malformed auth token")
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json") // not necessary??
u.Respond(w, response)
return
}
tokenPart := splitted[1] // Получаем вторую часть токена
tk := &models.Token{}
token, err := jwt.ParseWithClaims(tokenPart, tk, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("token_password")), nil
})
if err != nil { // Неправильный токен, как правило, возвращает 403 http-код
response = u.Message(false, "Malformed authentication token")
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json") // not necessary??
u.Respond(w, response)
return
}
if !token.Valid { // токен недействителен, возможно, не подписан на этом сервере
response = u.Message(false, "Token is not valid.")
w.WriteHeader(http.StatusForbidden)
w.Header().Add("Content-Type", "application/json")
u.Respond(w, response)
return
}
// Всё прошло хорошо, продолжаем выполнение запроса
println(fmt.Sprintf("User %d", tk.UserId)) // Полезно для мониторинга
ctx := context.WithValue(r.Context(), "user", tk.UserId)
r = r.WithContext(ctx)
next.ServeHTTP(w, r) // передать управление следующему обработчику!
})
}