This commit is contained in:
Sakurasan
2023-04-09 21:35:20 +08:00
parent 4cca88d4e1
commit 31341cf5bf

View File

@@ -1,6 +1,7 @@
package main
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
@@ -15,30 +16,39 @@ import (
"github.com/google/go-github/v50/github"
"github.com/joho/godotenv"
"golang.org/x/oauth2"
ogithub "golang.org/x/oauth2/github"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var db *gorm.DB
var jwtSecret = []byte("JWT_SECRET")
var oauthConf *oauth2.Config
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
oauthConf = &oauth2.Config{
ClientID: os.Getenv("GITHUB_CLIENT_ID"),
ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
// Scopes: []string{"read:user", "user:email"},
Endpoint: oauth2.Endpoint{
AuthURL: "https://github.com/login/oauth/authorize",
TokenURL: "https://github.com/login/oauth/access_token",
}}
initDB()
router := gin.Default()
router.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:8000"},
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"},
AllowHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
AllowCredentials: true,
}))
router.GET("/", func(ctx *gin.Context) { ctx.Writer.WriteString("hello world") })
router.GET("/auth/github", githubLoginHandler)
router.GET("/auth/github/callback", githubCallbackHandler)
@@ -46,7 +56,6 @@ func main() {
}
func githubLoginHandler(c *gin.Context) {
state := "1234567890"
// state := generateState()
// code := generateCode()
@@ -57,15 +66,8 @@ func githubLoginHandler(c *gin.Context) {
// return
// }
oauthConfig := &oauth2.Config{
ClientID: os.Getenv("GITHUB_CLIENT_ID"),
ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
RedirectURL: "http://localhost:8000/auth/github/callback",
Scopes: []string{"user:email"},
Endpoint: ogithub.Endpoint,
}
url := oauthConfig.AuthCodeURL(state)
url := oauthConf.AuthCodeURL("state")
log.Println(url)
c.Redirect(http.StatusFound, url)
}
@@ -79,45 +81,51 @@ func githubCallbackHandler(c *gin.Context) {
// return
// }
oauthConfig := &oauth2.Config{
ClientID: os.Getenv("GITHUB_CLIENT_ID"),
ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
RedirectURL: "http://localhost:8000/auth/github/callback",
Scopes: []string{"user:email"},
Endpoint: ogithub.Endpoint,
}
token, err := oauthConfig.Exchange(c.Request.Context(), code)
// 使用 code 换取 token
token, err := oauthConf.Exchange(context.Background(), code)
if err != nil {
log.Println("Error exchanging token:", err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Internal server error"})
// c.String(http.StatusBadRequest, "授权失败: %s", err.Error())
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Errorf("授权失败: %s", err.Error())})
return
}
log.Println("token:", token)
client := github.NewClient(oauthConfig.Client(c.Request.Context(), token))
// 使用 token 获取 GitHub 用户信息
// client := github.NewClient(oauthConf.Client(context.Background(), token))
client := github.NewClient(oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(token)))
user, _, err := client.Users.Get(c.Request.Context(), "")
if err != nil {
log.Println("Error getting user:", err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Internal server error"})
// c.String(http.StatusInternalServerError, "获取用户信息失败: %s", err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Errorf("获取用户信息失败: %s", err.Error())})
return
}
err = storeUserToDB(user)
if err != nil {
log.Println("Error storing user to DB:", err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Internal server error"})
return
}
// err = storeUserToDB(user)
// if err != nil {
// log.Println("Error storing user to DB:", err)
// c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Internal server error"})
// return
// }
jwtToken, err := generateJWTToken(*user.ID)
if err != nil {
log.Println("Error generating JWT token:", err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Internal server error"})
return
}
log.Printf("%#v\n", user)
log.Println(user.GetEmail(), user.GetName(), user.GetID(), user.GetAvatarURL())
// 处理用户信息
c.JSON(http.StatusOK, gin.H{
"login": user.Login,
"name": user.Name,
"email": user.Email,
"location": user.Location,
"scopes": token.Extra("scope"),
})
// jwtToken, err := generateJWTToken(*user.ID)
// if err != nil {
// log.Println("Error generating JWT token:", err)
// c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Internal server error"})
// return
// }
c.SetCookie("token", jwtToken, 60*60*24, "/", "localhost", false, true)
c.Redirect(http.StatusFound, "http://localhost:8000/")
// c.SetCookie("token", jwtToken, 60*60*24, "/", "localhost", false, true)
// c.Redirect(http.StatusFound, "http://152.70.110.4:8000")
}
func initDB() {