-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
61 lines (58 loc) · 1.62 KB
/
middleware.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
package main
import (
"net/http"
"strings"
"time"
)
func (s *Server) ValidateToken(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
parts := strings.Split(token, ":")
if token == "" || len(parts) != 2 {
http.Error(w, "Token is missing, malformed, or you are stupid.", http.StatusUnauthorized)
return
}
user, err := s.DB.GetUserByEmail(parts[0])
if err != nil {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
if user.Key != parts[1] {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
next(w, r)
}
}
func (s *Server) ValidateSessionToken(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token, err := s.GetTokenFromSession(r)
if err != nil {
// fmt.Println("Error getting token from session")
token := r.Header.Get("Authorization")
// fmt.Println("Token from header:", token)
parts := strings.Split(token, ":")
if token == "" || len(parts) != 2 {
http.Error(w, "Token is missing, malformed, or you are stupid.", http.StatusUnauthorized)
return
}
user, err := s.DB.GetUserByEmail(parts[0])
if err != nil {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
if user.Key != parts[1] {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
next(w, r)
return
}
tk, err := s.DB.GetTokenByValue(token)
if err != nil || tk.ExpiresAt.Before(time.Now()) {
http.Error(w, "Invalid session token", http.StatusUnauthorized)
return
}
next(w, r)
}
}