Ejemplo n.º 1
0
func doTestRequireAuthc(p *Provider, t *testing.T) {
	h := p.RequireAuthc(fooHandler)
	hserv := httptest.NewServer(h)
	defer hserv.Close()
	//
	// Valid Authentication
	//
	auth, _ := p.NewAuthz("jtkirk", "", nil)
	header := make(http.Header)
	header.Add("Authorization", "Bearer "+auth.Token)
	rr := restclient.RequestResponse{
		Url:    hserv.URL,
		Method: "GET",
		Header: &header,
	}
	status, err := restclient.Do(&rr)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, 200, status)
	//
	// Invalid Auth Token
	//
	header = make(http.Header)
	header.Add("Authorization", "Bearer foorbar") // "foobar" is not a valid token
	rr = restclient.RequestResponse{
		Url:    hserv.URL,
		Method: "GET",
		Header: &header,
	}
	status, err = restclient.Do(&rr)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, 401, status)
	//
	// No Auth Token
	//
	rr = restclient.RequestResponse{
		Url:    hserv.URL,
		Method: "GET",
	}
	status, err = restclient.Do(&rr)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, 401, status)
}
Ejemplo n.º 2
0
func newArtist(hserv *httptest.Server) (*Artist, error) {
	url := hserv.URL + "/api/v1/artists"
	a := Artist{}
	rr := restclient.RequestResponse{
		Url:            url,
		Method:         "POST",
		Data:           &ggAllin,
		Result:         &a,
		ExpectedStatus: 200,
	}
	_, err := restclient.Do(&rr)
	return &a, err
}
Ejemplo n.º 3
0
func (gs *GoogleSearch) Query(s string) (hits int, err error) {
	u, err := url.Parse(googleSearchApi)
	if err != nil {
		return -1, err
	}
	v := url.Values{}
	v.Set("key", gs.ApiKey)
	v.Set("cx", gs.CustomSearchId)
	v.Set("q", s)
	u.RawQuery = v.Encode()
	resp := struct {
		Queries struct {
			Request []struct {
				TotalResults string `json:"totalResults"`
			} `json:"requests"`
		} `json:"queries"`
	}{}
	e := new(interface{})
	req := restclient.RequestResponse{
		Url:    u.String(),
		Method: "GET",
		Result: &resp,
		Error:  e,
	}
	status, err := restclient.Do(&req)
	if err != nil {
		return -1, err
	}
	if status != 200 {
		log.Printf("Bad response code from Google: %v", status)
		return -1, BadResponse
	}
	if len(resp.Queries.Request) < 1 {
		err = errors.New("Could not parse JSON response from Google.")
		return -1, BadResponse
	}
	count, err := strconv.Atoi(resp.Queries.Request[0].TotalResults)
	if err != nil {
		return -1, err
	}
	return count, nil
}
Ejemplo n.º 4
0
func (bs *BingSearch) Query(s string) (hits int, err error) {
	query := fmt.Sprintf("'%v'", s) // Enclose in single quote marks
	payload := map[string]string{
		"Sources": "'web'", // Inner single quote marks are required
		"$format": "json",  // Yes the $ prefix is correct
		"Query":   query,
	}
	resp := struct {
		D struct {
			Results []struct {
				Total string `json:"WebTotal"`
			} `json:"results"`
		} `json:"d"`
	}{}
	req := restclient.RequestResponse{
		Url:      bingSearchApi,
		Method:   "GET",
		Userinfo: url.UserPassword(bs.CustomerId, bs.Key),
		Params:   payload,
		Result:   &resp,
	}
	// r.json['d']['results'][0]['WebTotal']
	status, err := restclient.Do(&req)
	if err != nil {
		return -1, err
	}
	if status != 200 {
		log.Printf("Bad response code from Bing: %v", status)
		return -1, BadResponse
	}
	if len(resp.D.Results) != 1 {
		log.Printf("Expected single item in results dict, but got", len(resp.D.Results))
		return -1, BadResponse
	}
	hits, err = strconv.Atoi(resp.D.Results[0].Total)
	if err != nil {
		return -1, err
	}
	return hits, nil
}
Ejemplo n.º 5
0
func TestNewArtist(t *testing.T) {
	hserv := setupTest(t)
	defer hserv.Close()
	//
	// Create a new artist
	//
	_, err := newArtist(hserv)
	if err != nil {
		t.Fatal(err)
	}
	//
	// Confirm DB record
	//
	query := "SELECT COUNT(*) FROM artist WHERE email=$1"
	cnt, err := dbmap.SelectInt(query, ggEmail)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, int64(1), cnt, "One and only one artist with this email.")
	//
	// Create with invalid request
	//
	rr := restclient.RequestResponse{
		Url:            hserv.URL + "/api/v1/artists",
		Method:         "POST",
		Data:           "foobar",
		ExpectedStatus: 400,
	}
	_, err = restclient.Do(&rr)
	if err != nil {
		t.Fatal(err)
	}
	//
	// Try to use duplicate email
	//
}
Ejemplo n.º 6
0
func main() {
	//
	// Prompt user for Github username/password
	//
	var username string
	fmt.Printf("Github username: "******"%s", &username)
	if err != nil {
		log.Fatal(err)
	}
	passwd, err := gopass.GetPass("Github password: "******"scopes"`
		Note   string   `json:"note"`
	}{
		Scopes: []string{"public_repo"},
		Note:   "testing Go restclient",
	}
	//
	// Struct to hold response data
	//
	res := struct {
		Id        int
		Url       string
		Scopes    []string
		Token     string
		App       map[string]string
		Note      string
		NoteUrl   string `json:"note_url"`
		UpdatedAt string `json:"updated_at"`
		CreatedAt string `json:"created_at"`
	}{}
	//
	// Struct to hold error response
	//
	e := struct {
		Message string
	}{}
	//
	// Setup HTTP Basic auth (ONLY use this with SSL)
	//
	u := url.UserPassword(username, passwd)
	rr := restclient.RequestResponse{
		Url:      "https://api.github.com/authorizations",
		Userinfo: u,
		Method:   "POST",
		Data:     &d,
		Result:   &res,
		Error:    &e,
	}
	//
	// Send request to server
	//
	status, err := restclient.Do(&rr)
	if err != nil {
		log.Fatal(err)
	}
	//
	// Process response
	//
	println("")
	if status == 201 {
		fmt.Printf("Github auth token: %s\n\n", res.Token)
	} else {
		fmt.Println("Bad response status from Github server")
		fmt.Printf("\t Status:  %v\n", status)
		fmt.Printf("\t Message: %v\n", e.Message)
	}
	println("")
}
Ejemplo n.º 7
0
func TestNewPatron(t *testing.T) {
	hserv := setupTest(t)
	defer hserv.Close()
	//
	// Create a new artist
	//
	a, _ := newArtist(hserv)
	//
	// Create new patron
	//
	payload := PatronageRequest{
		Email: "*****@*****.**",
		Zip:   "94102",
	}
	p := Patron{}
	url := hserv.URL + "/api/v1/artists/" + strconv.Itoa(int(a.Id)) + "/patrons"
	rr := restclient.RequestResponse{
		Url:            url,
		Method:         "POST",
		Data:           payload,
		Result:         &p,
		ExpectedStatus: 200,
	}
	_, err := restclient.Do(&rr)
	if err != nil {
		t.Fatal(err)
	}
	//
	// Invalid payload
	//
	rr = restclient.RequestResponse{
		Url:            url,
		Method:         "POST",
		Data:           "foobar",
		Result:         &p,
		ExpectedStatus: 400,
	}
	_, err = restclient.Do(&rr)
	if err != nil {
		t.Fatal(err)
	}
	//
	// Invalid artist id
	//
	rr = restclient.RequestResponse{
		Url:            hserv.URL + "/api/v1/artists/foobar/patrons",
		Method:         "POST",
		Data:           payload,
		Result:         &p,
		ExpectedStatus: 400,
	}
	_, err = restclient.Do(&rr)
	if err != nil {
		t.Fatal(err)
	}
	//
	// Bad zip code
	//
	payload.Zip = "foobar"
	rr = restclient.RequestResponse{
		Url:            url,
		Method:         "POST",
		Data:           payload,
		Result:         &p,
		ExpectedStatus: 400,
	}
	_, err = restclient.Do(&rr)
	if err != nil {
		t.Fatal(err)
	}
}
Ejemplo n.º 8
0
func doTestRequireScope(p *Provider, t *testing.T) {
	h := p.RequireScope(fooHandler, "enterprise")
	hserv := httptest.NewServer(h)
	defer hserv.Close()
	//
	// Valid Scope
	//
	username := "******"
	scopes := []string{"enterprise", "shuttlecraft"}
	note := "foo bar baz"
	auth, _ := p.NewAuthz(username, note, scopes)
	header := make(http.Header)
	header.Add("Authorization", "Bearer "+auth.Token)
	rr := restclient.RequestResponse{
		Url:    hserv.URL,
		Method: "GET",
		Header: &header,
	}
	status, err := restclient.Do(&rr)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, 200, status)
	//
	// No Token
	//
	rr = restclient.RequestResponse{
		Url:    hserv.URL,
		Method: "GET",
	}
	status, err = restclient.Do(&rr)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, 401, status)
	//
	// Bad Header
	//
	header = make(http.Header)
	header.Add("Authorization", "foobar")
	rr = restclient.RequestResponse{
		Url:    hserv.URL,
		Method: "GET",
		Header: &header,
	}
	status, err = restclient.Do(&rr)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, 401, status)
	//
	// Unauthorized Scope
	//
	h1 := p.RequireScope(fooHandler, "foobar") // Not among the authorized scopes
	hserv1 := httptest.NewServer(h1)
	defer hserv1.Close()
	header = make(http.Header)
	header.Add("Authorization", "Bearer "+auth.Token)
	rr = restclient.RequestResponse{
		Url:    hserv1.URL,
		Method: "GET",
		Header: &header,
	}
	status, err = restclient.Do(&rr)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, 401, status)
}