Skip to content

Instantly share code, notes, and snippets.

@smallnest
Created February 28, 2019 07:01
Show Gist options
  • Select an option

  • Save smallnest/2bb81c94666301590093bdf7cc4dff24 to your computer and use it in GitHub Desktop.

Select an option

Save smallnest/2bb81c94666301590093bdf7cc4dff24 to your computer and use it in GitHub Desktop.
package auth
import (
"net/http"
"net/url"
"strings"
"time"
"colobu.com/tr/common/data"
"colobu.com/tr/common/db"
"golang.org/x/oauth2"
"github.com/bitly/go-simplejson"
"github.com/go-zoo/bone"
"github.com/golang/glog"
"github.com/kidstuff/mongostore"
"github.com/satori/go.uuid"
"github.com/smallnest/goreq"
)
var oauthQQConf = &oauth2.Config{
ClientID: "11111111",
ClientSecret: "asdsadsadsadsadsadsadsdsds",
Scopes: []string{"get_user_info"},
RedirectURL: "http://tr.colobu.com/signin/qq/callback",
Endpoint: oauth2.Endpoint{AuthURL: "https://graph.qq.com/oauth2.0/authorize",
TokenURL: "https://graph.qq.com/oauth2.0/token"},
}
// RegisterQQAuth handle qq oauth2
func RegisterQQAuth(mux *bone.Mux, store *mongostore.MongoStore) {
mux.GetFunc("/signin/qq", func(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "gosessionid")
oauthStateString := uuid.NewV4().String()
session.Values["oauthStateString"] = oauthStateString
session.Save(r, w)
url := oauthQQConf.AuthCodeURL(oauthStateString, oauth2.AccessTypeOnline)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
})
mux.GetFunc("/signin/qq/callback", func(w http.ResponseWriter, r *http.Request) {
state := r.FormValue("state")
session, _ := store.Get(r, "gosessionid")
oauthStateString := session.Values["oauthStateString"]
if state != oauthStateString {
glog.Errorf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
http.Redirect(w, r, "/signin", http.StatusTemporaryRedirect)
return
}
code := r.FormValue("code")
// token, err := oauthQQConf.Exchange(oauth2.NoContext, code)
// if err != nil {
// glog.Errorf("oauthConf.Exchange() failed with '%s'\n", err)
// http.Redirect(w, r, "/signin", http.StatusTemporaryRedirect)
// return
// }
_, body, errors := goreq.New().Get("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=" + oauthQQConf.ClientID +
"&client_secret=" + oauthQQConf.ClientSecret + "&code=" + code +
"&redirect_uri=" + oauthQQConf.RedirectURL).ContentType("html").End()
if len(errors) > 0 {
glog.Errorf("oauthConf.Exchange() failed with '%v'\n", errors)
http.Redirect(w, r, "/signin", http.StatusTemporaryRedirect)
return
}
v, err := url.ParseQuery(body)
if err != nil {
glog.Errorf("Parse failed with '%s'\n", body)
http.Redirect(w, r, "/signin", http.StatusTemporaryRedirect)
return
}
accessToken := v.Get("access_token")
// tr := &http.Transport{
// TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
// }
// client := &http.Client{Transport: tr}
_, body, errors = goreq.New().Get("https://graph.qq.com/oauth2.0/me?access_token=" + accessToken).End()
if len(errors) > 0 || len(body) == 0 {
glog.Errorf("client.Get() failed with '%v'\n", errors)
http.Redirect(w, r, "/signin", http.StatusTemporaryRedirect)
return
}
openidStart := strings.Index(body, "\"openid\":\"")
openidEnd := strings.Index(body, "\"}")
openid := body[openidStart+10 : openidEnd]
//returnJSON := make(map[string]*json.RawMessage)
_, bytes, errors := goreq.New().Get("https://graph.qq.com/user/get_user_info?access_token=" +
accessToken + "&oauth_consumer_key=" + oauthQQConf.ClientID +
"&openid=" + openid).ContentType("html").EndBytes()
json, err := simplejson.NewJson(bytes)
nickname := json.Get("nickname").MustString()
avatar := json.Get("figureurl_2").MustString()
glog.Infof("Logged in as QQ user: %s\n", nickname)
session.Values["userLogin"] = openid
session.Values["userName"] = nickname
session.Values["userRole"] = data.CommonUser
session.Values["userFrom"] = "qq"
session.Values["avatar"] = avatar
session.Save(r, w)
var userDataStore = &db.UserDataStore{DataStore: CommonTRSession.NewDataStore()}
defer userDataStore.Close()
user := userDataStore.FindByLoginAndFrom(openid, "qq")
if user.UserLogin == "" {
u := data.User{UserLogin: openid, UserName: nickname, Role: data.CommonUser, RegistedFrom: "qq",
RegistedDate: time.Now(), Avatar: avatar}
u.SetPassword("unset")
userDataStore.InsertUser(&u)
} else if avatar != user.Avatar {
userDataStore.UpdateAvatar(user.ID, avatar)
}
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment