Passed
Push — main ( aafc79...d8fe53 )
by Yume
01:26 queued 13s
created

oauth.GetGithubData   B

Complexity

Conditions 5

Size

Total Lines 36
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 21
nop 1
dl 0
loc 36
rs 8.9093
c 0
b 0
f 0
1
package oauth
2
3
import (
4
	"bytes"
5
	"context"
6
	"fmt"
7
	"io"
8
	"net/http"
9
10
	"github.com/memnix/memnix-rest/config"
11
	"github.com/memnix/memnix-rest/infrastructures"
12
	"github.com/rs/zerolog/log"
13
)
14
15
// GetGithubAccessToken gets the access token from Github using the code
16
func GetGithubAccessToken(code string) (string, error) {
17
	// Set us the request body as JSON
18
	requestBodyMap := map[string]string{
19
		"client_id":     infrastructures.GetAppConfig().GithubConfig.ClientID,
20
		"client_secret": infrastructures.GetAppConfig().GithubConfig.ClientSecret,
21
		"code":          code,
22
	}
23
	requestJSON, _ := config.JSONHelper.Marshal(requestBodyMap)
24
25
	// POST request to set URL
26
	req, reqerr := http.NewRequestWithContext(context.Background(),
27
		http.MethodPost,
28
		"https://github.com/login/oauth/access_token",
29
		bytes.NewBuffer(requestJSON),
30
	)
31
	if reqerr != nil {
32
		log.Info().Msg("Request failed")
33
	}
34
	req.Header.Set("Content-Type", "application/json")
35
	req.Header.Set("Accept", "application/json")
36
37
	// Get the response
38
	resp, resperr := http.DefaultClient.Do(req)
39
	if resperr != nil {
40
		log.Info().Msg("Response failed")
41
	}
42
43
	defer func(Body io.ReadCloser) {
44
		err := Body.Close()
45
		if err != nil {
46
			log.Info().Msg("Body close failed")
47
		}
48
	}(resp.Body)
49
50
	// Response body converted to stringified JSON
51
	respbody, _ := io.ReadAll(resp.Body)
52
53
	// Represents the response received from Github
54
	type githubAccessTokenResponse struct {
55
		AccessToken string `json:"access_token"`
56
		TokenType   string `json:"token_type"`
57
		Scope       string `json:"scope"`
58
	}
59
60
	// Convert stringified JSON to a struct object of type githubAccessTokenResponse
61
	var ghresp githubAccessTokenResponse
62
	err := config.JSONHelper.Unmarshal(respbody, &ghresp)
63
	if err != nil {
64
		return "", err
65
	}
66
67
	// Return the access token (as the rest of the
68
	// details are relatively unnecessary for us)
69
	return ghresp.AccessToken, nil
70
}
71
72
// GetGithubData gets the user data from Github using the access token
73
func GetGithubData(accessToken string) (string, error) {
74
	// Get request to a set URL
75
	req, err := http.NewRequestWithContext(context.Background(),
76
		http.MethodGet,
77
		"https://api.github.com/user",
78
		nil,
79
	)
80
	if err != nil {
81
		log.Info().Msg("Request failed")
82
		return "", err
83
	}
84
85
	defer func(Body io.ReadCloser) {
86
		err := Body.Close()
87
		if err != nil {
88
			log.Info().Msg("Body close failed")
89
		}
90
	}(req.Body)
91
92
	// Set the Authorization header before sending the request
93
	// Authorization: token XXXXXXXXXXXXXXXXXXXXXXXXXXX
94
	authorizationHeaderValue := fmt.Sprintf("token %s", accessToken)
95
	req.Header.Set("Authorization", authorizationHeaderValue)
96
97
	// Make the request
98
	resp, err := http.DefaultClient.Do(req)
99
	if err != nil {
100
		log.Info().Msg("Response failed")
101
		return "", err
102
	}
103
104
	// Read the response as a byte slice
105
	respbody, _ := io.ReadAll(resp.Body)
106
107
	// Convert byte slice to string and return
108
	return string(respbody), nil
109
}
110