-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.go
More file actions
38 lines (32 loc) · 1.03 KB
/
middleware.go
File metadata and controls
38 lines (32 loc) · 1.03 KB
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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
)
func tokenMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
req := struct {
APIToken string `json:"api_token"`
}{""}
err := decoder.Decode(&req)
if err != nil {
failWithStatusCode(err, "Token Error", w, http.StatusForbidden)
}
if tokenCache[req.APIToken] == false {
// Have to get from DB
apiToken := ""
queryString := "SELECT current_status FROM users WHERE api_token LIKE $1;"
stmt, _ := db.Prepare(queryString)
err = stmt.QueryRow(req.APIToken).Scan(&apiToken)
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "Token Validation failed")
}
tokenCache[apiToken] = true
}
next.ServeHTTP(w, r)
})
}