made LoginHandler slightly less awful

Signed-off-by: ari melody <ari@arimelody.me>
This commit is contained in:
ari melody 2024-07-31 04:21:52 +01:00
parent 5631c4bd87
commit 4b58a27fdc
2 changed files with 87 additions and 67 deletions

View file

@ -100,64 +100,23 @@ func LoginHandler() http.Handler {
return
}
// let's get an oauth token!
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/oauth2/token", discord.API_ENDPOINT),
strings.NewReader(url.Values{
"client_id": {discord.CLIENT_ID},
"client_secret": {discord.CLIENT_SECRET},
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {discord.MY_REDIRECT_URI},
}.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := http.DefaultClient.Do(req)
auth_token, err := discord.GetOAuthTokenFromCode(code)
if err != nil {
fmt.Printf("Failed to retrieve OAuth token: %s\n", err)
fmt.Printf("Failed to retrieve discord access token: %s\n", err)
w.WriteHeader(500)
w.Write([]byte("Internal server error"))
return
}
oauth := discord.AccessTokenResponse{}
err = json.NewDecoder(res.Body).Decode(&oauth)
discord_user, err := discord.GetDiscordUserFromAuth(auth_token)
if err != nil {
fmt.Printf("Failed to parse OAuth response data from discord: %s\n", err)
w.WriteHeader(500)
w.Write([]byte("Internal server error"))
return
}
res.Body.Close()
discord_access_token := oauth.AccessToken
// let's get authorisation information!
req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/oauth2/@me", discord.API_ENDPOINT), nil)
req.Header.Add("Authorization", "Bearer " + discord_access_token)
res, err = http.DefaultClient.Do(req)
if err != nil {
fmt.Printf("Failed to retrieve discord auth information: %s\n", err)
fmt.Printf("Failed to retrieve discord user information: %s\n", err)
w.WriteHeader(500)
w.Write([]byte("Internal server error"))
return
}
auth_info := discord.AuthInfoResponse{}
err = json.NewDecoder(res.Body).Decode(&auth_info)
if err != nil {
fmt.Printf("Failed to parse auth information from discord: %s\n", err)
w.WriteHeader(500)
w.Write([]byte("Internal server error"))
return
}
res.Body.Close()
discord_user_id := auth_info.User.Id
if discord_user_id != ADMIN_ID_DISCORD {
if discord_user.Id != ADMIN_ID_DISCORD {
// TODO: unauthorized user. revoke the token
w.WriteHeader(401)
w.Write([]byte("Unauthorized"))
@ -165,7 +124,7 @@ func LoginHandler() http.Handler {
}
// login success!
session := CreateSession(auth_info.User.Username)
session := CreateSession(discord_user.Username)
sessions = append(sessions, &session)
cookie := http.Cookie{}