-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwxoauth.go
74 lines (61 loc) · 1.38 KB
/
wxoauth.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
package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
"time"
"github.com/chanxuehong/wechat/mp/user/oauth2"
"github.com/chanxuehong/sid"
"github.com/chanxuehong/session"
"github.com/chanxuehong/rand"
)
const (
oriid = ""
appid = ""
appsecret = ""
token = ""
enaeskey = ""
)
var (
sessionStorage = session.New(20*60, 60*60)
backcallurl = ""
oauth2Config = oauth2.NewOAuth2Config(
appid,
appsecret,
backcallurl,
//"snsapi_userinfo",
"snsapi_base",
)
oauth2Client = oauth2.Client{Config: oauth2Config,}
state string
)
func WxOauth(c *gin.Context) {
path := c.Request.URL.Path
if path != "/logout" {
if code := c.Query("code"); code == "" {
islogin := 1
if cookie, err := c.Request.Cookie("sid");err == nil {
if _, err := sessionStorage.Get(cookie.Value); err == nil {
islogin = 0
}
}
if islogin == 1 {
state = string(rand.NewHex())
oauth2Config.RedirectURI = backcallurl + path
AuthCodeURL := oauth2Config.AuthCodeURL(state, nil)
c.Redirect(302, AuthCodeURL)
}
}else {
sid := sid.New()
if err := sessionStorage.Add(sid, state); err != nil {
c.String(401, "error")
}
cookie := http.Cookie{
Name: "sid",
Value: sid,
HttpOnly: true,
}
http.SetCookie(c.Writer, &cookie)
oauth2Client.Exchange(code)
}
}
}