Passed
Push — main ( d8fe53...15d6f0 )
by Yume
01:34 queued 25s
created

oauth.GetGithubData   A

Complexity

Conditions 3

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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