| skipped 61 lines |
62 | 62 | | |
63 | 63 | | func RequireAPIKey(handler http.Handler) http.HandlerFunc { |
64 | 64 | | return func(w http.ResponseWriter, r *http.Request) { |
65 | | - | r.ParseForm() |
66 | | - | ak := r.Form.Get("api_key") |
67 | 65 | | w.Header().Set("Access-Control-Allow-Origin", "*") |
68 | 66 | | if r.Method == "OPTIONS" { |
69 | 67 | | w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS") |
| skipped 1 lines |
71 | 69 | | w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") |
72 | 70 | | return |
73 | 71 | | } |
| 72 | + | r.ParseForm() |
| 73 | + | ak := r.Form.Get("api_key") |
| 74 | + | // If we can't get the API key, we'll also check for the |
| 75 | + | // Authorization Bearer token |
| 76 | + | if ak == "" { |
| 77 | + | tokens, ok := r.Header["Authorization"] |
| 78 | + | if ok && len(tokens) >= 1 { |
| 79 | + | ak = tokens[0] |
| 80 | + | ak = strings.TrimPrefix(ak, "Bearer ") |
| 81 | + | } |
| 82 | + | } |
74 | 83 | | if ak == "" { |
75 | 84 | | JSONError(w, 400, "API Key not set") |
76 | 85 | | return |
77 | | - | } else { |
78 | | - | u, err := models.GetUserByAPIKey(ak) |
79 | | - | if err != nil { |
80 | | - | JSONError(w, 400, "Invalid API Key") |
81 | | - | return |
82 | | - | } |
83 | | - | r = ctx.Set(r, "user_id", u.Id) |
84 | | - | r = ctx.Set(r, "api_key", ak) |
85 | | - | handler.ServeHTTP(w, r) |
| 86 | + | } |
| 87 | + | u, err := models.GetUserByAPIKey(ak) |
| 88 | + | if err != nil { |
| 89 | + | JSONError(w, 400, "Invalid API Key") |
| 90 | + | return |
86 | 91 | | } |
| 92 | + | r = ctx.Set(r, "user_id", u.Id) |
| 93 | + | r = ctx.Set(r, "api_key", ak) |
| 94 | + | handler.ServeHTTP(w, r) |
87 | 95 | | } |
88 | 96 | | } |
89 | 97 | | |
| skipped 23 lines |