| 22 | ) |
| 23 | |
| 24 | func authenticateHandler(w http.ResponseWriter, r *http.Request) { |
| 25 | // This is required to populate r.Form. |
| 26 | if err := r.ParseForm(); err != nil { |
| 27 | w.WriteHeader(http.StatusBadRequest) |
| 28 | return |
| 29 | } |
| 30 | |
| 31 | // Retrieve and validate the POST-ed credentials |
| 32 | username := r.Form.Get("username") |
| 33 | password := r.Form.Get("password") |
| 34 | |
| 35 | // Authenticate the password, responding to errors appropriately |
| 36 | valid, err := authenticatePassword(username, password) |
| 37 | if err != nil { |
| 38 | w.WriteHeader(http.StatusInternalServerError) |
| 39 | return |
| 40 | } else if !valid { |
| 41 | w.WriteHeader(http.StatusUnauthorized) |
| 42 | return |
| 43 | } |
| 44 | |
| 45 | // Password is valid; build a new token |
| 46 | tokenString, err := buildToken(username) |
| 47 | if err != nil { |
| 48 | w.WriteHeader(http.StatusInternalServerError) |
| 49 | return |
| 50 | } |
| 51 | |
| 52 | // Respond with the new token string |
| 53 | fmt.Fprint(w, tokenString) |
| 54 | } |
| 55 | |
| 56 | // authenticatePassword always returns true and a nil error, just |
| 57 | // for the sake of demonstration |