handlers.go (6049B)
1 package main 2 3 import ( 4 "database/sql" 5 "encoding/json" 6 "errors" 7 "fmt" 8 "log" 9 "net/http" 10 "net/url" 11 "strconv" 12 "strings" 13 "time" 14 ) 15 16 // Used for the calls to the other services, so a hung one cannot hang us. 17 var client = &http.Client{Timeout: 5 * time.Second} 18 19 func writeJSON(w http.ResponseWriter, status int, v any) { 20 w.Header().Set("Content-Type", "application/json") 21 w.WriteHeader(status) 22 json.NewEncoder(w).Encode(v) 23 } 24 25 // bearer returns the token of an "Authorization: Bearer <token>" header, or "". 26 func bearer(r *http.Request) string { 27 h := r.Header.Get("Authorization") 28 if len(h) > 7 && strings.EqualFold(h[:7], "bearer ") { 29 return strings.TrimSpace(h[7:]) 30 } 31 return "" 32 } 33 34 // session is an authenticated request: its token and the user that owns it. 35 type session struct { 36 token string 37 username string 38 } 39 40 // authenticate asks the auth service whose session the token of the request 41 // is. It returns ok == false after writing the error response. 42 func authenticate(w http.ResponseWriter, r *http.Request) (s session, ok bool) { 43 token := bearer(r) 44 if token == "" { 45 http.Error(w, "missing bearer token", http.StatusUnauthorized) 46 return s, false 47 } 48 49 resp, err := client.Get(authURL + "/" + url.PathEscape(token)) 50 if err != nil { 51 log.Println("auth request:", err) 52 http.Error(w, "auth service unavailable", http.StatusServiceUnavailable) 53 return s, false 54 } 55 defer resp.Body.Close() 56 57 switch resp.StatusCode { 58 case http.StatusOK: 59 case http.StatusBadRequest, http.StatusUnauthorized: 60 http.Error(w, "invalid token", http.StatusUnauthorized) 61 return s, false 62 default: 63 http.Error(w, "auth service error: "+resp.Status, http.StatusServiceUnavailable) 64 return s, false 65 } 66 67 var body struct{ Username string } 68 if err := json.NewDecoder(resp.Body).Decode(&body); err != nil || body.Username == "" { 69 log.Println("auth response without username:", err) 70 http.Error(w, "auth service error: bad response", http.StatusServiceUnavailable) 71 return s, false 72 } 73 return session{token: token, username: body.Username}, true 74 } 75 76 // ownUsername checks that the username of the body, if any, is the one of the 77 // session: a user can only act on their own signups. It returns the username 78 // to use, or ok == false after writing the error response. 79 func ownUsername(w http.ResponseWriter, s session, fromBody string) (string, bool) { 80 if fromBody != "" && fromBody != s.username { 81 http.Error(w, "cannot act on behalf of another user", http.StatusForbidden) 82 return "", false 83 } 84 return s.username, true 85 } 86 87 // eventExists asks the event service (with the caller's token) if the event 88 // exists. It returns false after writing the error response. 89 func eventExists(w http.ResponseWriter, token string, id int32) bool { 90 req, err := http.NewRequest("GET", fmt.Sprintf("%s/event/%d", eventURL, id), nil) 91 if err != nil { 92 log.Println("event request:", err) 93 http.Error(w, "internal server error", http.StatusInternalServerError) 94 return false 95 } 96 req.Header.Set("Authorization", "Bearer "+token) 97 98 resp, err := client.Do(req) 99 if err != nil { 100 log.Println("event request:", err) 101 http.Error(w, "event service unavailable", http.StatusServiceUnavailable) 102 return false 103 } 104 defer resp.Body.Close() 105 106 if resp.StatusCode == http.StatusOK { 107 return true 108 } 109 // 4xx (e.g. 404, event not found) goes back to the caller as is. 110 if resp.StatusCode >= 400 && resp.StatusCode < 500 { 111 http.Error(w, "event service: "+resp.Status, resp.StatusCode) 112 } else { 113 http.Error(w, "event service: "+resp.Status, http.StatusServiceUnavailable) 114 } 115 return false 116 } 117 118 // POST /signup {"event_id": 1} 119 // Signs up the owner of the token. "username" may be in the body, but it must 120 // be the owner's. 121 func signup(w http.ResponseWriter, r *http.Request) { 122 sess, ok := authenticate(w, r) 123 if !ok { 124 return 125 } 126 127 var s Signup 128 if err := json.NewDecoder(r.Body).Decode(&s); err != nil { 129 http.Error(w, "invalid JSON", http.StatusBadRequest) 130 return 131 } 132 if s.Username, ok = ownUsername(w, sess, s.Username); !ok { 133 return 134 } 135 if !eventExists(w, sess.token, s.EventID) { 136 return 137 } 138 139 id, err := NewSignup(s.Username, s.EventID) 140 if errors.Is(err, errDuplicate) { 141 http.Error(w, "already signed up for this event", http.StatusConflict) 142 return 143 } 144 if err != nil { 145 log.Println("new signup:", err) 146 http.Error(w, "internal server error", http.StatusInternalServerError) 147 return 148 } 149 150 s.ID, s.PresenceConfirmed = id, 0 151 writeJSON(w, http.StatusCreated, s) 152 } 153 154 // PUT /presence {"event_id": 1, "presence_confirmed": 1} 155 // presence_confirmed is 1 to confirm and 0 to unconfirm. Changes the signup of 156 // the owner of the token; "username" may be in the body, but it must be the 157 // owner's. 158 func presence(w http.ResponseWriter, r *http.Request) { 159 sess, ok := authenticate(w, r) 160 if !ok { 161 return 162 } 163 164 var s Signup 165 if err := json.NewDecoder(r.Body).Decode(&s); err != nil { 166 http.Error(w, "invalid JSON", http.StatusBadRequest) 167 return 168 } 169 if s.Username, ok = ownUsername(w, sess, s.Username); !ok { 170 return 171 } 172 if s.PresenceConfirmed != 0 && s.PresenceConfirmed != 1 { 173 http.Error(w, "presence_confirmed must be 0 or 1", http.StatusBadRequest) 174 return 175 } 176 177 err := RegisterPresence(s) 178 if errors.Is(err, sql.ErrNoRows) { 179 http.Error(w, "signup not found", http.StatusNotFound) 180 return 181 } 182 if err != nil { 183 log.Println("register presence:", err) 184 http.Error(w, "internal server error", http.StatusInternalServerError) 185 return 186 } 187 188 w.WriteHeader(http.StatusOK) 189 } 190 191 // GET /signup/{id} 192 func check_signup(w http.ResponseWriter, r *http.Request) { 193 if _, ok := authenticate(w, r); !ok { 194 return 195 } 196 197 id, err := strconv.ParseInt(r.PathValue("id"), 10, 32) 198 if err != nil { 199 http.Error(w, "invalid id", http.StatusBadRequest) 200 return 201 } 202 203 s, err := GetByID(int32(id)) 204 if errors.Is(err, sql.ErrNoRows) { 205 http.Error(w, "signup not found", http.StatusNotFound) 206 return 207 } 208 if err != nil { 209 log.Println("get signup:", err) 210 http.Error(w, "internal server error", http.StatusInternalServerError) 211 return 212 } 213 214 writeJSON(w, http.StatusOK, s) 215 }