Passed
Push — main ( f6597a...58b626 )
by Yume
01:31 queued 12s
created

oauth.GetDiscordAccessToken   A

Complexity

Conditions 4

Size

Total Lines 49
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 30
nop 1
dl 0
loc 49
rs 9.16
c 0
b 0
f 0
1
package oauth
2
3
import (
4
	"bytes"
5
	"fmt"
6
	"io"
7
	"net/http"
8
9
	"github.com/memnix/memnix-rest/config"
10
	"github.com/memnix/memnix-rest/infrastructures"
11
	"github.com/rs/zerolog/log"
12
)
13
14
func GetDiscordAccessToken(code string) (string, error) {
15
	reqBody := bytes.NewBuffer([]byte(fmt.Sprintf(
16
		"client_id=%s&client_secret=%s&grant_type=authorization_code&redirect_uri=%s&code=%s&scope=identify,email",
17
		infrastructures.AppConfig.DiscordConfig.ClientID,
18
		infrastructures.AppConfig.DiscordConfig.ClientSecret,
19
		config.GetCurrentURL()+"/v2/security/discord_callback",
20
		code,
21
	)))
22
23
	// POST request to set URL
24
	req, reqerr := http.NewRequest(
25
		"POST",
26
		"https://discord.com/api/oauth2/token",
27
		reqBody,
28
	)
29
	if reqerr != nil {
30
		log.Info().Msg("Request failed")
31
	}
32
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
33
	req.Header.Set("Accept", "application/json")
34
35
	// Get the response
36
	resp, resperr := http.DefaultClient.Do(req)
37
	if resperr != nil {
38
		log.Info().Msg("Response failed")
39
	}
40
41
	// Response body converted to stringified JSON
42
	respbody, _ := io.ReadAll(resp.Body)
43
44
	// Represents the response received from Github
45
	type discordAccessTokenResponse struct {
46
		AccessToken  string `json:"access_token"`
47
		TokenType    string `json:"token_type"`
48
		Scope        string `json:"scope"`
49
		Expires      int    `json:"expires_in"`
50
		RefreshToken string `json:"refresh_token"`
51
	}
52
53
	// Convert stringified JSON to a struct object of type githubAccessTokenResponse
54
	var ghresp discordAccessTokenResponse
55
	err := config.JSONHelper.Unmarshal(respbody, &ghresp)
56
	if err != nil {
57
		return "", err
58
	}
59
60
	// Return the access token (as the rest of the
61
	// details are relatively unnecessary for us)
62
	return ghresp.AccessToken, nil
63
}
64
65
func GetDiscordData(accessToken string) (string, error) {
66
	req, reqerr := http.NewRequest(
67
		"GET",
68
		"https://discord.com/api/users/@me",
69
		nil,
70
	)
71
	if reqerr != nil {
72
		log.Info().Msg("Request failed")
73
	}
74
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
75
76
	// Get the response
77
	resp, resperr := http.DefaultClient.Do(req)
78
	if resperr != nil {
79
		log.Info().Msg("Response failed")
80
	}
81
82
	// Response body converted to stringified JSON
83
	respbody, _ := io.ReadAll(resp.Body)
84
85
	return string(respbody), nil
86
}
87