|
5 | 5 | package api |
6 | 6 |
|
7 | 7 | import ( |
| 8 | + "bytes" |
| 9 | + "encoding/json" |
8 | 10 | "errors" |
9 | 11 | "fmt" |
10 | 12 | "log" |
@@ -191,6 +193,57 @@ func (handler *V1Handler) postLobby(writer http.ResponseWriter, request *http.Re |
191 | 193 | state.AddLobby(lobby) |
192 | 194 | } |
193 | 195 |
|
| 196 | +type discordAuthenticatePayload struct { |
| 197 | + Code string `json:"code"` |
| 198 | +} |
| 199 | + |
| 200 | +type discordTokenRequest struct { |
| 201 | + ClientId string `json:"client_id"` |
| 202 | + ClientSecret string `json:"client_secret"` |
| 203 | + GrantType string `json:"grant_type"` |
| 204 | + Code string `json:"code"` |
| 205 | +} |
| 206 | +type discordTokenResponse struct { |
| 207 | + AccessCode string `json:"access_code"` |
| 208 | +} |
| 209 | + |
| 210 | +func (handler *V1Handler) discordAuthenticate(writer http.ResponseWriter, request *http.Request) { |
| 211 | + decoder := json.NewDecoder(request.Body) |
| 212 | + var payload discordAuthenticatePayload |
| 213 | + if err := decoder.Decode(&payload); err != nil { |
| 214 | + http.Error(writer, "error decoding payload", http.StatusBadRequest) |
| 215 | + return |
| 216 | + } |
| 217 | + |
| 218 | + discordPayload := bytes.NewBuffer(nil) |
| 219 | + if err := json.NewEncoder(discordPayload).Encode(discordTokenRequest{ |
| 220 | + ClientId: "1320396325925163070", |
| 221 | + ClientSecret: handler.cfg.DiscordApiKey, |
| 222 | + GrantType: "authorization_code", |
| 223 | + Code: payload.Code, |
| 224 | + }); err != nil { |
| 225 | + http.Error(writer, "error retrieving token from discord", http.StatusInternalServerError) |
| 226 | + return |
| 227 | + } |
| 228 | + discordRequest, err := http.NewRequest(http.MethodPost, "https://discord.com/api/oauth2/token", discordPayload) |
| 229 | + if err != nil { |
| 230 | + http.Error(writer, "internal server error", http.StatusInternalServerError) |
| 231 | + return |
| 232 | + } |
| 233 | + |
| 234 | + response, err := http.DefaultClient.Do(discordRequest) |
| 235 | + if err != nil { |
| 236 | + http.Error(writer, "error retrieving token from discord", http.StatusInternalServerError) |
| 237 | + return |
| 238 | + } |
| 239 | + |
| 240 | + var discordTokenResponse discordTokenResponse |
| 241 | + if err := json.NewDecoder(response.Body).Decode(&discordTokenResponse); err != nil { |
| 242 | + http.Error(writer, "error retrieving token from discord", http.StatusInternalServerError) |
| 243 | + return |
| 244 | + } |
| 245 | +} |
| 246 | + |
194 | 247 | func (handler *V1Handler) postPlayer(writer http.ResponseWriter, request *http.Request) { |
195 | 248 | lobby := state.GetLobby(request.PathValue("lobby_id")) |
196 | 249 | if lobby == nil { |
|
0 commit comments