-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathfacebook.go
81 lines (64 loc) · 2.26 KB
/
facebook.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
// Copyright 2012-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package rest
import (
"net/http"
"net/url"
"github.com/couchbase/sync_gateway/auth"
"github.com/couchbase/sync_gateway/base"
)
const kFacebookOpenGraphURL = "https://graph.facebook.com"
type FacebookResponse struct {
Id string
Name string
Email string
}
// POST /_facebook creates a facebook-based login session and sets its cookie.
func (h *handler) handleFacebookPOST() error {
// CORS not allowed for login #115 #762
originHeader := h.rq.Header["Origin"]
if len(originHeader) > 0 {
matched := auth.MatchedOrigin(h.server.Config.API.CORS.LoginOrigin, originHeader)
if matched == "" {
return base.HTTPErrorf(http.StatusBadRequest, "No CORS")
}
}
var params struct {
AccessToken string `json:"access_token"`
}
err := h.readJSONInto(¶ms)
if err != nil {
return err
}
facebookResponse, err := verifyFacebook(kFacebookOpenGraphURL, params.AccessToken)
if err != nil {
return err
}
createUserIfNeeded := h.server.Config.DeprecatedConfig.Facebook.Register
return h.makeSessionFromNameAndEmail(facebookResponse.Id, facebookResponse.Email, createUserIfNeeded)
}
func verifyFacebook(fbUrl, accessToken string) (*FacebookResponse, error) {
params := url.Values{"fields": []string{"id,name,email"}, "access_token": []string{accessToken}}
destUrl := fbUrl + "/me?" + params.Encode()
res, err := http.Get(destUrl)
if err != nil {
return nil, base.HTTPErrorf(http.StatusGatewayTimeout, "Unable to send request to Facebook API: %v", err)
}
defer func() { _ = res.Body.Close() }()
if res.StatusCode >= 300 {
return nil, base.HTTPErrorf(http.StatusUnauthorized,
"Facebook verification server status %d", res.StatusCode)
}
decoder := base.JSONDecoder(res.Body)
var response FacebookResponse
err = decoder.Decode(&response)
if err != nil {
return nil, base.HTTPErrorf(http.StatusBadGateway, "Invalid response from Facebook verifier")
}
return &response, nil
}