This repository was archived by the owner on May 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwitch.go
More file actions
151 lines (127 loc) · 3.99 KB
/
twitch.go
File metadata and controls
151 lines (127 loc) · 3.99 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package main
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/dchest/uniuri"
"github.com/sirupsen/logrus"
"github.com/gin-gonic/gin"
"github.com/dgrijalva/jwt-go"
"github.com/nicklaw5/helix"
)
// TwitchUser ...
type TwitchUser struct {
ID string `json:"_id"`
Bio string `json:"bio"`
CreatedAt time.Time `json:"created_at"`
DisplayName string `json:"display_name"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Logo string `json:"logo"`
Name string `json:"name"`
Partnered bool `json:"partnered"`
Type string `json:"type"`
UpdatedAt time.Time `json:"updated_at"`
}
type oauthResponse struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
IDToken string `json:"id_token"`
RefreshToken string `json:"refresh_token"`
Scope []string `json:"scope"`
}
func (ur *UnRustleLogs) setupTwitchClient() (err error) {
ur.twitchAPIClient, err = helix.NewClient(&helix.Options{
ClientID: ur.config.Twitch.ClientID,
ClientSecret: ur.config.Twitch.ClientSecret,
RedirectURI: ur.config.Twitch.RedirectURL,
Scopes: ur.config.Twitch.Scopes,
})
return err
}
func (ur *UnRustleLogs) getUserByOAuthToken(accessToken string) (*TwitchUser, error) {
userAPI := "https://api.twitch.tv/kraken/user"
req, err := http.NewRequest("GET", userAPI, nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("OAuth %s", accessToken))
req.Header.Add("Client-ID", ur.config.Twitch.ClientID)
req.Header.Add("Accept", "application/vnd.twitchtv.v5+json")
response, err := ur.twitchHTTPClient.Do(req)
if err != nil {
return nil, err
}
defer response.Body.Close()
var user TwitchUser
err = json.NewDecoder(response.Body).Decode(&user)
return &user, err
}
// TwitchLoginHandle ...
func (ur *UnRustleLogs) TwitchLoginHandle(c *gin.Context) {
state := uniuri.New()
ur.addTwitchState(state)
url := ur.twitchAPIClient.GetAuthorizationURL(state, true)
c.Header("Location", url)
c.Redirect(http.StatusFound, url)
}
// TwitchLogoutHandle ...
func (ur *UnRustleLogs) TwitchLogoutHandle(c *gin.Context) {
ur.deleteCookie(c, ur.config.Twitch.Cookie)
c.Redirect(http.StatusFound, "/")
}
func (ur *UnRustleLogs) deleteCookie(c *gin.Context, cookie string) {
c.SetCookie(cookie, "", -1, "/", fmt.Sprintf("%s", c.Request.Host), c.Request.URL.Scheme == "https", false)
}
// TwitchCallbackHandle ...
func (ur *UnRustleLogs) TwitchCallbackHandle(c *gin.Context) {
state := c.Query("state")
if !ur.hasTwitchState(state) {
c.Redirect(http.StatusFound, "/")
return
}
go ur.deleteTwitchState(state)
code := c.Query("code")
errorMsg := c.Query("error")
if errorMsg != "" {
c.String(http.StatusBadRequest, errorMsg)
return
}
if code == "" {
c.String(http.StatusUnauthorized, "Authentication failed without error")
return
}
oauth, err := ur.twitchAPIClient.GetUserAccessToken(code)
if err != nil {
logrus.Error(err)
c.String(http.StatusUnauthorized, "Failed to get token from OAuth exchange code")
return
}
user, err := ur.getUserByOAuthToken(oauth.Data.AccessToken)
if err != nil {
logrus.Error(err)
c.String(http.StatusServiceUnavailable, "Twitch API failure while retrieving user")
return
}
id := ur.AddTwitchUser(user)
// Set custom claims
claims := &jwtClaims{
id,
jwt.StandardClaims{
// 1 month expire
ExpiresAt: time.Now().Add((time.Hour * 24) * 31).Unix(),
},
}
// Create token with claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Generate encoded token and send it as response.
t, err := token.SignedString([]byte(ur.config.Server.JWTSecret))
if err != nil {
logrus.Error(err)
c.JSON(http.StatusInternalServerError, gin.H{"message": "failed signing jwt"})
return
}
c.SetCookie(ur.config.Twitch.Cookie, t, 604800, "/", fmt.Sprintf("%s", c.Request.Host), c.Request.URL.Scheme == "https", false)
c.Redirect(http.StatusFound, "/twitch")
}