-
Notifications
You must be signed in to change notification settings - Fork 18
/
oauth.go
79 lines (67 loc) · 2.08 KB
/
oauth.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
package api
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/google/go-github/github"
"github.com/mecm/gin-auth/pkg/app"
"github.com/mecm/gin-auth/pkg/oauth"
"github.com/mecm/gin-auth/pkg/util"
"github.com/mecm/gin-auth/service/user_service"
"golang.org/x/oauth2"
"net/http"
"strconv"
)
var oauthStateString = "random-user"
// LoginGithub github登录/注册
func LoginGithub(c *gin.Context) {
oauthStateString = util.GetRandomSalt()
url := oauth.GithubOauthConfig.AuthCodeURL(oauthStateString, oauth2.AccessTypeOnline)
c.Redirect(http.StatusMovedPermanently, url)
}
// CallBackGithub 登录成功
func CallBackGithub(c *gin.Context) {
state, _ := c.GetQuery("state")
code, _ := c.GetQuery("code")
appG := app.GetGin(c)
// TODO 如果服务器重启了, oauthStateString就失效了
if state != oauthStateString {
err := fmt.Sprintf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
appG.ResponseFailMsg(err)
// c.Redirect(http.StatusTemporaryRedirect, "/")
return
}
token, err := oauth.GithubOauthConfig.Exchange(oauth2.NoContext, code)
if err != nil {
fmt.Printf("oauthConf.Exchange() failed with '%s'\n", err)
appG.ResponseFailMsg(err.Error())
// c.Redirect(http.StatusTemporaryRedirect, "/")
return
}
oauthClient := oauth.GithubOauthConfig.Client(oauth2.NoContext, token)
client := github.NewClient(oauthClient)
user, _, err := client.Users.Get(oauth2.NoContext, "")
if err != nil {
fmt.Printf("client.Users.Get() faled with '%s'\n", err)
appG.ResponseFailMsg(err.Error())
// c.Redirect(http.StatusTemporaryRedirect, "/")
return
}
// 3: Github
userID := strconv.FormatInt(*(user.ID), 10)
userService := user_service.UserOauth{OauthID: userID, OauthType: 3, OauthAccessToken: token.AccessToken, OauthExpires: "3600"}
exist, err := userService.ExistUserOauth()
if err != nil {
appG.ResponseFailMsg(err.Error())
return
}
if exist {
goto Success
}
// 不存在创建一个
if err := userService.LoginGithub(); err != nil {
appG.ResponseFailMsg(err.Error())
return
}
Success:
appG.ResponseSuc(token.AccessToken)
}