Esempio n. 1
0
func GithubCallback(session sessions.Session, r *http.Request, re render.Render) {
	code, state := r.URL.Query().Get("code"), r.URL.Query().Get("state")
	client_id, client_secret := common.Config.OAuth2Client_ID, common.Config.OAuth2Client_Secret

	flashes := session.Flashes("state")
	if code == "" || state == "" || session == nil || len(flashes) == 0 || flashes[0].(string) != state {
		re.Redirect("/")
		return
	}

	client := &http.Client{}

	form := url.Values{}
	form.Add("code", code)
	form.Add("client_id", client_id)
	form.Add("client_secret", client_secret)

	req, _ := http.NewRequest("POST", "https://github.com/login/oauth/access_token/", strings.NewReader(form.Encode()))
	req.Header.Set("Accept", "application/json")

	resp, _ := client.Do(req)
	body, _ := ioutil.ReadAll(resp.Body)
	parse := map[string]interface{}{}
	json.Unmarshal([]byte(string(body)), &parse)

	token := parse["access_token"].(string)

	req, _ = http.NewRequest("GET", "https://api.github.com/user?access_token="+token, nil)

	resp, _ = client.Do(req)
	body, _ = ioutil.ReadAll(resp.Body)
	parse = map[string]interface{}{}
	json.Unmarshal([]byte(string(body)), &parse)

	username, id := parse["login"].(string), strconv.FormatFloat(parse["id"].(float64), 'f', -1, 64)

	if !common.UserExist(id) {
		common.NewUser(id)
	}

	session.Set("loggedin", true)
	session.Set("username", username)
	session.Set("id", id)
	session.Set("token", token)

	redirectTo := session.Get("redirect_to")
	if redirectTo != nil {
		re.Redirect(redirectTo.(string))
	} else {
		re.Redirect("/")
	}
	session.Set("redirect_to", nil)
}
Esempio n. 2
0
// NewPageData is the constructor for PageData struct
func NewPageData(tokens oauth2.Tokens, session sessions.Session) *PageData {
	pd := &PageData{}

	pd.User = CurrentUser(tokens)

	pd.GravatarImage = fmt.Sprintf(
		"https://secure.gravatar.com/avatar/%x?s=50&d=https%%3A%%2F%%2Fwww.synkee.com%%2Fapp%%2Fstatic%%2Fdist%%2Fimg%%2Fuser.png",
		md5.Sum([]byte(pd.User.Email)))

	pd.AppUrl = config.AppUrl
	pd.Errors = &binding.Errors{}

	pd.SuccessFlash = session.Flashes("success")
	pd.ErrorFlash = session.Flashes("error")

	pd.Config = config

	pd.Settings = &Setting{}
	db.Where(&Setting{UserID: int(pd.User.ID)}).First(pd.Settings)

	// log.Printf("[NewPageData] settings: %s", pd.Settings)

	return pd
}