/
app.go
82 lines (70 loc) · 2.05 KB
/
app.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
package controllers
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"github.com/revel/examples/facebook-oauth2/app/models"
"github.com/revel/revel"
"golang.org/x/oauth2"
"golang.org/x/oauth2/facebook"
)
type Application struct {
*revel.Controller
}
// The following keys correspond to a test application
// registered on Facebook, and associated with the loisant.org domain.
// You need to bind loisant.org to your machine with /etc/hosts to
// test the application locally.
var FACEBOOK = &oauth2.Config{
ClientID: "943076975742162",
ClientSecret: "d3229ebe3501771344bb0f2db2324014",
Scopes: []string{},
Endpoint: facebook.Endpoint,
RedirectURL: "http://loisant.org:9000/Application/Auth",
}
func (c Application) Index() revel.Result {
u := c.connected()
me := map[string]interface{}{}
if u != nil && u.AccessToken != "" {
resp, _ := http.Get("https://graph.facebook.com/me?access_token=" +
url.QueryEscape(u.AccessToken))
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(&me); err != nil {
c.Log.Error("json decode error", "error", err)
}
c.Log.Info("Data fetched", "data", me)
}
authUrl := FACEBOOK.AuthCodeURL("state", oauth2.AccessTypeOffline)
return c.Render(me, authUrl)
}
func (c Application) Auth(code string) revel.Result {
tok, err := FACEBOOK.Exchange(oauth2.NoContext, code)
if err != nil {
c.Log.Error("Exchange error", "error", err)
return c.Redirect(Application.Index)
}
user := c.connected()
user.AccessToken = tok.AccessToken
return c.Redirect(Application.Index)
}
func setuser(c *revel.Controller) revel.Result {
var user *models.User
if _, ok := c.Session["uid"]; ok {
uid, _ := strconv.ParseInt(c.Session["uid"].(string), 10, 0)
user = models.GetUser(int(uid))
}
if user == nil {
user = models.NewUser()
c.Session["uid"] = fmt.Sprintf("%d", user.Uid)
}
c.ViewArgs["user"] = user
return nil
}
func init() {
revel.InterceptFunc(setuser, revel.BEFORE, &Application{})
}
func (c Application) connected() *models.User {
return c.ViewArgs["user"].(*models.User)
}