0
0
Fork 0
mirror of https://github.com/go-gitea/gitea synced 2024-11-25 12:52:48 +01:00

add github social login, first step

This commit is contained in:
skyblue 2014-04-02 08:14:56 +08:00
parent 67bd2daa02
commit 272c27c8f2
2 changed files with 53 additions and 0 deletions

View file

@ -5,11 +5,14 @@
package user
import (
"encoding/json"
"fmt"
"net/url"
"strings"
"code.google.com/p/goauth2/oauth"
"github.com/go-martini/martini"
"github.com/martini-contrib/oauth2"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
@ -74,6 +77,43 @@ func Profile(ctx *middleware.Context, params martini.Params) {
ctx.HTML(200, "user/profile")
}
// github && google && ...
func SocialSignIn(tokens oauth2.Tokens) {
transport := &oauth.Transport{}
transport.Token = &oauth.Token{
AccessToken: tokens.Access(),
RefreshToken: tokens.Refresh(),
Expiry: tokens.ExpiryTime(),
Extra: tokens.ExtraData(),
}
// Github API refer: https://developer.github.com/v3/users/
// FIXME: need to judge url
type GithubUser struct {
Id int `json:"id"`
Name string `json:"login"`
Email string `json:"email"`
}
// Make the request.
scope := "https://api.github.com/user"
r, err := transport.Client().Get(scope)
if err != nil {
log.Error("connect with github error: %s", err)
// FIXME: handle error page
return
}
defer r.Body.Close()
user := &GithubUser{}
err = json.NewDecoder(r.Body).Decode(user)
if err != nil {
log.Error("Get: %s", err)
}
log.Info("login: %s", user.Name)
// FIXME: login here, user email to check auth, if not registe, then generate a uniq username
}
func SignIn(ctx *middleware.Context, form auth.LogInForm) {
ctx.Data["Title"] = "Log In"

13
web.go
View file

@ -11,6 +11,8 @@ import (
"github.com/codegangsta/cli"
"github.com/go-martini/martini"
"github.com/martini-contrib/oauth2"
"github.com/martini-contrib/sessions"
"github.com/gogits/binding"
@ -58,6 +60,16 @@ func runWeb(*cli.Context) {
// Middlewares.
m.Use(middleware.Renderer(middleware.RenderOptions{Funcs: []template.FuncMap{base.TemplateFuncs}}))
scope := "https://api.github.com/user"
oauth2.PathCallback = "/oauth2callback"
m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
m.Use(oauth2.Github(&oauth2.Options{
ClientId: "09383403ff2dc16daaa1",
ClientSecret: "5f6e7101d30b77952aab22b75eadae17551ea6b5",
RedirectURL: base.AppUrl + oauth2.PathCallback,
Scopes: []string{scope},
}))
m.Use(middleware.InitContext())
reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true})
@ -80,6 +92,7 @@ func runWeb(*cli.Context) {
m.Get("/avatar/:hash", avt.ServeHTTP)
m.Group("/user", func(r martini.Router) {
r.Any("/login/github", user.SocialSignIn)
r.Any("/login", binding.BindIgnErr(auth.LogInForm{}), user.SignIn)
r.Any("/sign_up", binding.BindIgnErr(auth.RegisterForm{}), user.SignUp)
}, reqSignOut)