-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.go
58 lines (55 loc) · 1.46 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
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/context"
"golang.org/x/exp/errors"
)
// ValidateMiddleware provides authentication of user credentials
func ValidateMiddleware(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var user string
if r.Method == "GET" {
query := r.URL.Query()
user = query.Get("user") //user="bla"
if user == "" {
w.Write([]byte("Please provide user name"))
}
} else if r.Method == "POST" {
var otpToken OtpToken
err := json.NewDecoder(r.Body).Decode(&otpToken)
if err != nil {
log.Println("error", err)
json.NewEncoder(w).Encode(err)
return
}
user = otpToken.User
}
secret := findUserSecret(user)
if secret == "" {
err := errors.New("Unable to find user credentials, please obtain proper QR code")
json.NewEncoder(w).Encode(err)
return
}
bearerToken, err := getBearerToken(r.Header.Get("authorization"))
if err != nil {
json.NewEncoder(w).Encode(err)
return
}
// for verification we can use either user's secret
// or server secret
// in latter case it should be global and available to all APIs
decodedToken, err := VerifyJwt(bearerToken, secret)
if err != nil {
json.NewEncoder(w).Encode(err)
return
}
if decodedToken["authorized"] == true {
context.Set(r, "decoded", decodedToken)
next(w, r)
} else {
json.NewEncoder(w).Encode("2FA is required")
}
})
}