-
Notifications
You must be signed in to change notification settings - Fork 37
/
social.go
342 lines (277 loc) · 8.09 KB
/
social.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// Copyright 2014 beego authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
// Maintain by https://github.com/slene
package social
import (
"encoding/base64"
"fmt"
"net/url"
"strconv"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/utils"
)
const (
defaultURLPrefix = "/login/"
defaultConnectSuccessURL = "/login?flag=connect_success"
defaultConnectFailedURL = "/login?flag=connect_failed"
defaultLoginURL = "/login"
defaultConnectRegisterURL = "/register/connect"
)
type SocialAuth struct {
app SocialAuther
URLPrefix string
ConnectSuccessURL string
ConnectFailedURL string
LoginURL string
ConnectRegisterURL string
}
// generate session key for social-auth
func (this *SocialAuth) getSessKey(social SocialType, key string) string {
return "social_" + fmt.Sprintf("%v", social) + "_" + key
}
// create oauth2 state string
func (this *SocialAuth) createState(ctx *context.Context, social SocialType) string {
values := make(url.Values, 2)
if uid, ok := this.app.IsUserLogin(ctx); ok {
// add uid if user current is login
values.Add("uid", strconv.FormatInt(int64(uid), 10))
}
// our secret string
values.Add("secret", string(utils.RandomCreateBytes(20)))
// create state string
state := base64.URLEncoding.EncodeToString([]byte(values.Encode()))
// save to session
name := this.getSessKey(social, "state")
ctx.Input.CruSession.Set(name, state)
return state
}
// verify oauth2 state string
func (this *SocialAuth) verifyState(ctx *context.Context, social SocialType) (string, bool) {
code := ctx.Input.Query("code")
state := ctx.Input.Query("state")
if len(code) == 0 || len(state) == 0 {
return "", false
}
name := this.getSessKey(social, "state")
vu, ok := ctx.Input.CruSession.Get(name).(string)
if !ok || ok && state != vu {
return "", false
}
return code, true
}
// Get provider according request path. ex: /login/: match /login/github
func (this *SocialAuth) getProvider(ctx *context.Context) Provider {
path := ctx.Input.Param(":splat")
p, ok := GetProviderByPath(path)
if ok {
return p
}
return nil
}
// After OAuthAccess check saved token for ready connect
func (this *SocialAuth) ReadyConnect(ctx *context.Context) (SocialType, bool) {
var social SocialType
if s, _ := ctx.Input.CruSession.Get("social_connect").(int); s == 0 {
return 0, false
} else {
social = SocialType(s)
}
if !social.Available() {
return 0, false
}
return social, true
}
// Redirect to other social platform
func (this *SocialAuth) OAuthRedirect(ctx *context.Context) (redirect string, failedErr error) {
_, isLogin := this.app.IsUserLogin(ctx)
defer func() {
if len(redirect) == 0 && failedErr != nil {
if isLogin {
redirect = this.ConnectFailedURL
} else {
redirect = this.LoginURL
}
}
}()
var p Provider
if p = this.getProvider(ctx); p == nil {
failedErr = fmt.Errorf("unknown provider")
return
}
social := p.GetType()
config := p.GetConfig()
// create redirect url
redirect = config.AuthCodeURL(this.createState(ctx, social))
return
}
// Callback from social platform
func (this *SocialAuth) OAuthAccess(ctx *context.Context) (redirect string, userSocial *UserSocial, failedErr error) {
_, isLogin := this.app.IsUserLogin(ctx)
defer func() {
if len(redirect) == 0 {
if failedErr != nil {
if isLogin {
redirect = this.ConnectFailedURL
} else {
redirect = this.LoginURL
}
}
}
}()
// check if param has a error key
if err := ctx.Input.Query("error"); len(err) > 0 {
failedErr = fmt.Errorf(err)
return
}
// get provider from matched url path
var p Provider
if p = this.getProvider(ctx); p == nil {
failedErr = fmt.Errorf("unknown provider")
return
}
social := p.GetType()
var code string
// verify state string
if c, ok := this.verifyState(ctx, social); !ok {
failedErr = fmt.Errorf("state not verified")
return
} else {
code = c
}
config := p.GetConfig()
trans := &Transport{config, nil, DefaultTransport}
// Send code to platform then get token
if tok, err := trans.Exchange(code); err != nil {
// get access token
failedErr = err
} else if err := tok.GetExtra("error"); err != "" {
// token has error
failedErr = fmt.Errorf(err)
} else if tok.IsEmpty() {
failedErr = fmt.Errorf("empty access token")
} else {
// check
var uSocial = UserSocial{}
if ok, err := p.CanConnect(tok, &uSocial); ok {
// save token to session, for connect
tk := SocialTokenField{tok}
ctx.Input.CruSession.Set(this.getSessKey(social, "token"), tk.RawValue())
ctx.Input.CruSession.Set("social_connect", int(social))
redirect = this.ConnectRegisterURL
} else if err == nil {
if !isLogin {
// login user
redirect, failedErr = this.app.LoginUser(ctx, uSocial.Uid)
if len(redirect) == 0 && failedErr == nil {
redirect = this.ConnectSuccessURL
}
} else {
redirect = this.ConnectSuccessURL
}
// save new access token if it changed
uSocial.PutToken(tok)
userSocial = &uSocial
} else {
failedErr = err
}
}
return
}
// general use of redirect
func (this *SocialAuth) handleRedirect(ctx *context.Context) {
redirect, err := this.OAuthRedirect(ctx)
if err != nil {
beego.Error("SocialAuth.handleRedirect", err)
}
if len(redirect) > 0 {
ctx.Redirect(302, redirect)
}
}
// general use of redirect callback
func (this *SocialAuth) handleAccess(ctx *context.Context) {
redirect, _, err := this.OAuthAccess(ctx)
if err != nil {
beego.Error("SocialAuth.handleAccess", err)
}
if len(redirect) > 0 {
ctx.Redirect(302, redirect)
}
}
// save user social info and login the user
func (this *SocialAuth) ConnectAndLogin(ctx *context.Context, socialType SocialType, uid int) (string, *UserSocial, error) {
tokKey := this.getSessKey(socialType, "token")
defer func() {
// delete connect tok in session
if ctx.Input.CruSession.Get("social_connect") != nil {
ctx.Input.CruSession.Delete("social_connect")
}
if ctx.Input.CruSession.Get(tokKey) != nil {
ctx.Input.CruSession.Delete(tokKey)
}
}()
tk := SocialTokenField{}
value := ctx.Input.CruSession.Get(tokKey)
if err := tk.SetRaw(value); err != nil {
return "", nil, err
}
var p Provider
if p, _ = GetProviderByType(socialType); p == nil {
return "", nil, fmt.Errorf("unknown provider")
}
identify, err := p.GetIndentify(tk.Token)
if err != nil {
return "", nil, err
}
if len(identify) == 0 {
return "", nil, fmt.Errorf("empty identify")
}
userSocial := UserSocial{
Uid: uid,
Type: socialType,
Data: tk,
Identify: identify,
}
if err := userSocial.Save(); err != nil {
return "", nil, err
}
// login user
loginRedirect, err := this.app.LoginUser(ctx, uid)
return loginRedirect, &userSocial, nil
}
// create a global SocialAuth instance
func NewSocial(urlPrefix string, socialAuther SocialAuther) *SocialAuth {
social := new(SocialAuth)
social.app = socialAuther
if len(urlPrefix) == 0 {
urlPrefix = defaultURLPrefix
}
if urlPrefix[len(urlPrefix)-1] != '/' {
urlPrefix += "/"
}
social.URLPrefix = urlPrefix
social.ConnectSuccessURL = defaultConnectSuccessURL
social.ConnectFailedURL = defaultConnectFailedURL
social.LoginURL = defaultLoginURL
social.ConnectRegisterURL = defaultConnectRegisterURL
return social
}
// create a instance and create filter
func NewWithFilter(urlPrefix string, socialAuther SocialAuther) *SocialAuth {
social := NewSocial(urlPrefix, socialAuther)
beego.InsertFilter(social.URLPrefix+"*/access", beego.BeforeRouter, social.handleAccess)
beego.InsertFilter(social.URLPrefix+"*", beego.BeforeRouter, social.handleRedirect)
return social
}