-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
286 lines (258 loc) · 9.72 KB
/
main.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
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package main
import (
"encoding/base64"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/KNN3-Network/oauth-server/module"
"github.com/KNN3-Network/oauth-server/utils"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
var logger = utils.Logger
var stackoverflow = new(module.Stackoverflow)
func main() {
r := gin.Default()
r.Use(cors.Default())
r.POST("/oauth/bind", func(c *gin.Context) {
var requestBody utils.RequestBody
// 将请求体中的 JSON 数据绑定到结构体
if err := c.ShouldBindJSON(&requestBody); err != nil {
// 处理绑定错误
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
jwt := requestBody.JWT
code := requestBody.Code
platformType := requestBody.PlatformType
if jwt == "" || code == "" || platformType == "" {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("参数错误"))
return
}
db := utils.GetDB()
address, err := utils.JwtDecode(jwt)
logger.Info("JwtDecode address", zap.Any("address", address))
if err != nil {
logger.Error("failed to decode jwt:", zap.Error(err))
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("解析jwt错误"))
return
}
if platformType == "github" {
userInfo, err := module.RequestGithubUserInfo(c, code)
if err != nil {
logger.Error("failed to get user info:", zap.Error(err))
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("获取github用户信息错误"))
return
}
github := userInfo["login"].(string)
bind := utils.OauthBind{}
result := db.Model(&utils.OauthBind{}).Where("github = ?", github).First(&bind)
// 判断返回结果里面github是不是空
if bind != (utils.OauthBind{}) {
logger.Error("github has bound:", zap.Error(result.Error))
c.JSON(http.StatusOK, gin.H{"data": "false"})
return
}
logger.Info("userInfo", zap.Any("user", userInfo))
bind = utils.OauthBind{}
result = db.Model(&utils.OauthBind{}).Where("addr = ?", address).First(&bind)
// 判断返回结果里面address是不是空
if bind != (utils.OauthBind{}) {
result = db.Model(&bind).Where("addr = ?", address).Updates(map[string]interface{}{"github": github})
if result.Error != nil {
logger.Error("failed to update address:", zap.Error(result.Error))
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("Update Error"))
return
}
} else {
// insert into oauth_binds (addr, github) values (address, github)
result = db.Model(&utils.OauthBind{}).Create(&utils.OauthBind{Addr: address, Github: github})
if result.Error != nil {
logger.Error("failed to insert oauth_bind:", zap.Error(result.Error))
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("Insert Error"))
return
}
}
c.JSON(http.StatusOK, gin.H{"data": "success"})
} else if platformType == "discord" {
token, err := module.ExchangeCodeForToken(code)
if err != nil {
logger.Error("failed to exchange discord token:", zap.Error(err))
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("获取token错误"))
return
}
user, err := module.FetchUser(token)
if err != nil {
logger.Error("failed to get discord user info:", zap.Error(err))
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("获取discord用户信息错误"))
return
}
addr := utils.OauthBind{}
result := db.Model(&utils.OauthBind{}).Where("discord = ?", user.ID).First(&addr)
if addr != (utils.OauthBind{}) {
logger.Error("discord has bound:", zap.Error(result.Error))
c.JSON(http.StatusOK, gin.H{"data": "false"})
return
}
logger.Info("userInfo", zap.Any("user", user.ID))
logger.Info("discord username", zap.Any("username", user.Username))
logger.Info("discord avatar", zap.Any("user", user.Avatar))
bind := utils.OauthBind{}
result = db.Model(&utils.OauthBind{}).Where("addr = ?", address).First(&bind)
// 判断返回结果里面address是不是空
if bind != (utils.OauthBind{}) {
result = db.Model(&bind).Where("addr = ?", address).Updates(map[string]interface{}{"discord": user.ID, "discord_name": user.Username})
if result.Error != nil {
logger.Error("failed to update address:", zap.Error(result.Error))
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("Update Error"))
return
}
} else {
result = db.Model(&utils.OauthBind{}).Create(&utils.OauthBind{Addr: address, Discord: user.ID, DiscordName: user.Username})
if result.Error != nil {
logger.Error("failed to insert oauth_bind:", zap.Error(result.Error))
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("Insert Error"))
return
}
}
c.JSON(http.StatusOK, gin.H{"data": "success"})
} else if platformType == "stackexchange" {
stackoverflow.Bind(c, code, address)
} else if platformType == "gmail" {
profile, err := module.GetGmailProfile(code)
if err != nil {
logger.Error("failed to exchange gmail token:", zap.Error(err))
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("获取token错误"))
return
}
addr := utils.OauthBind{}
result := db.Model(&utils.OauthBind{}).Where("gmail = ?", profile.EmailAddress).First(&addr)
if addr != (utils.OauthBind{}) {
logger.Error("gmail has bound:", zap.Error(result.Error))
c.JSON(http.StatusOK, gin.H{"data": "false"})
return
}
bind := utils.OauthBind{}
result = db.Model(&utils.OauthBind{}).Where("addr = ?", address).First(&bind)
// 判断返回结果里面address是不是空
if bind != (utils.OauthBind{}) {
result = db.Model(&bind).Where("addr = ?", address).Updates(map[string]interface{}{"gmail": profile.EmailAddress})
if result.Error != nil {
logger.Error("failed to update address:", zap.Error(result.Error))
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("Update Error"))
return
}
} else {
result = db.Model(&utils.OauthBind{}).Create(&utils.OauthBind{Addr: address, Gmail: profile.EmailAddress})
if result.Error != nil {
logger.Error("failed to insert oauth_bind:", zap.Error(result.Error))
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("Insert Error"))
return
}
}
c.JSON(http.StatusOK, gin.H{"data": "success"})
}
})
r.POST("/oauth/login", func(c *gin.Context) {
var requestBody utils.RequestLoginBody
// 将请求体中的 JSON 数据绑定到结构体
if err := c.ShouldBindJSON(&requestBody); err != nil {
// 处理绑定错误
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
code := requestBody.Code
platformType := requestBody.PlatformType
if code == "" || platformType == "" {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("参数错误"))
return
}
if platformType == "github" {
module.GithubLogin(c, code)
} else {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("平台不支持"))
return
}
})
// github oauth
r.GET("/oauth/github", func(c *gin.Context) {
code := c.Query("code")
source := c.Query("source")
if code == "" {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("No authorization code provided."))
return
}
logger.Info("github oauth认证", zap.String("code", code))
logger.Info("github oauth source", zap.String("source", source))
if source != "" { // 使用OAuth配置对象中定义的Exchange方法,通过code获取access token
// 拼接https://transformer.knn3.xyz/ + source + /type=github&code= + code
url := fmt.Sprintf("https://transformer.knn3.xyz/%s?type=github&code=%s", source, code)
c.Redirect(http.StatusTemporaryRedirect, url)
} else {
c.Redirect(http.StatusTemporaryRedirect, "https://topscore.social/pass?type=github&code="+code)
}
})
// github oauth
r.GET("/oauth/discord", func(c *gin.Context) {
code := c.Query("code")
if code == "" {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("No authorization code provided."))
return
}
logger.Info("discord oauth认证", zap.String("code", code))
c.Redirect(http.StatusTemporaryRedirect, "https://topscore.social/pass?type=discord&code="+code)
})
r.GET("/oauth/gmail", func(c *gin.Context) {
code := c.Query("code")
state := c.Query("state")
// logger.Info("gmail state", zap.String("state", "state"))
// logger.Info("gmail url", zap.String("state", Request.URL.String()))
if code == "" || state == "" {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("No authorization code provided."))
return
}
logger.Info("gmail oauth认证", zap.String("code", code))
// knexus gmail login
decodedURL, err := url.QueryUnescape(state)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("authorization error state"))
return
}
stateArr := strings.Split(decodedURL, "$")
logger.Info("gmail state arr", zap.Any("stateArr", stateArr))
if stateArr[0] == "knexus" || stateArr[0] == "knexus_early" {
success := stateArr[1]
fail := stateArr[2]
profile, err := module.GetGmailProfileByKnexus(code)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("authorization error code"))
return
}
source := ""
if stateArr[0] == "knexus" {
source = "normal"
}
if stateArr[0] == "knexus_early" {
source = "early"
}
accessToken, err := module.GetAccessToken(profile.EmailAddress, source)
if err != nil {
c.Redirect(http.StatusMovedPermanently, strings.Replace(fail, "fail=", "", 1))
return
}
c.Redirect(http.StatusMovedPermanently, strings.Replace(success, "success=", "", 1)+"?j="+base64.StdEncoding.EncodeToString([]byte(accessToken)))
return
}
c.Redirect(http.StatusTemporaryRedirect, "https://topscore.social/pass?type=gmail&code="+code)
})
// stackoverflow
v1 := r.Group("/oauth/stackoverflow")
{
// stackoverflow := new(module.Stackoverflow)
v1.GET("/authcodeurl", stackoverflow.AuthCodeURL)
v1.GET("/", stackoverflow.CallBack)
}
r.Run(":8001")
}