Browse Source

add google oauth2 support

pull/77/head
skyblue 11 years ago
parent
commit
2ce0c3befe
  1. 4
      models/oauth2.go
  2. 140
      routers/user/social.go
  3. 68
      routers/user/social_github.go
  4. 66
      routers/user/social_google.go
  5. 2
      web.go

4
models/oauth2.go

@ -26,7 +26,7 @@ type Oauth2 struct {
User *User `xorm:"-"` User *User `xorm:"-"`
Type int `xorm:"unique(s) unique(oauth)"` // twitter,github,google... Type int `xorm:"unique(s) unique(oauth)"` // twitter,github,google...
Identity string `xorm:"unique(s) unique(oauth)"` // id.. Identity string `xorm:"unique(s) unique(oauth)"` // id..
Token string `xorm:"VARCHAR(200) not null"` Token string `xorm:"TEXT not null"`
} }
func BindUserOauth2(userId, oauthId int64) error { func BindUserOauth2(userId, oauthId int64) error {
@ -48,7 +48,7 @@ func GetOauth2(identity string) (oa *Oauth2, err error) {
return return
} else if !isExist { } else if !isExist {
return nil, ErrOauth2RecordNotExists return nil, ErrOauth2RecordNotExists
} else if oa.Uid == 0 { } else if oa.Uid == -1 {
return oa, ErrOauth2NotAssociatedWithUser return oa, ErrOauth2NotAssociatedWithUser
} }
oa.User, err = GetUserById(oa.Uid) oa.User, err = GetUserById(oa.Uid)

140
routers/user/social.go

@ -6,65 +6,32 @@ package user
import ( import (
"encoding/json" "encoding/json"
"net/http" "fmt"
"net/url" "net/url"
"strconv"
"strings" "strings"
"code.google.com/p/goauth2/oauth" "code.google.com/p/goauth2/oauth"
"github.com/go-martini/martini"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/middleware" "github.com/gogits/gogs/modules/middleware"
) )
type SocialConnector interface { type BasicUserInfo struct {
Identity() string Identity string
Name() string Name string
Email() string Email string
TokenString() string
}
type SocialGithub struct {
data struct {
Id int `json:"id"`
Name string `json:"login"`
Email string `json:"email"`
}
Token *oauth.Token
} }
func (s *SocialGithub) Identity() string { type SocialConnector interface {
return strconv.Itoa(s.data.Id) Type() int
} SetRedirectUrl(string)
UserInfo(*oauth.Token) (*BasicUserInfo, error)
func (s *SocialGithub) Name() string {
return s.data.Name
}
func (s *SocialGithub) Email() string {
return s.data.Email
}
func (s *SocialGithub) TokenString() string {
data, _ := json.Marshal(s.Token)
return string(data)
}
// Github API refer: https://developer.github.com/v3/users/ AuthCodeURL(string) string
func (s *SocialGithub) Update() error { Exchange(string) (*oauth.Token, error)
scope := "https://api.github.com/user"
transport := &oauth.Transport{
Token: s.Token,
}
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 { func extractPath(next string) string {
@ -75,85 +42,76 @@ func extractPath(next string) string {
return n.Path return n.Path
} }
// github && google && ... var (
func SocialSignIn(ctx *middleware.Context) { SocialBaseUrl = "/user/login"
//if base.OauthService != nil && base.OauthService.GitHub.Enabled { SocialMap = make(map[string]SocialConnector)
//} )
var socid int64 // github && google && ...
var ok bool func SocialSignIn(params martini.Params, ctx *middleware.Context) {
next := extractPath(ctx.Query("next")) if base.OauthService == nil || !base.OauthService.GitHub.Enabled {
log.Debug("social signed check %s", next) ctx.Handle(404, "social login not enabled", nil)
if socid, ok = ctx.Session.Get("socialId").(int64); ok && socid != 0 {
// already login
ctx.Redirect(next)
log.Info("login soc id: %v", socid)
return return
} }
next := extractPath(ctx.Query("next"))
config := &oauth.Config{ name := params["name"]
ClientId: base.OauthService.GitHub.ClientId, connect, ok := SocialMap[name]
ClientSecret: base.OauthService.GitHub.ClientSecret, if !ok {
RedirectURL: strings.TrimSuffix(base.AppUrl, "/") + ctx.Req.URL.RequestURI(), ctx.Handle(404, "social login", nil)
Scope: base.OauthService.GitHub.Scopes, return
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") code := ctx.Query("code")
if code == "" { if code == "" {
// redirect to social login page // redirect to social login page
ctx.Redirect(config.AuthCodeURL(next)) connect.SetRedirectUrl(strings.TrimSuffix(base.AppUrl, "/") + ctx.Req.URL.RequestURI())
ctx.Redirect(connect.AuthCodeURL(next))
return return
} }
// handle call back // handle call back
tk, err := transport.Exchange(code) tk, err := connect.Exchange(code) // transport.Exchange(code)
if err != nil { if err != nil {
log.Error("oauth2 handle callback error: %v", err) log.Error("oauth2 handle callback error: %v", err)
return // FIXME, need error page 501 ctx.Handle(500, "exchange code error", nil)
return
} }
next = extractPath(ctx.Query("state")) next = extractPath(ctx.Query("state"))
log.Debug("success token: %v", tk) log.Trace("success get token")
gh := &SocialGithub{Token: tk} ui, err := connect.UserInfo(tk)
if err = gh.Update(); err != nil { if err != nil {
// FIXME: handle error page 501 ctx.Handle(500, fmt.Sprintf("get infomation from %s error: %v", name, err), nil)
log.Error("connect with github error: %s", err) log.Error("social connect error: %s", err)
return return
} }
var soc SocialConnector = gh log.Info("social login: %s", ui)
log.Info("login: %s", soc.Name()) oa, err := models.GetOauth2(ui.Identity)
oa, err := models.GetOauth2(soc.Identity())
switch err { switch err {
case nil: case nil:
ctx.Session.Set("userId", oa.User.Id) ctx.Session.Set("userId", oa.User.Id)
ctx.Session.Set("userName", oa.User.Name) ctx.Session.Set("userName", oa.User.Name)
case models.ErrOauth2RecordNotExists: case models.ErrOauth2RecordNotExists:
oa = &models.Oauth2{} oa = &models.Oauth2{}
raw, _ := json.Marshal(tk) // json encode
oa.Token = string(raw)
oa.Uid = -1 oa.Uid = -1
oa.Type = models.OT_GITHUB oa.Type = connect.Type()
oa.Token = soc.TokenString() oa.Identity = ui.Identity
oa.Identity = soc.Identity() log.Trace("oa: %v", oa)
log.Debug("oa: %v", oa)
if err = models.AddOauth2(oa); err != nil { if err = models.AddOauth2(oa); err != nil {
log.Error("add oauth2 %v", err) // 501 log.Error("add oauth2 %v", err) // 501
return return
} }
case models.ErrOauth2NotAssociatedWithUser: case models.ErrOauth2NotAssociatedWithUser:
ctx.Session.Set("socialId", oa.Id) next = "/user/sign_up"
ctx.Session.Set("socialName", soc.Name())
ctx.Session.Set("socialEmail", soc.Email())
ctx.Redirect("/user/sign_up")
return
default: default:
log.Error(err.Error()) // FIXME: handle error page log.Error("other error: %v", err)
ctx.Handle(500, err.Error(), nil)
return return
} }
ctx.Session.Set("socialId", oa.Id) ctx.Session.Set("socialId", oa.Id)
log.Debug("socialId: %v", oa.Id) ctx.Session.Set("socialName", ui.Name)
ctx.Session.Set("socialEmail", ui.Email)
log.Trace("socialId: %v", oa.Id)
ctx.Redirect(next) ctx.Redirect(next)
} }

68
routers/user/social_github.go

@ -0,0 +1,68 @@
package user
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"code.google.com/p/goauth2/oauth"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
)
type SocialGithub struct {
Token *oauth.Token
*oauth.Transport
}
func (s *SocialGithub) Type() int {
return models.OT_GITHUB
}
func init() {
github := &SocialGithub{}
name := "github"
config := &oauth.Config{
ClientId: "09383403ff2dc16daaa1", //base.OauthService.GitHub.ClientId, // FIXME: panic when set
ClientSecret: "0e4aa0c3630df396cdcea01a9d45cacf79925fea", //base.OauthService.GitHub.ClientSecret,
RedirectURL: strings.TrimSuffix(base.AppUrl, "/") + "/user/login/" + name, //ctx.Req.URL.RequestURI(),
Scope: "https://api.github.com/user",
AuthURL: "https://github.com/login/oauth/authorize",
TokenURL: "https://github.com/login/oauth/access_token",
}
github.Transport = &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
}
SocialMap[name] = github
}
func (s *SocialGithub) SetRedirectUrl(url string) {
s.Transport.Config.RedirectURL = url
}
func (s *SocialGithub) UserInfo(token *oauth.Token) (*BasicUserInfo, error) {
transport := &oauth.Transport{
Token: token,
}
var data struct {
Id int `json:"id"`
Name string `json:"login"`
Email string `json:"email"`
}
var err error
r, err := transport.Client().Get(s.Transport.Scope)
if err != nil {
return nil, err
}
defer r.Body.Close()
if err = json.NewDecoder(r.Body).Decode(&data); err != nil {
return nil, err
}
return &BasicUserInfo{
Identity: strconv.Itoa(data.Id),
Name: data.Name,
Email: data.Email,
}, nil
}

66
routers/user/social_google.go

@ -0,0 +1,66 @@
package user
import (
"encoding/json"
"net/http"
"github.com/gogits/gogs/models"
"code.google.com/p/goauth2/oauth"
)
type SocialGoogle struct {
Token *oauth.Token
*oauth.Transport
}
func (s *SocialGoogle) Type() int {
return models.OT_GOOGLE
}
func init() {
google := &SocialGoogle{}
name := "google"
// get client id and secret from
// https://console.developers.google.com/project
config := &oauth.Config{
ClientId: "849753812404-mpd7ilvlb8c7213qn6bre6p6djjskti9.apps.googleusercontent.com", //base.OauthService.GitHub.ClientId, // FIXME: panic when set
ClientSecret: "VukKc4MwaJUSmiyv3D7ANVCa", //base.OauthService.GitHub.ClientSecret,
Scope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
google.Transport = &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
}
SocialMap[name] = google
}
func (s *SocialGoogle) SetRedirectUrl(url string) {
s.Transport.Config.RedirectURL = url
}
func (s *SocialGoogle) UserInfo(token *oauth.Token) (*BasicUserInfo, error) {
transport := &oauth.Transport{Token: token}
var data struct {
Id string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
var err error
reqUrl := "https://www.googleapis.com/oauth2/v1/userinfo"
r, err := transport.Client().Get(reqUrl)
if err != nil {
return nil, err
}
defer r.Body.Close()
if err = json.NewDecoder(r.Body).Decode(&data); err != nil {
return nil, err
}
return &BasicUserInfo{
Identity: data.Id,
Name: data.Name,
Email: data.Email,
}, nil
}

2
web.go

@ -88,7 +88,7 @@ func runWeb(*cli.Context) {
m.Group("/user", func(r martini.Router) { m.Group("/user", func(r martini.Router) {
r.Get("/login", user.SignIn) r.Get("/login", user.SignIn)
r.Post("/login", bindIgnErr(auth.LogInForm{}), user.SignInPost) r.Post("/login", bindIgnErr(auth.LogInForm{}), user.SignInPost)
r.Get("/login/github", user.SocialSignIn) r.Get("/login/:name", user.SocialSignIn)
r.Get("/sign_up", user.SignUp) r.Get("/sign_up", user.SignUp)
r.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost) r.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
r.Get("/reset_password", user.ResetPasswd) r.Get("/reset_password", user.ResetPasswd)

Loading…
Cancel
Save