-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.go
More file actions
91 lines (77 loc) · 2.12 KB
/
github.go
File metadata and controls
91 lines (77 loc) · 2.12 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package auth
import (
"net/http"
"trakrlog/internal/service"
"github.com/gin-gonic/gin"
"github.com/markbates/goth/gothic"
)
type GitHubHandler struct {
sessionSecret string
userService *service.UserService
}
func NewGitHubHandler(sessionSecret string, userService *service.UserService) *GitHubHandler {
return &GitHubHandler{
sessionSecret: sessionSecret,
userService: userService,
}
}
func (h *GitHubHandler) Signup(ctx *gin.Context) {
query := ctx.Request.URL.Query()
query.Add("provider", "github")
ctx.Request.URL.RawQuery = query.Encode()
gothic.BeginAuthHandler(ctx.Writer, ctx.Request)
}
func (h *GitHubHandler) HandleCallback(ctx *gin.Context) {
query := ctx.Request.URL.Query()
query.Add("provider", "github")
ctx.Request.URL.RawQuery = query.Encode()
gothUser, err := gothic.CompleteUserAuth(ctx.Writer, ctx.Request)
if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"success": false,
"message": "Error authenticating user",
"error": err.Error(),
})
return
}
// Use AuthenticateWithProvider method
dbUser, err := h.userService.AuthenticateWithProvider(
ctx.Request.Context(),
"github",
gothUser.UserID,
gothUser.Email,
gothUser.Name,
gothUser.AvatarURL,
gothUser.AccessToken,
gothUser.RefreshToken,
)
if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"success": false,
"message": "Error authenticating with GitHub",
"error": err.Error(),
})
return
}
// Store user session
session, err := gothic.Store.New(ctx.Request, "trakrlog-session")
if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"success": false,
"message": "Error creating session",
"error": err.Error(),
})
return
}
session.Values["user_id"] = dbUser.ID.Hex()
session.Values["user_email"] = dbUser.Email
if err = session.Save(ctx.Request, ctx.Writer); err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"success": false,
"message": "Error saving session",
"error": err.Error(),
})
return
}
ctx.Redirect(http.StatusTemporaryRedirect, "/dashboard")
}