Skip to content

Commit

Permalink
feat: Add github oauth2 login
Browse files Browse the repository at this point in the history
  • Loading branch information
Xunop committed Jul 25, 2024
1 parent 9bf2097 commit ac76a2c
Show file tree
Hide file tree
Showing 9 changed files with 227 additions and 96 deletions.
63 changes: 52 additions & 11 deletions src/api/v1/oauth_client_github.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@ import (
"fmt"
"io"
"net/http"
"time"

"github.com/NJUPT-SAST/sast-link-backend/config"
"github.com/NJUPT-SAST/sast-link-backend/endpoints"
"github.com/NJUPT-SAST/sast-link-backend/log"
"github.com/NJUPT-SAST/sast-link-backend/model"
"github.com/NJUPT-SAST/sast-link-backend/model/result"
"github.com/NJUPT-SAST/sast-link-backend/service"
"github.com/NJUPT-SAST/sast-link-backend/util"
"github.com/gin-gonic/gin"
"github.com/tidwall/gjson"
"golang.org/x/oauth2"
Expand All @@ -25,14 +28,16 @@ var (
githubConf = oauth2.Config{
ClientID: config.Config.GetString("oauth.client.github.id"),
ClientSecret: config.Config.GetString("oauth.client.github.secret"),
RedirectURL: config.Config.GetString("oauth.client.github.redirect_url"),
RedirectURL: "http://localhost:3000/callback/github",
Scopes: []string{},
Endpoint: endpoints.GitHub,
}
)

func OauthGithubLogin(c *gin.Context) {

redirectURL := c.Query("redirect_url")
githubConf.RedirectURL = redirectURL
// Create oauthState cookie
oauthState := GenerateStateOauthCookie(c.Writer)
url := githubConf.AuthCodeURL(oauthState)
Expand All @@ -58,29 +63,65 @@ func OauthGithubCallback(c *gin.Context) {

code := c.Query("code")

githubId, err := getUserInfoFromGithub(c.Request.Context(), code)
// githubinfo is the user info from github
githubInfo, err := getUserInfoFromGithub(c.Request.Context(), code)
if err != nil {
c.JSON(http.StatusOK, result.Failed(result.HandleError(err)))
return
}
if githubId == "" {
if githubInfo == "" {
c.JSON(http.StatusOK, result.Failed(result.HandleError(result.RequestParamError)))
return
}
log.Debug("GithubId: ", githubId)

user, err := service.GetUserByGithubId(githubId)
githubID := gjson.Get(githubInfo, "id").String()
// userInfo is the github user info in the database
userInfo, err := service.GetUserByGithubId(githubID)
if err != nil {
log.Errorf("service.GetUserByGithubId ::: %s", err.Error())
c.JSON(http.StatusOK, result.Failed(result.HandleError(err)))
return
}

// Store to redis
model.Rdb.Set(model.RedisCtx, githubID,
githubInfo, time.Duration(model.OAUTH_USER_INFO_EXP))

// User not found, Need to register to bind the github id
if user == nil {
if userInfo == nil {
log.Debugf("User not found, Need to register to bind the github id: %s", githubID)
oauthToken, err := util.GenerateTokenWithExp(c, model.OauthSubKey(githubID, model.OAUTH_GITHUB_SUB), model.OAUTH_TICKET_EXP)

if err != nil {
c.JSON(http.StatusOK, result.Failed(result.GenerateToken))
log.Log.Errorln("util.GenerateTokenWithExp ::: ", err)
return
}
c.JSON(http.StatusOK, result.Response{
Success: false,
ErrCode: result.OauthUserUnbounded.ErrCode,
ErrMsg: result.OauthUserUnbounded.ErrMsg,
Data: gin.H{
"oauthTicket": oauthToken,
},
})
return
} else {
// User already registered and bounded github,
// directly return token
uid := userInfo.UserID
log.Debugf("User already registered and bounded github: %s", uid)
token, err := util.GenerateTokenWithExp(c, model.LoginJWTSubKey(uid), model.LOGIN_TOKEN_EXP)
if err != nil {
c.JSON(http.StatusOK, result.Failed(result.GenerateToken))
return
}
model.Rdb.Set(c, model.LoginTokenKey(uid), token, model.LOGIN_TOKEN_EXP)
c.JSON(http.StatusOK, result.Success(gin.H{
model.LOGIN_TOKEN_SUB: token,
}))
return
}

c.JSON(http.StatusOK, result.Success(githubId))
}

func getUserInfoFromGithub(ctx context.Context, code string) (string, error) {
Expand Down Expand Up @@ -109,7 +150,7 @@ func getUserInfoFromGithub(ctx context.Context, code string) (string, error) {
return "", result.InternalErr
}

// TODO:Now just get the github id
githubId := gjson.Get(string(body), "id").String()
return githubId, nil
log.Debugf("Github user info: %s", gjson.ParseBytes(body).String())

return gjson.ParseBytes(body).String(), nil
}
6 changes: 3 additions & 3 deletions src/api/v1/oauth_client_lark.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,17 +96,17 @@ func OauthLarkCallback(c *gin.Context) {
// save user info in redis (then retrive in login)
userInfo := gjson.Get(userInfoBody, "data")
model.Rdb.Set(model.RedisCtx, unionId,
userInfo, time.Duration(model.LARK_USER_INFO_EXP))

userInfo, time.Duration(model.OAUTH_USER_INFO_EXP))

// FIXME: Use OauthInfoByUID to get user
user, err := service.UserByLarkUnionID(unionId)
if err != nil {
c.JSON(http.StatusOK, result.Failed(result.InternalErr))
log.Log.Errorln("service.UserByLarkUnionID ::: ", err)
return
} else if user == nil {
// return with oauth lark ticket, which contains "union_id"
oauthToken, err := util.GenerateTokenWithExp(c, model.OauthSubKey(unionId), model.OAUTH_TICKET_EXP)
oauthToken, err := util.GenerateTokenWithExp(c, model.OauthSubKey(unionId, model.OAUTH_LARK_SUB), model.OAUTH_TICKET_EXP)

if err != nil {
c.JSON(http.StatusOK, result.Failed(result.GenerateToken))
Expand Down
42 changes: 28 additions & 14 deletions src/api/v1/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
"github.com/NJUPT-SAST/sast-link-backend/service"
"github.com/NJUPT-SAST/sast-link-backend/util"
"github.com/gin-gonic/gin"

"gorm.io/datatypes"
)

var controllerLogger = log.Log
Expand Down Expand Up @@ -208,16 +210,6 @@ func Login(ctx *gin.Context) {
return
}

// Set Token with expire time and return
token, err := util.GenerateTokenWithExp(ctx, model.LoginJWTSubKey(uid), model.LOGIN_TOKEN_EXP)
if err != nil {
ctx.JSON(http.StatusOK, result.Failed(result.GenerateToken))
}
model.Rdb.Set(ctx, model.LoginTokenKey(uid), token, model.LOGIN_TOKEN_EXP)
ctx.JSON(http.StatusOK, result.Success(gin.H{
model.LOGIN_TOKEN_SUB: token,
}))

// Oauth: check if need to bound oauth servers like lark, github...
// TODO: use cookie to manage ticket etc...
oauthTicket := ctx.Request.Header.Get("OAUTH-TICKET")
Expand All @@ -232,8 +224,10 @@ func Login(ctx *gin.Context) {
}
flagIn := strings.Split(audience[0], "-")[1]

log.Debugf("Login ::: Oauth ::: flagIn ::: %v", flagIn)

switch flagIn {
case "oauthLarkToken":
case model.OAUTH_LARK_SUB:
unionID, err := util.IdentityFromToken(oauthTicket, model.OAUTH_LARK_SUB)
if err != nil {
ctx.JSON(http.StatusOK, result.Failed(result.OauthTokenError))
Expand All @@ -243,16 +237,36 @@ func Login(ctx *gin.Context) {

// TODO: save oauth user info
oauthLarkUserInfo, _ := model.Rdb.Get(ctx, unionID).Result()
if err := service.UpdateLarkUserInfo(username, model.LARK_CLIENT_TYPE, unionID, oauthLarkUserInfo); err != nil {
ctx.JSON(http.StatusOK, result.Failed(result.InternalErr))
log.Log.Errorln("service.UpdateLarkUserInfo ::: ", err)
service.UpsetOauthInfo(username, model.LARK_CLIENT_TYPE, unionID, datatypes.JSON(oauthLarkUserInfo))
case model.OAUTH_GITHUB_SUB:
unionID, err := util.IdentityFromToken(oauthTicket, model.OAUTH_GITHUB_SUB)
if err != nil {
ctx.JSON(http.StatusOK, result.Failed(result.OauthTokenError))
log.Log.Errorln("util.IdentityFromToken ::: ", err)
return
}

oauthGithubUserInfo, _ := model.Rdb.Get(ctx, unionID).Result()

log.Debugf("Login ::: Oauth ::: github info ::: %v", oauthGithubUserInfo)

service.UpsetOauthInfo(username, model.GITHUB_CLIENT_TYPE, unionID, datatypes.JSON(oauthGithubUserInfo))
default:
log.Errorf("Login ::: Oauth ::: flagIn ::: %v", flagIn)
ctx.JSON(http.StatusOK, result.Failed(result.OauthTokenError))
return
}
}

// Set Token with expire time and return
token, err := util.GenerateTokenWithExp(ctx, model.LoginJWTSubKey(uid), model.LOGIN_TOKEN_EXP)
if err != nil {
ctx.JSON(http.StatusOK, result.Failed(result.GenerateToken))
}
model.Rdb.Set(ctx, model.LoginTokenKey(uid), token, model.LOGIN_TOKEN_EXP)
ctx.JSON(http.StatusOK, result.Success(gin.H{
model.LOGIN_TOKEN_SUB: token,
}))
}

// Modify paassword
Expand Down
23 changes: 13 additions & 10 deletions src/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ require (
github.com/spf13/viper v1.15.0
github.com/stretchr/testify v1.8.3
gorm.io/driver/postgres v1.5.0
gorm.io/gorm v1.25.0
gorm.io/gorm v1.25.9
)

require (
Expand All @@ -28,6 +28,7 @@ require (
github.com/vgarvardt/go-oauth2-pg/v4 v4.4.3
github.com/vgarvardt/go-pg-adapter v1.0.0
golang.org/x/oauth2 v0.12.0
gorm.io/datatypes v1.2.1
)

require (
Expand All @@ -40,6 +41,7 @@ require (
)

require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/bytedance/sonic v1.9.2 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
Expand All @@ -48,13 +50,13 @@ require (
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/frankban/quicktest v1.14.4 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/logger v0.2.6 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-pkgz/expirable-cache v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.1 // indirect
github.com/go-redis/redis/v8 v8.11.4 // indirect
github.com/go-sql-driver/mysql v1.8.1 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang-jwt/jwt v3.2.1+incompatible // indirect
github.com/golang/protobuf v1.5.3 // indirect
Expand All @@ -66,10 +68,11 @@ require (
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.2.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect
github.com/jackc/pgtype v1.10.0 // indirect
github.com/jackc/pgx/v5 v5.3.1 // indirect
github.com/jackc/pgx/v5 v5.5.5 // indirect
github.com/jackc/puddle v1.2.1 // indirect
github.com/jackc/puddle/v2 v2.2.1 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/jmoiron/sqlx v1.3.4 // indirect
Expand All @@ -78,28 +81,28 @@ require (
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mozillazg/go-httpheader v0.4.0 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rs/zerolog v1.29.1 // indirect
github.com/smarty/assertions v1.15.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
github.com/vgarvardt/pgx-helpers/v4 v4.0.0-20200225100150-876aee3d1a22 // indirect
golang.org/x/arch v0.4.0 // indirect
golang.org/x/crypto v0.13.0 // indirect
golang.org/x/net v0.15.0 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/text v0.13.0 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/mysql v1.5.6 // indirect
)
Loading

0 comments on commit ac76a2c

Please sign in to comment.