Esempio n. 1
0
func initTransport(transport *oauth.Transport) error {
	// First: check the cache.
	if token, err := transport.Config.TokenCache.Token(); err == nil {
		// We have a token, refresh it. The lifetime is 1h, so we always
		// refresh to ensure lengthy commands do not time out.
		transport.Token = token
		err := transport.Refresh()
		if err == nil {
			return nil
		}
		log.Infof("token refresh failed, requesting new one")
	}

	// Get a new token. Pops up a browser window (hopefully).
	randState := fmt.Sprintf("st%d", time.Now().UnixNano())
	authURL := transport.Config.AuthCodeURL(randState)
	log.Infof("Opening auth URL in browser: %s", authURL)
	log.Infof("If the URL doesn't open please open it manually and copy the code here.")
	openURL(authURL)
	code := getCodeFromStdin()

	_, err := transport.Exchange(code)
	if err != nil {
		log.Infof("problem exchanging code: %v", err)
		return err
	}

	return nil
}
Esempio n. 2
0
File: print.go Progetto: 0x7cc/rsc
// VerifyClaim checks that the printer has been claimed.
// If the printer is claimed, VerifyClaim returns no error.
// If the printer is unclaimed, VerifyClaim retruns ErrUnclaimed.
// It is possible for VerifyClaim to return other errors, such as
// in the case of network problems.
//
// A side effect of verifying that claim is that Google creates
// a synthetic account that is only useful in a future call to
// NewServer, to manage just this one printer.
// The information about that account can be retrieved
// from the Auth, Printer, and Server methods after VerifyClaim
// succeeds.
func (p *OpenPrinter) VerifyClaim() error {
	if p.verify != nil {
		return nil
	}

	var resp verifyResponse
	if err := jsonRPC(&p.auth, "GET", p.register.PollingURL+p.auth.APIClientID, nil, &resp); err != nil {
		return fmt.Errorf("VerifyClaim: %v", err)
	}

	var tr oauth.Transport
	tr.Config = &oauth.Config{
		ClientId:     p.auth.APIClientID,
		ClientSecret: p.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",
	}
	tok, err := tr.Exchange(resp.AuthorizationCode)
	if err != nil {
		return fmt.Errorf("VerifyClaim: oauth exchange: %v", err)
	}

	p.auth.Token = *tok
	p.auth.TokenUser = resp.UserEmail
	p.auth.XMPPJID = resp.XMPPJID
	p.verify = &resp
	return nil
}
Esempio n. 3
0
func authenticate(transport *oauth.Transport) error {
	code := make(chan string)

	listener, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		return err
	}
	go http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, closeMessage)
		code <- r.FormValue("code") // send code to OAuth flow
		listener.Close()            // shut down HTTP server
	}))

	transport.Config.RedirectURL = fmt.Sprintf("http://%s/", listener.Addr())
	url := transport.Config.AuthCodeURL("")
	if err := openURL(url); err != nil {
		fmt.Fprintln(os.Stderr, visitMessage)
	} else {
		fmt.Fprintln(os.Stderr, openedMessage)
	}
	fmt.Fprintf(os.Stderr, "\n%s\n\n", url)
	fmt.Fprintln(os.Stderr, resumeMessage)

	_, err = transport.Exchange(<-code)
	return err
}
Esempio n. 4
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
}
Esempio n. 5
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
}
Esempio n. 6
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
}
Esempio n. 7
0
func getToken(t *oauth.Transport) {
	var c string
	authURL := config.AuthCodeURL("state")
	log.Printf("Open in browser: %v\n", authURL)
	log.Printf("Enter verification code: ")
	fmt.Scanln(&c)
	_, err := t.Exchange(c)
	if err != nil {
		log.Fatalf("An error occurred exchanging the code: %v\n", err)
	}
}
Esempio n. 8
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()
}
Esempio n. 9
0
// 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
}
func authorize(w http.ResponseWriter, r *http.Request, t *oauth.Transport) (*oauth.Token, error) {
	//Get the code from the response
	code := r.FormValue("code")

	if code == "" {
		// Get an authorization code from the data provider.
		// ("Please ask the user if I can access this resource.")
		url := config.AuthCodeURL("")
		http.Redirect(w, r, url, http.StatusFound)
		return nil, nil
	}
	// Exchange the authorization code for an access token.
	// ("Here's the code you gave the user, now give me a token!")
	return t.Exchange(code)
}
Esempio n. 11
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
}
Esempio n. 12
0
func handleOAuth2Callback(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
	next := extractPath(r.URL.Query().Get("state"))
	code := r.URL.Query().Get("code")
	tk, err := t.Exchange(code)
	if err != nil {
		// Pass the error message, or allow dev to provide its own
		// error handler.
		http.Redirect(w, r, PathError, codeRedirect)
		return
	}
	// Store the credentials in the session.
	val, _ := json.Marshal(tk)
	s.Set(keyToken, val)
	http.Redirect(w, r, next, codeRedirect)
}
Esempio n. 13
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
}
Esempio n. 14
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()
}
Esempio n. 15
0
// Returns true if we have a valid cached token
func hasValidToken(cacheFile oauth.CacheFile, transport *oauth.Transport) bool {
	// Check if we have a cached token
	token, err := cacheFile.Token()
	if err != nil {
		return false
	}

	// Refresh token if its expired
	if token.Expired() {
		transport.Token = token
		err = transport.Refresh()
		if err != nil {
			fmt.Println(err)
			return false
		}
	}
	return true
}
Esempio n. 16
0
File: rpc.go Progetto: 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
}
Esempio n. 17
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
}
Esempio n. 18
0
func obtainToken(transport *oauth.Transport) {
	t, _ := config.TokenCache.Token()
	if t != nil {
		return
	}

	authUrl := config.AuthCodeURL("state")
	fmt.Printf("Go to the following link in your browser: %v\n", authUrl)

	fmt.Printf("Enter verification code: ")
	var code string
	fmt.Scanln(&code)

	// Read the code, and exchange it for a token.
	_, err := transport.Exchange(code)
	if err != nil {
		log.Errorf("An error occurred exchanging the token: %v\n", err)
		panic(-2)
	}
}
Esempio n. 19
0
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
}
Esempio n. 20
0
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
}
Esempio n. 21
0
// handleTimelineNotification processes a timeline notification.
func handleTimelineNotification(c appengine.Context, svc *mirror.Service, not *mirror.Notification, transport *oauth.Transport) error {
	for _, ua := range not.UserActions {
		if ua.Type != "SHARE" {
			c.Infof("I don't know what to do with this notification: %+v", ua)
			continue
		}
		t, err := svc.Timeline.Get(not.ItemId).Do()
		if err != nil {
			return fmt.Errorf("Unable to retrieve timeline item: %s", err)
		}
		nt := &mirror.TimelineItem{
			Text:         fmt.Sprintf("Echoing your shared item: %s", t.Text),
			Notification: &mirror.NotificationConfig{Level: "DEFAULT"},
		}
		tic := svc.Timeline.Insert(nt)
		if t.Attachments != nil && len(t.Attachments) > 0 {
			a, err := svc.Timeline.Attachments.Get(t.Id, t.Attachments[0].Id).Do()
			if err != nil {
				return fmt.Errorf("Unable to retrieve attachment metadata: %s", err)
			}
			req, err := http.NewRequest("GET", a.ContentUrl, nil)
			if err != nil {
				return fmt.Errorf("Unable to create new HTTP request: %s", err)
			}
			resp, err := transport.RoundTrip(req)
			if err != nil {
				return fmt.Errorf("Unable to retrieve attachment content: %s", err)
			}
			defer resp.Body.Close()
			tic.Media(resp.Body)
		}
		_, err = tic.Do()
		if err != nil {
			return fmt.Errorf("Unable to insert timeline item: %s", err)
		}
	}
	return nil
}
Esempio n. 22
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)
}
Esempio n. 23
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
}
Esempio n. 25
0
File: rpc.go Progetto: 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
}
Esempio n. 26
0
func Setup(r pork.Router, ctx *context.Context) {
	r.RespondWithFunc("/auth/a", func(w pork.ResponseWriter, r *http.Request) {
		http.Redirect(w, r,
			configFromRequest(ctx.Cfg, r).AuthCodeURL(""),
			http.StatusTemporaryRedirect)
	})

	r.RespondWithFunc("/auth/z", func(w pork.ResponseWriter, r *http.Request) {
		code := r.FormValue("code")
		if code == "" {
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}

		tx := oauth.Transport{
			Config: configFromRequest(ctx.Cfg, r),
		}

		_, err := tx.Exchange(code)
		if err != nil {
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}

		var user ghUser
		if err := fetchGhUser(&tx, &user); err != nil {
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}

		sess, err := createSessionFrom(ctx, &user, tx.Token)
		if err != nil {
			panic(err)
		}

		if err := setAuthCookie(w, ctx.Cfg, sess); err != nil {
			panic(err)
		}
	})

	r.RespondWithFunc("/auth/sock", func(w pork.ResponseWriter, r *http.Request) {
		sess, err := SessionFromRequest(ctx, r)
		if err != nil {
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}

		buf, err := secure.Encrypt(sess.Key, ctx.Cfg.AesKey, ctx.Cfg.HmacKey)
		if err != nil {
			panic(err)
		}

		var res bytes.Buffer
		e := base62.NewEncoder(&res)
		if _, err := e.Write(buf); err != nil {
			panic(err)
		}
		e.Close()

		w.Header().Set("Content-Type", "text/plain")
		w.Write(res.Bytes())
	})

	r.RespondWithFunc("/auth/exit", func(w pork.ResponseWriter, r *http.Request) {
		sid, err := SessionIdFromRequest(ctx, r)
		if err != nil {
			panic(err)
		}

		if sid == nil {
			return
		}

		if err := store.DeleteSession(ctx, sid); err != nil {
			panic(err)
		}

		http.SetCookie(w, &http.Cookie{
			Name:     AuthCookieName,
			Value:    "",
			Path:     "/",
			MaxAge:   0,
			HttpOnly: true,
		})
	})
}
Esempio n. 27
0
func ClientFactory(token string, transport *oauth.Transport) *Client {
	t := &oauth.Token{AccessToken: token}
	transport.Token = t
	c := Client{AccessToken: token, transport: transport}
	return &c
}