Compare commits

...
2 Commits
5 changed files with 96 additions and 46 deletions

No files matched your search

+15 -11
View File
@@ -175,21 +175,25 @@ func FormValues(r *http.Request, params interface{}, validationRules []*v.FieldR
structValue := ref.Elem()
fields := map[string]bool{}
for i := 0; i < structType.NumField(); i++ {
name := structType.Field(i).Name
underscoredName := util.Underscore(name)
value := strings.TrimSpace(r.FormValue(underscoredName))
fieldName := structType.Field(i).Name
formattedName := util.Underscore(fieldName)
jsonName, ok := structType.Field(i).Tag.Lookup("json")
if ok {
formattedName = jsonName
}
value := strings.TrimSpace(r.FormValue(formattedName))
// if param is not set at all, continue
// comes after call to r.FormValue so form values get parsed internally (if they arent already)
if len(r.Form[underscoredName]) == 0 {
if len(r.Form[formattedName]) == 0 {
continue
}
fields[underscoredName] = true
fields[formattedName] = true
isPtr := false
var finalValue reflect.Value
structField := structValue.FieldByName(name)
structField := structValue.FieldByName(fieldName)
structFieldKind := structField.Kind()
if structFieldKind == reflect.Ptr {
isPtr = true
@@ -205,7 +209,7 @@ func FormValues(r *http.Request, params interface{}, validationRules []*v.FieldR
}
castVal, err := cast.ToInt64E(value)
if err != nil {
return errors.Err("%s: must be an integer", underscoredName)
return errors.Err("%s: must be an integer", formattedName)
}
switch structFieldKind {
case reflect.Int:
@@ -225,7 +229,7 @@ func FormValues(r *http.Request, params interface{}, validationRules []*v.FieldR
}
castVal, err := cast.ToUint64E(value)
if err != nil {
return errors.Err("%s: must be an unsigned integer", underscoredName)
return errors.Err("%s: must be an unsigned integer", formattedName)
}
switch structFieldKind {
case reflect.Uint:
@@ -245,7 +249,7 @@ func FormValues(r *http.Request, params interface{}, validationRules []*v.FieldR
}
if !validator.IsBoolString(value) {
return errors.Err("%s: must be one of the following values: %s",
underscoredName, strings.Join(validator.GetBoolStringValues(), ", "))
formattedName, strings.Join(validator.GetBoolStringValues(), ", "))
}
finalValue = reflect.ValueOf(validator.IsTruthy(value))
@@ -255,7 +259,7 @@ func FormValues(r *http.Request, params interface{}, validationRules []*v.FieldR
}
castVal, err := cast.ToFloat64E(value)
if err != nil {
return errors.Err("%s: must be a floating point number", underscoredName)
return errors.Err("%s: must be a floating point number", formattedName)
}
switch structFieldKind {
case reflect.Float32:
@@ -264,7 +268,7 @@ func FormValues(r *http.Request, params interface{}, validationRules []*v.FieldR
finalValue = reflect.ValueOf(float64(castVal))
}
default:
return errors.Err("field %s is an unsupported type", name)
return errors.Err("field %s is an unsupported type", fieldName)
}
if isPtr {
+12 -3
View File
@@ -18,8 +18,9 @@ const (
timeout = 5 * time.Second
headerForwardedFor = "X-Forwarded-For"
userObjectPath = "user"
userMeMethod = "me"
userObjectPath = "user"
userMeMethod = "me"
userHasVerifiedEmailMethod = "has_verified_email"
)
// Client stores data about internal-apis call it is about to make.
@@ -48,6 +49,10 @@ type APIResponse struct {
// ResponseData is a map containing parsed json response.
type ResponseData map[string]interface{}
func makeMethodPath(obj, method string) string {
return fmt.Sprintf("/%s/%s", obj, method)
}
// NewClient returns a client instance for internal-apis. It requires authToken to be provided
// for authentication.
func NewClient(authToken string, opts *ClientOpts) Client {
@@ -70,7 +75,7 @@ func NewClient(authToken string, opts *ClientOpts) Client {
}
func (c Client) getEndpointURL(object, method string) string {
return fmt.Sprintf("%s/%s/%s", c.serverAddress, object, method)
return fmt.Sprintf("%s%s", c.serverAddress, makeMethodPath(object, method))
}
func (c Client) prepareParams(params map[string]interface{}) (string, error) {
@@ -137,3 +142,7 @@ func (c Client) Call(object, method string, params map[string]interface{}) (Resp
func (c Client) UserMe() (ResponseData, error) {
return c.Call(userObjectPath, userMeMethod, map[string]interface{}{})
}
func (c Client) UserHasVerifiedEmail() (ResponseData, error) {
return c.Call(userObjectPath, userHasVerifiedEmailMethod, map[string]interface{}{})
}
+67 -31
View File
@@ -1,6 +1,7 @@
package lbryinc
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
@@ -17,53 +18,54 @@ func TestUserMeWrongToken(t *testing.T) {
assert.Nil(t, r)
}
func launchDummyServer(lastReq **http.Request) *httptest.Server {
func TestUserHasVerifiedEmailWrongToken(t *testing.T) {
c := NewClient("abc", nil)
r, err := c.UserHasVerifiedEmail()
require.NotNil(t, err)
assert.Equal(t, "could not authenticate user", err.Error())
assert.Nil(t, r)
}
func launchDummyServer(lastReq **http.Request, path, response string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*lastReq = &*r
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
response := []byte(`{
"success": true,
"error": null,
"data": {
"id": 751365,
"language": "en",
"given_name": null,
"family_name": null,
"created_at": "2019-01-17T12:13:06Z",
"updated_at": "2019-05-02T13:57:59Z",
"invited_by_id": null,
"invited_at": null,
"invites_remaining": 0,
"invite_reward_claimed": false,
"is_email_enabled": true,
"manual_approval_user_id": 837139,
"reward_status_change_trigger": "manual",
"primary_email": "andrey@lbry.com",
"has_verified_email": true,
"is_identity_verified": false,
"is_reward_approved": true,
"groups": []
}
}`)
w.Write(response)
if r.URL.Path != path {
fmt.Printf("path doesn't match: %v != %v", r.URL.Path, path)
w.WriteHeader(http.StatusNotFound)
} else {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(response))
}
}))
}
func TestUserMe(t *testing.T) {
var req *http.Request
ts := launchDummyServer(&req)
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userMeMethod), userMeResponse)
defer ts.Close()
c := NewClient("realToken", &ClientOpts{ServerAddress: ts.URL})
r, err := c.UserMe()
assert.Nil(t, err)
assert.Equal(t, r["primary_email"], "andrey@lbry.com")
assert.Equal(t, "user@lbry.tv", r["primary_email"])
}
func TestUserHasVerifiedEmail(t *testing.T) {
var req *http.Request
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userHasVerifiedEmailMethod), userHasVerifiedEmailResponse)
defer ts.Close()
c := NewClient("realToken", &ClientOpts{ServerAddress: ts.URL})
r, err := c.UserHasVerifiedEmail()
assert.Nil(t, err)
assert.EqualValues(t, 12345, r["user_id"])
assert.Equal(t, true, r["has_verified_email"])
}
func TestRemoteIP(t *testing.T) {
var req *http.Request
ts := launchDummyServer(&req)
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userMeMethod), userMeResponse)
defer ts.Close()
c := NewClient("realToken", &ClientOpts{ServerAddress: ts.URL, RemoteIP: "8.8.8.8"})
@@ -71,3 +73,37 @@ func TestRemoteIP(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, []string{"8.8.8.8"}, req.Header["X-Forwarded-For"])
}
const userMeResponse = `{
"success": true,
"error": null,
"data": {
"id": 12345,
"language": "en",
"given_name": null,
"family_name": null,
"created_at": "2019-01-17T12:13:06Z",
"updated_at": "2019-05-02T13:57:59Z",
"invited_by_id": null,
"invited_at": null,
"invites_remaining": 0,
"invite_reward_claimed": false,
"is_email_enabled": true,
"manual_approval_user_id": 654,
"reward_status_change_trigger": "manual",
"primary_email": "user@lbry.tv",
"has_verified_email": true,
"is_identity_verified": false,
"is_reward_approved": true,
"groups": []
}
}`
const userHasVerifiedEmailResponse = `{
"success": true,
"error": null,
"data": {
"user_id": 12345,
"has_verified_email": true
}
}`
+1 -1
View File
@@ -17,7 +17,7 @@ require (
github.com/gorilla/websocket v1.4.1 // indirect
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
github.com/kr/pretty v0.1.0 // indirect
github.com/lbryio/lbry.go v1.1.2 // indirect
github.com/lbryio/lbry.go v1.1.2
github.com/lbryio/lbryschema.go v0.0.0-20190602173230-6d2f69a36f46
github.com/lbryio/ozzo-validation v0.0.0-20170323141101-d1008ad1fd04
github.com/lbryio/types v0.0.0-20191009145016-1bb8107e04f8
+1
View File
@@ -193,6 +193,7 @@ golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=