-
Notifications
You must be signed in to change notification settings - Fork 0
/
github_oauth.go
76 lines (62 loc) · 1.82 KB
/
github_oauth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package server
import (
"context"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/luqmansen/blogo/pkg/blogo"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"net/http"
)
type OAuth2ConfigInterface interface {
AuthCodeURL(state string, opts ...oauth2.AuthCodeOption) string
Exchange(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error)
Client(ctx context.Context, t *oauth2.Token) *http.Client
}
type OauthHandler struct {
oauth2Config OAuth2ConfigInterface
githubService blogo.GitHubInterface
}
func NewOauthHandler(
configInterface OAuth2ConfigInterface,
githubService blogo.GitHubInterface,
) OauthHandler {
return OauthHandler{
oauth2Config: configInterface,
githubService: githubService,
}
}
func (h OauthHandler) Authorize(ctx *gin.Context) {
sess := sessions.Default(ctx)
state := uuid.New().String()
sess.Set("state", state)
if err := sess.Save(); err != nil {
log.Error(err)
ctx.AbortWithStatusJSON(http.StatusInternalServerError, err)
return
}
ctx.Redirect(http.StatusTemporaryRedirect, h.oauth2Config.AuthCodeURL(state))
}
func (h OauthHandler) GithubCallbackHandler(ctx *gin.Context) {
sess := sessions.Default(ctx)
storedState := sess.Get("state")
returnedState := ctx.Query("state")
if returnedState != storedState.(string) {
ctx.AbortWithStatusJSON(http.StatusUnprocessableEntity, "Invalid state parameter")
return
}
code := ctx.Query("code")
if code == "" {
ctx.String(http.StatusBadRequest, "no code in query param")
return
}
token, err := h.oauth2Config.Exchange(ctx, code)
if err != nil {
log.Error(err)
}
client := h.oauth2Config.Client(ctx, token)
githubClient := h.githubService.NewClient(client)
repo, _, _ := githubClient.Repositories.Get(ctx, "1", "")
ctx.JSON(200, repo)
}