summaryrefslogtreecommitdiffstats
path: root/routers/user/social.go
blob: b87c313f5dd426fc4dba99ece02a9479ae0c5463 (plain)
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
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package user

import (
	"encoding/json"
	"net/http"
	"net/url"
	"strconv"
	"strings"

	"code.google.com/p/goauth2/oauth"

	"github.com/gogits/gogs/models"
	"github.com/gogits/gogs/modules/base"
	"github.com/gogits/gogs/modules/log"
	"github.com/gogits/gogs/modules/middleware"
	"github.com/gogits/gogs/modules/oauth2"
)

type SocialConnector interface {
	Identity() string
	Type() int
	Name() string
	Email() string
	Token() string
}

type SocialGithub struct {
	data struct {
		Id    int    `json:"id"`
		Name  string `json:"login"`
		Email string `json:"email"`
	}
	WebToken *oauth.Token
}

func (s *SocialGithub) Identity() string {
	return strconv.Itoa(s.data.Id)
}

func (s *SocialGithub) Type() int {
	return models.OT_GITHUB
}

func (s *SocialGithub) Name() string {
	return s.data.Name
}

func (s *SocialGithub) Email() string {
	return s.data.Email
}

func (s *SocialGithub) Token() string {
	data, _ := json.Marshal(s.WebToken)
	return string(data)
}

// Github API refer: https://developer.github.com/v3/users/
func (s *SocialGithub) Update() error {
	scope := "https://api.github.com/user"
	transport := &oauth.Transport{
		Token: s.WebToken,
	}
	log.Debug("update github info")
	r, err := transport.Client().Get(scope)
	if err != nil {
		return err
	}
	defer r.Body.Close()
	return json.NewDecoder(r.Body).Decode(&s.data)
}

func extractPath(next string) string {
	n, err := url.Parse(next)
	if err != nil {
		return "/"
	}
	return n.Path
}

// github && google && ...
func SocialSignIn(ctx *middleware.Context, tokens oauth2.Tokens) {
	var socid int64
	var ok bool
	next := extractPath(ctx.Query("next"))
	log.Debug("social signed check %s", next)
	if socid, ok = ctx.Session.Get("socialId").(int64); ok && socid != 0 {
		// already login
		ctx.Redirect(next)
		log.Info("login soc id: %v", socid)
		return
	}
	config := &oauth.Config{
		//ClientId: base.OauthService.Github.ClientId,
		//ClientSecret: base.OauthService.Github.ClientSecret, // FIXME: I don't know why compile error here
		ClientId:     "09383403ff2dc16daaa1",
		ClientSecret: "0e4aa0c3630df396cdcea01a9d45cacf79925fea",
		RedirectURL:  strings.TrimSuffix(base.AppUrl, "/") + ctx.Req.URL.RequestURI(),
		Scope:        base.OauthService.GitHub.Scopes,
		AuthURL:      "https://github.com/login/oauth/authorize",
		TokenURL:     "https://github.com/login/oauth/access_token",
	}
	transport := &oauth.Transport{
		Config:    config,
		Transport: http.DefaultTransport,
	}
	code := ctx.Query("code")
	if code == "" {
		// redirect to social login page
		ctx.Redirect(config.AuthCodeURL(next))
		return
	}

	// handle call back
	tk, err := transport.Exchange(code)
	if err != nil {
		log.Error("oauth2 handle callback error: %v", err)
		return // FIXME, need error page 501
	}
	next = extractPath(ctx.Query("state"))
	log.Debug("success token: %v", tk)

	gh := &SocialGithub{WebToken: tk}
	if err = gh.Update(); err != nil {
		// FIXME: handle error page 501
		log.Error("connect with github error: %s", err)
		return
	}
	var soc SocialConnector = gh
	log.Info("login: %s", soc.Name())
	oa, err := models.GetOauth2(soc.Identity())
	switch err {
	case nil:
		ctx.Session.Set("userId", oa.User.Id)
		ctx.Session.Set("userName", oa.User.Name)
	case models.ErrOauth2RecordNotExists:
		oa = &models.Oauth2{}
		oa.Uid = 0
		oa.Type = soc.Type()
		oa.Token = soc.Token()
		oa.Identity = soc.Identity()
		log.Debug("oa: %v", oa)
		if err = models.AddOauth2(oa); err != nil {
			log.Error("add oauth2 %v", err) // 501
			return
		}
	case models.ErrOauth2NotAssociatedWithUser:
		// ignore it. judge in /usr/login page
	default:
		log.Error(err.Error()) // FIXME: handle error page
		return
	}
	ctx.Session.Set("socialId", oa.Id)
	log.Debug("socialId: %v", oa.Id)
	ctx.Redirect(next)
}