Exemple #1
0
func rtRoot(w http.ResponseWriter, r *http.Request, args []string) error {
	sess := getSession(r)
	if sess == nil || sess.token == nil {
		http.Redirect(w, r, "/oauth2/login", http.StatusFound)
		return nil
	}

	t := oauth.Transport{
		Config: oauthConfig,
		Token:  sess.token,
	}

	if er := t.Refresh(); er != nil {
		return er
	}

	res, er := t.Client().Get("https://api.guildwars2.com/v2/account")
	if er != nil {
		return er
	}

	w.Header().Set("Content-Type", "application/json")
	io.Copy(w, res.Body)

	return nil
}
Exemple #2
0
func get_profile_facebook(transport *oauth.Transport) (Profile, error) {
	resp, err := transport.Client().Get("https://graph.facebook.com/me?fields=id,name,first_name,last_name,email,username,picture.width(256).height(256)")
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	if resp.StatusCode/100 != 2 {
		return nil, fmt.Errorf("http status: %d", resp.StatusCode)
	}

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	profile := &FacebookProfile{}

	err = json.Unmarshal(data, &profile)
	if err != nil {
		return nil, err
	}

	profile.raw = data

	return profile, nil
}
Exemple #3
0
func get_profile_github(transport *oauth.Transport) (Profile, error) {
	resp, err := transport.Client().Get("https://api.github.com/user")
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	if resp.StatusCode/100 != 2 {
		return nil, fmt.Errorf("http status: %d", resp.StatusCode)
	}

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	profile := &GithubProfile{}

	err = json.Unmarshal(data, &profile)
	if err != nil {
		return nil, err
	}

	profile.raw = data

	return profile, nil
}
Exemple #4
0
// GetHttpClient returns a http.Client which performs authenticated requests as
// the logged-in user.
func GetHttpClient(r *http.Request) *http.Client {
	s, err := getSession(r)
	if err != nil {
		glog.Errorf("Failed to get session state; falling back to default http client.")
		return &http.Client{}
	}
	t := oauth.Transport{
		Config: oauthConfig,
		Token:  s.Token,
	}
	return t.Client()
}
// This function does the work of obtaining the contacts from the server
func fetch_all_contacts(transport *oauth.Transport) contacts_response {
	// XXX: increase the max-results
	request_url := fmt.Sprintf("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&max-results=10000")
	// fmt.Println("request_url is", request_url)
	resp, _ := transport.Client().Get(request_url)
	defer resp.Body.Close()

	var result contacts_response
	err := json.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		log.Fatal(err)
	}
	return result
}
Exemple #6
0
// obtain user data from constant REQUEST_API
// UserInfo is used to Unmarshal the json response
// returns UserInfor strct for display
func userData(w http.ResponseWriter, transport *oauth.Transport, token string, ui *UserInfo) (UserInfo, error) {
	url := REQUEST_API + token
	resp, err := transport.Client().Get(url)
	if err != nil {
		http.Error(w, "api error", http.StatusInternalServerError)
		return *ui, errors.New("api error")
	}
	defer resp.Body.Close()

	d, _ := ioutil.ReadAll(resp.Body)

	err = json.Unmarshal(d, &ui)

	return *ui, nil
}
Exemple #7
0
func initializeApiService(c appengine.Context) (*api.Service, error) {
	d := datastore.New(c)
	token, err := d.FindToken(user.Current(c).Email)
	if err != nil {
		return nil, err
	}

	transport := oauth.Transport{
		Token:     &token,
		Config:    &cfg,
		Transport: urlfetch.Client(c).Transport,
	}

	return api.NewFromClient(transport.Client(), token.AccessToken), nil
}
Exemple #8
0
func newOauthClient(storePath string) *http.Client {
	config := &oauth.Config{
		ClientId:     ClientId,
		ClientSecret: ClientSecret,
		Scope:        raw.ComputeScope,
		AuthURL:      AuthURL,
		TokenURL:     TokenURL,
	}
	token := token(storePath, config)
	t := oauth.Transport{
		Token:     token,
		Config:    config,
		Transport: http.DefaultTransport,
	}
	return t.Client()
}
Exemple #9
0
Fichier : rpc.go Projet : 0x7cc/rsc
func httpGET(auth *Auth, url string) ([]byte, error) {
	verb := "GET"
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	if i := strings.Index(url, "?"); i >= 0 {
		url = url[:i]
	}
	req.Header.Set("X-CloudPrint-Proxy", auth.ProxyID)

	var client *http.Client
	if auth.Token.AccessToken != "" {
		var tr oauth.Transport
		tr.Config = &oauth.Config{
			ClientId:     auth.APIClientID,
			ClientSecret: auth.APIClientSecret,
			Scope:        "https://www.googleapis.com/auth/cloudprint https://www.googleapis.com/auth/googletalk",
			AuthURL:      "https://accounts.google.com/o/oauth2/auth",
			TokenURL:     "https://accounts.google.com/o/oauth2/token",
			RedirectURL:  "oob",
		}
		tr.Token = &auth.Token
		client = tr.Client()
	} else {
		client = http.DefaultClient
	}

	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("%s %s: %v", verb, url, err)
	}
	defer resp.Body.Close()
	var buf bytes.Buffer
	_, err = io.Copy(&buf, resp.Body)
	if err != nil {
		return nil, fmt.Errorf("%s %s: reading HTTP response: %v", verb, url, err)
	}

	// TODO: Check 200

	return buf.Bytes(), nil
}
Exemple #10
0
func (self *GoogleUser) Fetch(transport *oauth.Transport) (*GoogleUser, error) {
	r, err := transport.Client().Get(GOOGLE_USER_INFO)
	if err != nil {
		return nil, err
	}
	defer r.Body.Close()
	body, _ := ioutil.ReadAll(r.Body)
	if err != nil {
		return nil, err
	}
	s := string(body)
	decoder := json.NewDecoder(strings.NewReader(s))
	result := &GoogleUser{}
	err = decoder.Decode(&result)
	if err != nil {
		return nil, err
	}
	return result, nil
}
func (a *GoogleOAuthHandler) getBaseUserInfo(t *oauth.Transport) *googleUserInfoJSON {
	req, err := t.Client().Get("https://www.googleapis.com/oauth2/v1/userinfo")
	if err != nil {
		panic(err)
	}
	defer req.Body.Close()

	body, _ := ioutil.ReadAll(req.Body)

	var user_info googleUserInfoJSON
	json_err := json.Unmarshal(body, &user_info)
	if json_err != nil {
		panic(json_err)
	}

	if user_info.Id == "" {
		panic(errors.New(fmt.Sprintf("Incorrect JSON response from Google: %s", body)))
	}

	return &user_info
}
func (a *GoogleOAuthHandler) getExtendedUserInfo(t *oauth.Transport, info *googleUserInfoJSON) *googlePeopleInfoJSON {
	req, err := t.Client().Get(fmt.Sprintf("https://www.googleapis.com/plus/v1/people/%s", info.Id))
	if err != nil {
		panic(err)
	}
	defer req.Body.Close()

	body, _ := ioutil.ReadAll(req.Body)

	var user_info googlePeopleInfoJSON
	json_err := json.Unmarshal(body, &user_info)
	if json_err != nil {
		panic(json_err)
	}

	if user_info.Id != info.Id {
		panic(errors.New(fmt.Sprintf("Incorrect JSON response from Google: %s", body)))
	}

	return &user_info
}
Exemple #13
0
func (s *OAuthScheme) Auth(header string) (auth.Token, error) {
	token, err := getToken(header)
	if err != nil {
		nativeScheme := native.NativeScheme{}
		token, nativeErr := nativeScheme.Auth(header)
		if nativeErr == nil && token.IsAppToken() {
			return token, nil
		}
		return nil, err
	}
	config, err := s.loadConfig()
	if err != nil {
		return nil, err
	}
	transport := goauth2.Transport{Config: &config}
	transport.Token = &token.Token
	client := transport.Client()
	_, err = client.Get(s.InfoUrl)
	if err != nil {
		return nil, err
	}
	return makeToken(transport.Token), nil
}
func getCurrentUser(r *http.Request, t *oauth.Transport) (*models.User, error) {
	// Make the request.
	request, err := t.Client().Get("https://www.googleapis.com/oauth2/v1/userinfo?alt=json")

	if err != nil {
		return nil, err
	}

	if userInfo, err := ioutil.ReadAll(request.Body); err == nil {
		var gu models.GoogleUser

		if err := json.Unmarshal(userInfo, &gu); err == nil {
			// create new user if he doesn't already exist
			if currentUser, err = models.GetUser(r, gu.Id, gu.Email); err != nil {
				currentUser, err = models.NewUser(r, gu.Id, gu.Email, gu.Name, "google")
			}

			return currentUser, err
		}
	}

	return nil, err
}
Exemple #15
0
func oauthCallbackHandler(w http.ResponseWriter, r *http.Request) {
	profileInfoURL := "https://www.googleapis.com/oauth2/v1/userinfo?alt=json"
	code := r.FormValue("code")
	t := oauth.Transport{Config: oauthCfg}
	t.Exchange(code)
	resp, err := t.Client().Get(profileInfoURL)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	user := User{}
	contents, err := ioutil.ReadAll(resp.Body)
	json.Unmarshal(contents, &user)

	session, _ := store.Get(r, "session")
	session.Values["UserId"] = user.Id
	session.Values["GivenName"] = user.Given_Name
	log.Printf("** %s Logged in **", user.Name)
	session.Save(r, w)

	http.Redirect(w, r, "/view/", http.StatusFound)
}
Exemple #16
0
Fichier : rpc.go Projet : 0x7cc/rsc
func jsonRPC(auth *Auth, verb, url string, mr *multipartRequest, dst interface{}) error {
	var reader io.Reader
	if mr != nil {
		if auth.ProxyID != "" {
			mr.WriteField("proxy", auth.ProxyID)
		}
		mr.Writer.Close()
		reader = &mr.buf
	}
	req, err := http.NewRequest(verb, url, reader)
	if err != nil {
		return err
	}
	if i := strings.Index(url, "?"); i >= 0 {
		url = url[:i]
	}
	if mr != nil {
		req.Header.Set("Content-Type", mr.FormDataContentType())
	}
	if auth.ProxyID != "" {
		req.Header.Set("X-CloudPrint-Proxy", auth.ProxyID)
	}

	var client *http.Client
	if auth.Token.AccessToken != "" {
		var tr oauth.Transport
		tr.Config = &oauth.Config{
			ClientId:     auth.APIClientID,
			ClientSecret: auth.APIClientSecret,
			Scope:        "https://www.googleapis.com/auth/cloudprint https://www.googleapis.com/auth/googletalk",
			AuthURL:      "https://accounts.google.com/o/oauth2/auth",
			TokenURL:     "https://accounts.google.com/o/oauth2/token",
			RedirectURL:  "oob",
		}
		tr.Token = &auth.Token
		client = tr.Client()
	} else {
		client = http.DefaultClient
	}

	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("%s %s: %v", verb, url, err)
	}
	defer resp.Body.Close()
	var buf bytes.Buffer
	_, err = io.Copy(&buf, resp.Body)
	if err != nil {
		return fmt.Errorf("%s %s: reading HTTP response: %v", verb, url, err)
	}

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("%s %s: %s\n%s", verb, url, resp.Status, buf.Bytes())
	}

	fmt.Printf("%s\n", buf.Bytes())

	var js jsonStatus
	if err := json.Unmarshal(buf.Bytes(), &js); err != nil {
		return fmt.Errorf("%s %s: invalid JSON response: %v", verb, url, err)
	}
	if !js.Success {
		suffix := ""
		if js.Message != "" {
			msg := js.Message
			if len(msg) > 2 && 'A' <= msg[0] && msg[0] <= 'Z' && 'a' <= msg[1] && msg[1] <= 'z' {
				msg = string(msg[0]+'a'-'A') + msg[1:]
			}
			suffix = ": " + msg
		} else {
			suffix = "\n" + buf.String()
		}
		return fmt.Errorf("%s %s: server rejected request%s", verb, url, suffix)
	}

	if dst != nil {
		if err := json.Unmarshal(buf.Bytes(), dst); err != nil {
			return fmt.Errorf("%s %s: invalid JSON response: %v", verb, url, err)
		}
	}

	return nil
}