func (p *JSONMediaTypeInputHandler) OutputTo(req wm.Request, cxt wm.Context, writer io.Writer) (int, http.Header, os.Error) { defer func() { if p.reader != nil { if closer, ok := p.reader.(io.Closer); ok { closer.Close() } } }() //log.Printf("[JSONMTIH]: Calling OutputTo with reader %v\n", p.reader) if p.reader == nil { return p.handler.HandleJSONObjectInputHandler(req, cxt, writer, nil) } obj := jsonhelper.NewJSONObject() dec := json.NewDecoder(p.reader) err := dec.Decode(&obj) if err != nil { headers := make(http.Header) //headers.Set("Content-Type", wm.MIME_TYPE_JSON) m := jsonhelper.NewJSONObject() w := json.NewEncoder(writer) m.Set("status", "error") m.Set("message", err.String()) m.Set("result", nil) w.Encode(m) return 500, headers, err } return p.handler.HandleJSONObjectInputHandler(req, cxt, writer, obj) }
func (p *JSONMediaTypeHandler) OutputTo(req wm.Request, cxt wm.Context, writer io.Writer, resp wm.ResponseWriter) { buf := bytes.NewBufferString("") obj := jsonhelper.NewJSONObject() enc := json.NewEncoder(buf) obj.Set("status", "success") obj.Set("result", p.obj) err := enc.Encode(obj) if err != nil { //resp.Header().Set("Content-Type", wm.MIME_TYPE_JSON) if !p.writtenStatusHeader { resp.WriteHeader(500) p.writtenStatusHeader = true } m := jsonhelper.NewJSONObject() w := json.NewEncoder(writer) m.Set("status", "error") m.Set("message", err.String()) m.Set("result", nil) w.Encode(m) return } //resp.Header().Set("Content-Type", wm.MIME_TYPE_JSON) resp.Header().Set("Content-Length", strconv.Itoa(buf.Len())) if p.lastModified != nil { resp.Header().Set("Last-Modified", p.lastModified.Format(http.TimeFormat)) } if len(p.etag) > 0 { resp.Header().Set("ETag", strconv.Quote(p.etag)) } handler := wm.NewPassThroughMediaTypeHandler(wm.MIME_TYPE_JSON, ioutil.NopCloser(bytes.NewBuffer(buf.Bytes())), int64(buf.Len()), p.lastModified) handler.OutputTo(req, cxt, writer, resp) }
func TestAuthSetPasswordAdmin(t *testing.T) { ds, wm := initializeAuthUserAccountDS() user, _ := ds.FindUserAccountByUsername("firstpresident") accessKeys, _, _ := ds.RetrieveUserKeys(user.Id, nil, 1000) if len(accessKeys) != 1 { t.Error("Expected to find 1 access key stored, but found", len(accessKeys)) } accessKey := accessKeys[0] jsonobj := jsonhelper.NewJSONObject() jsonobj.Set("password", "hi ho hi ho") jsonbuf, _ := json.Marshal(jsonobj) req, _ := http.NewRequest(webmachine.POST, "http://localhost/api/v1/json/auth/set_password/", bytes.NewBuffer(jsonbuf)) req.Header.Set("Accept", webmachine.MIME_TYPE_JSON+"; charset=utf-8") req.Header.Set("Accept-Charset", "utf-8") req.Header.Set("Accept-Encoding", "identity") req.Header.Set("Accept-Language", "en-us") req.Header.Set("Connection", "close") apiutil.NewSigner(accessKey.Id, accessKey.PrivateKey).SignRequest(req, 0) reqbytes, _ := httputil.DumpRequest(req, true) t.Log("Request is:\n", string(reqbytes), "\n\n") resp := webmachine.NewMockResponseWriter(req) wm.ServeHTTP(resp, req) t.Log("Response is:\n", resp.String(), "\n\n") if resp.StatusCode != http.StatusOK { t.Error("Expected ", http.StatusOK, " status code but received ", resp.StatusCode) } if resp.Header().Get("Content-Type") != req.Header.Get("Accept") { t.Error("Expected Content-Type \"", req.Header.Get("Accept"), "\" but received ", resp.Header().Get("Content-Type")) } obj := jsonhelper.NewJSONObject() err := json.Unmarshal(resp.Buffer.Bytes(), &obj) if err != nil { t.Error("Unable to unmarshal setPassword response due to error:", err.Error()) } if status := obj.GetAsString("status"); status != "success" { t.Error("Expected successful operation, but had status:", status) } result := obj.GetAsObject("result") if message := result.GetAsString("message"); message != "password changed" { t.Error("Expected message == \"password changed\", but was \"", message, "\"") } user2 := result.GetAsObject("user") uid := user2.GetAsString("id") if uid != user.Id { t.Error("Expected user id of", user.Id, ", but was", uid) } accessKeys2, _, _ := ds.RetrieveUserKeys(user.Id, nil, 1000) if len(accessKeys2) != 1 { t.Error("Expected to find one access key stored, but found", len(accessKeys)) } }
func (p *JSONMediaTypeHandler) MediaTypeHandleOutputTo(req wm.Request, cxt wm.Context, writer io.Writer, resp wm.ResponseWriter) { var responseHeaders http.Header var responseStatusCode int if p.obj == nil && p.responseGenerator != nil { p.obj, p.lastModified, p.etag, responseStatusCode, responseHeaders = p.responseGenerator() } buf := bytes.NewBufferString("") obj := jsonhelper.NewJSONObject() enc := json.NewEncoder(buf) obj.Set("status", "success") obj.Set("result", p.obj) err := enc.Encode(obj) if err != nil { //resp.Header().Set("Content-Type", wm.MIME_TYPE_JSON) if !p.writtenStatusHeader { resp.WriteHeader(500) p.writtenStatusHeader = true } m := jsonhelper.NewJSONObject() w := json.NewEncoder(writer) m.Set("status", "error") m.Set("message", err.Error()) m.Set("result", nil) w.Encode(m) return } if responseHeaders != nil { for k, arr := range responseHeaders { if _, ok := resp.Header()[k]; ok { if len(arr) > 0 { resp.Header().Set(k, arr[len(arr)-1]) } } else { for _, v := range arr { resp.Header().Add(k, v) } } } } //resp.Header().Set("Content-Type", wm.MIME_TYPE_JSON) resp.Header().Set("Content-Length", strconv.Itoa(buf.Len())) if !p.lastModified.IsZero() { resp.Header().Set("Last-Modified", p.lastModified.Format(http.TimeFormat)) } if len(p.etag) > 0 { resp.Header().Set("ETag", strconv.Quote(p.etag)) } handler := wm.NewPassThroughMediaTypeHandler(wm.MIME_TYPE_JSON, ioutil.NopCloser(bytes.NewBuffer(buf.Bytes())), int64(buf.Len()), p.lastModified) handler.SetStatusCode(responseStatusCode) handler.MediaTypeHandleOutputTo(req, cxt, writer, resp) }
func TestAuthLoginNoPassword(t *testing.T) { ds, wm := initializeAuthUserAccountDS() user, _ := ds.FindUserAccountByUsername("firstpresident") accessKeys, _, _ := ds.RetrieveUserKeys(user.Id, nil, 1000) if len(accessKeys) == 0 { t.Error("Expected to find at least one access key stored.") } jsonobj := jsonhelper.NewJSONObject() jsonobj.Set("username", user.Username) jsonbuf, _ := json.Marshal(jsonobj) req, _ := http.NewRequest(webmachine.POST, "http://localhost/api/v1/json/auth/login/", bytes.NewBuffer(jsonbuf)) req.Header.Set("Content-Type", webmachine.MIME_TYPE_JSON+"; charset=utf-8") req.Header.Set("Accept", webmachine.MIME_TYPE_JSON+"; charset=utf-8") req.Header.Set("Accept-Charset", "utf-8") req.Header.Set("Accept-Encoding", "identity") req.Header.Set("Accept-Language", "en-us") req.Header.Set("Connection", "close") reqbytes, _ := httputil.DumpRequest(req, true) t.Log("Request is:\n", string(reqbytes), "\n\n") resp := webmachine.NewMockResponseWriter(req) wm.ServeHTTP(resp, req) t.Log("Response is:\n", resp.String(), "\n\n") if resp.StatusCode != http.StatusUnauthorized { t.Error("Expected ", http.StatusUnauthorized, " status code but received ", resp.StatusCode) } if resp.Header().Get("Content-Type") != req.Header.Get("Accept") { t.Error("Expected Content-Type \"", req.Header.Get("Accept"), "\" but received ", resp.Header().Get("Content-Type")) } obj := jsonhelper.NewJSONObject() err := json.Unmarshal(resp.Buffer.Bytes(), &obj) if err != nil { t.Error("Unable to unmarshal login response due to error:", err.Error()) } if status := obj.GetAsString("status"); status != "error" { t.Error("Expected error operation, but had status:", status) } result := obj.GetAsObject("result") if result.Len() != 1 { t.Error("Expected a result object with 1 entry, but has", result.Len(), "entries as:", result) } if password := result.GetAsArray("password"); len(password) != 1 || password[0] != auth.ERR_MUST_SPECIFY_PASSWORD.Error() { t.Error("Expected one error for missing password, but was", result) } if message := obj.GetAsString("message"); message != auth.ERR_VALUE_ERRORS.Error() { t.Error("Expected ERR_VALUE_ERRORS for message, but was", message) } if accessKeys2, _, _ := ds.RetrieveUserKeys(user.Id, nil, 1000); len(accessKeys2) != 1 { t.Error("Expected 1 access key after logging in, but found", len(accessKeys2)) } }
func (p *googleplusClient) GenerateRequestTokenUrl(properties jsonhelper.JSONObject) string { if properties == nil { properties = jsonhelper.NewJSONObject() } m := make(url.Values) m.Add("response_type", "code") if v, ok := properties["client_id"]; ok && len(v.(string)) > 0 { m.Add("client_id", v.(string)) } else { m.Add("client_id", p.clientId) } if v, ok := properties["redirect_uri"]; ok { if len(v.(string)) > 0 { m.Add("redirect_uri", v.(string)) } } else if len(p.redirectUri) > 0 { m.Add("redirect_uri", p.redirectUri) } if v, ok := properties["scope"]; ok { if len(v.(string)) > 0 { m.Add("scope", v.(string)) } } else if len(p.scope) > 0 { m.Add("scope", p.scope) } if v, ok := properties["state"]; ok { if len(v.(string)) > 0 { m.Add("state", v.(string)) } } else if len(p.state) > 0 { m.Add("state", p.state) } return MakeUrl(_GOOGLEPLUS_ACCESS_TOKEN_URL, m) }
func (p *LoginAccountRequestHandler) HandleInputHandlerAfterSetup(lac LoginAccountContext) (int, http.Header, io.WriterTo) { errors := make(map[string][]error) user, err := lac.ValidateLogin(p.ds, p.authDS, errors) if len(errors) > 0 { if err != nil { return apiutil.OutputErrorMessage(err.Error(), errors, http.StatusBadRequest, nil) } return apiutil.OutputErrorMessage(ERR_VALUE_ERRORS.Error(), errors, http.StatusUnauthorized, nil) } if err == ERR_INVALID_USERNAME_PASSWORD_COMBO { return apiutil.OutputErrorMessage(err.Error(), nil, http.StatusUnauthorized, nil) } if err != nil { return apiutil.OutputErrorMessage("Unable to process login request: ", nil, http.StatusInternalServerError, nil) } if user == nil { return apiutil.OutputErrorMessage("Unable to process login request: no such username", nil, http.StatusUnauthorized, nil) } accessKey, err := p.authDS.StoreAccessKey(dm.NewAccessKey(user.Id, "")) if err != nil { return apiutil.OutputErrorMessage("Unable to process login request: "+err.Error(), nil, http.StatusInternalServerError, nil) } obj := jsonhelper.NewJSONObject() obj.Set("user_id", user.Id) obj.Set("username", user.Username) obj.Set("name", user.Name) obj.Set("access_key_id", accessKey.Id) obj.Set("private_key", accessKey.PrivateKey) lac.SetResult(obj) return 0, nil, nil }
func (p *facebookLocation) UnmarshalJSON(data []byte) error { props := jsonhelper.NewJSONObject() err := json.Unmarshal(data, &props) p.id = props.GetAsString("id") p.name = props.GetAsString("name") return err }
func (p *SetPasswordRequestHandler) HandleInputHandlerAfterSetup(cxt SetPasswordContext) (int, http.Header, io.WriterTo) { errors := make(map[string][]error) var obj jsonhelper.JSONObject var err error authDS := p.authDS if user := cxt.User(); user != nil { var userPassword *dm.UserPassword if user != nil { userPassword = dm.NewUserPassword(user.Id, cxt.Password()) } else { userPassword = dm.NewUserPassword("", cxt.Password()) } userPassword.Validate(true, errors) if len(errors) == 0 { userPassword, err = authDS.StoreUserPassword(userPassword) } obj = jsonhelper.NewJSONObject() userObj, _ := jsonhelper.Marshal(user) obj.Set("user", userObj) obj.Set("type", "user") obj.Set("message", "password changed") } else { return apiutil.OutputErrorMessage(ERR_MUST_SPECIFY_USERNAME.Error(), time.Time{}, http.StatusBadRequest, nil) } if len(errors) > 0 { return apiutil.OutputErrorMessage("Value errors. See result", errors, http.StatusBadRequest, nil) } if err != nil { return apiutil.OutputErrorMessage(err.Error(), time.Time{}, http.StatusInternalServerError, nil) } cxt.SetResult(obj) return 0, nil, nil }
func (p *facebookClient) ReadAccessToken(body string, now time.Time) error { params, err := url.ParseQuery(body) if err != nil { s := jsonhelper.NewJSONObject() if err2 := json.Unmarshal([]byte(body), &s); err2 != nil { LogError("Unable to read error response: ", body) return err2 } return errors.New(fmt.Sprintf("%v", s)) } if params == nil { params = make(url.Values) } t := &facebookAccessTokenResult{accessToken: params.Get("access_token")} if len(params.Get("expires")) > 0 { expiresIn, _ := strconv.ParseInt(params.Get("expires"), 10, 64) if expiresIn >= 0 { t.expiresAt = time.Unix(now.Unix()+expiresIn, 0).UTC() } } if len(t.accessToken) > 0 { p.expiresAt = t.expiresAt p.accessToken = t.accessToken } return nil }
func (p *ViewContactRequestHandler) HandleInputHandlerAfterSetup(cxt ViewContactContext) (int, http.Header, io.WriterTo) { obj := jsonhelper.NewJSONObject() contactObj, _ := jsonhelper.Marshal(cxt.Contact()) obj.Set("contact", contactObj) obj.Set("type", "contact") cxt.SetResult(obj) return 0, nil, nil }
func TestCreateUserAccount(t *testing.T) { ds := inmemory.NewInMemoryDataStore() wm := webmachine.NewWebMachine() wm.AddRouteHandler(account.NewCreateAccountRequestHandler(ds, ds)) buf := bytes.NewBufferString(`{"role": 9999999999999999, "name": "George Washington", "username": "******", "email":"*****@*****.**", "phone_number": "+1-405-555-5555", "address": "Valley Forge"}`) oldUser := new(dm.User) json.Unmarshal(buf.Bytes(), &oldUser) req, _ := http.NewRequest(webmachine.POST, "http://localhost/api/v1/json/account/user/create/", buf) req.Header.Set("Content-Type", webmachine.MIME_TYPE_JSON+"; charset=utf-8") req.Header.Set("Accept", webmachine.MIME_TYPE_JSON+"; charset=utf-8") req.Header.Set("Accept-Charset", "utf-8") req.Header.Set("Accept-Encoding", "identity") req.Header.Set("Accept-Language", "en-us") req.Header.Set("Connection", "close") resp := webmachine.NewMockResponseWriter(req) reqb, _ := httputil.DumpRequest(req, true) wm.ServeHTTP(resp, req) if resp.StatusCode != 200 { t.Error("Expected 200 status code but received ", resp.StatusCode) } if resp.Header().Get("Content-Type") != req.Header.Get("Accept") { t.Error("Expected Content-Type \"", req.Header.Get("Accept"), "\" but received ", resp.Header().Get("Content-Type")) } user := new(dm.User) obj := jsonhelper.NewJSONObject() err := json.Unmarshal(resp.Buffer.Bytes(), &obj) user.InitFromJSONObject(obj.GetAsObject("result").GetAsObject("user")) if err != nil { t.Error("Error while unmarshaling JSON: ", err.Error()) } if obj.GetAsString("status") != "success" { t.Error("Expected status = \"success\", but was \"", obj.GetAsString("status"), "\"") } if user.Name != oldUser.Name { t.Logf("Request was\n%s\n================\n", string(reqb)) t.Log("Response is:\n", resp.String(), "\n\n") t.Error("Expected name = \"", oldUser.Name, "\", but was ", user.Name) } if user.Username != oldUser.Username { t.Error("Expected username = \"", oldUser.Username, "\", but was ", user.Username) } if user.Email != oldUser.Email { t.Error("Expected email = \"", oldUser.Email, "\", but was ", user.Email) } if user.PhoneNumber != oldUser.PhoneNumber { t.Error("Expected phone_number = \"", oldUser.PhoneNumber, "\", but was ", user.PhoneNumber) } if user.Address != oldUser.Address { t.Error("Expected address = \"", oldUser.Address, "\", but was ", user.Address) } if user.Role != dm.ROLE_STANDARD { t.Error("Expected role = ", dm.ROLE_STANDARD, " but was ", user.Role) } if user.Id == "" { t.Error("Expected id to be populated, but was empty") } }
func HandleGenericOauthRequest(c oauth2_client.OAuth2Client, w http.ResponseWriter, req *http.Request) { uri := c.GenerateRequestTokenUrl(jsonhelper.NewJSONObject()) if len(uri) > 0 { w.Header().Set("Location", uri) w.WriteHeader(302) } else { w.WriteHeader(500) } }
func TestAuthLoginNoUsername(t *testing.T) { _, wm := initializeAuthUserAccountDS() jsonobj := jsonhelper.NewJSONObject() jsonobj.Set("password", "number two") jsonbuf, _ := json.Marshal(jsonobj) req, _ := http.NewRequest(webmachine.POST, "http://localhost/api/v1/json/auth/login/", bytes.NewBuffer(jsonbuf)) req.Header.Set("Content-Type", webmachine.MIME_TYPE_JSON+"; charset=utf-8") req.Header.Set("Accept", webmachine.MIME_TYPE_JSON+"; charset=utf-8") req.Header.Set("Accept-Charset", "utf-8") req.Header.Set("Accept-Encoding", "identity") req.Header.Set("Accept-Language", "en-us") req.Header.Set("Connection", "close") reqbytes, _ := httputil.DumpRequest(req, true) t.Log("Request is:\n", string(reqbytes), "\n\n") resp := webmachine.NewMockResponseWriter(req) wm.ServeHTTP(resp, req) t.Log("Response is:\n", resp.String(), "\n\n") if resp.StatusCode != http.StatusUnauthorized { t.Error("Expected ", http.StatusUnauthorized, " status code but received ", resp.StatusCode) } if resp.Header().Get("Content-Type") != req.Header.Get("Accept") { t.Error("Expected Content-Type \"", req.Header.Get("Accept"), "\" but received ", resp.Header().Get("Content-Type")) } obj := jsonhelper.NewJSONObject() err := json.Unmarshal(resp.Buffer.Bytes(), &obj) if err != nil { t.Error("Unable to unmarshal login response due to error:", err.Error()) } if status := obj.GetAsString("status"); status != "error" { t.Error("Expected error operation, but had status:", status) } result := obj.GetAsObject("result") if result.Len() != 1 { t.Error("Expected a result object with 1 entry, but has", result.Len(), "entries as:", result) } if username := result.GetAsArray("username"); len(username) != 1 || username[0] != auth.ERR_MUST_SPECIFY_USERNAME.Error() { t.Error("Expected one error for missing username, but was", result) } if message := obj.GetAsString("message"); message != auth.ERR_VALUE_ERRORS.Error() { t.Error("Expected ERR_VALUE_ERRORS for message, but was", message) } }
func HandleInitialClientRedirect(w http.ResponseWriter, req *http.Request) { client := oauth2_client.NewGoogleClient() client.Initialize(settings) tokenUrl := client.GenerateRequestTokenUrl(jsonhelper.NewJSONObject()) if len(tokenUrl) > 0 { w.Header().Set("Location", tokenUrl) w.WriteHeader(302) } else { w.WriteHeader(500) } }
func oauth1GenerateRequestTokenUrl(p OAuth1Client, properties jsonhelper.JSONObject) string { if properties == nil { properties = jsonhelper.NewJSONObject() } cred, err := getAuthToken(p) LogDebugf("Received credentials: %T -> %v", cred, cred) LogDebug("Received err: ", err) if cred == nil || err != nil { return "" } return oauth1GenerateAuthorizationUrl(p, cred) }
func TestAuthLoginAccountDoesNotExist(t *testing.T) { _, wm := initializeAuthUserAccountDS() jsonobj := jsonhelper.NewJSONObject() jsonobj.Set("username", "dudewhatever") jsonobj.Set("password", "blah blah") jsonbuf, _ := json.Marshal(jsonobj) req, _ := http.NewRequest(webmachine.POST, "http://localhost/api/v1/json/auth/login/", bytes.NewBuffer(jsonbuf)) req.Header.Set("Content-Type", webmachine.MIME_TYPE_JSON+"; charset=utf-8") req.Header.Set("Accept", webmachine.MIME_TYPE_JSON+"; charset=utf-8") req.Header.Set("Accept-Charset", "utf-8") req.Header.Set("Accept-Encoding", "identity") req.Header.Set("Accept-Language", "en-us") req.Header.Set("Connection", "close") reqbytes, _ := httputil.DumpRequest(req, true) t.Log("Request is:\n", string(reqbytes), "\n\n") resp := webmachine.NewMockResponseWriter(req) wm.ServeHTTP(resp, req) t.Log("Response is:\n", resp.String(), "\n\n") if resp.StatusCode != http.StatusUnauthorized { t.Error("Expected ", http.StatusUnauthorized, " status code but received ", resp.StatusCode) } if resp.Header().Get("Content-Type") != req.Header.Get("Accept") { t.Error("Expected Content-Type \"", req.Header.Get("Accept"), "\" but received ", resp.Header().Get("Content-Type")) } obj := jsonhelper.NewJSONObject() err := json.Unmarshal(resp.Buffer.Bytes(), &obj) if err != nil { t.Error("Unable to unmarshal login response due to error:", err.Error()) } if status := obj.GetAsString("status"); status != "error" { t.Error("Expected error operation, but had status:", status) } if result := obj.Get("result"); result != nil { t.Error("Expected result to be nil, but was", result) } if message := obj.GetAsString("message"); message != auth.ERR_INVALID_USERNAME_PASSWORD_COMBO.Error() { t.Error("Expected ERR_INVALID_USERNAME_PASSWORD_COMBO for message, but was", message) } }
func OutputErrorMessage(message string, result interface{}, statusCode int, headers http.Header) (int, http.Header, io.WriterTo) { if statusCode == 0 { statusCode = http.StatusInternalServerError } if headers == nil { headers = make(http.Header) } //headers.Set("Content-Type", wm.MIME_TYPE_JSON) m := jsonhelper.NewJSONObject() m.Set("status", "error") m.Set("message", message) m.Set("result", result) return statusCode, headers, newJSONWriter(m) }
func (p *yahooClient) RetrieveUserInfo() (UserInfo, error) { req, err := p.CreateAuthorizedRequest(_YAHOO_USERINFO_METHOD, nil, _YAHOO_USERINFO_URL, nil, nil) if err != nil { return nil, err } result := new(yahooUserInfoResult) resp, _, err := MakeRequest(p, req) if resp != nil && resp.Body != nil { props := jsonhelper.NewJSONObject() if err2 := json.NewDecoder(resp.Body).Decode(&props); err == nil { err = err2 } result.FromJSON(props.GetAsObject("profile")) } return result, err }
func (p *smugMugClient) RetrieveUserInfo() (UserInfo, error) { req, err := p.CreateAuthorizedRequest(_SMUGMUG_USERINFO_METHOD, nil, _SMUGMUG_USERINFO_URL, nil, nil) if err != nil { return nil, err } result := NewSmugMugUserInfoResult() resp, _, err := MakeRequest(p, req) if resp != nil && resp.Body != nil { props := jsonhelper.NewJSONObject() if err2 := json.NewDecoder(resp.Body).Decode(&props); err == nil { err = err2 } result.FromJSON(props.GetAsObject("Auth").GetAsObject("User")) } return result, err }
func OutputErrorMessage(writer io.Writer, message string, result interface{}, statusCode int, headers http.Header) (int, http.Header, os.Error) { if statusCode == 0 { statusCode = 500 } if headers == nil { headers = make(http.Header) } //headers.Set("Content-Type", wm.MIME_TYPE_JSON) m := jsonhelper.NewJSONObject() w := json.NewEncoder(writer) m.Set("status", "error") m.Set("message", message) m.Set("result", result) w.Encode(m) return statusCode, headers, nil }
func (p *DeleteContactRequestHandler) HandleJSONObjectInputHandler(req wm.Request, cxt wm.Context, inputObj jsonhelper.JSONObject) (int, http.Header, io.WriterTo) { dcc := cxt.(DeleteContactContext) var err error if !dcc.Deleted() { _, req, cxt, _, err = p.DeleteResource(req, cxt) } if err != nil { return apiutil.OutputErrorMessage(err.Error(), nil, http.StatusInternalServerError, nil) } obj := jsonhelper.NewJSONObject() obj.Set("type", "contact") obj.Set("contact", dcc.Contact()) theobj, _ := jsonhelper.MarshalWithOptions(obj, dm.UTC_DATETIME_FORMAT) jsonObj, _ := theobj.(jsonhelper.JSONObject) return apiutil.OutputJSONObject(jsonObj, time.Time{}, "", 0, nil) }
func TestCreateUserAccountMissingSeveralFields(t *testing.T) { ds := inmemory.NewInMemoryDataStore() wm := webmachine.NewWebMachine() wm.AddRouteHandler(account.NewCreateAccountRequestHandler(ds, ds)) buf := bytes.NewBufferString(`{"role": 9999999999999999, "name": " ", "username": "******", "email": "hi ho hi ho", "phone_number": "+1-405-555-5555", "address": "Valley Forge"}`) oldUser := new(dm.User) json.Unmarshal(buf.Bytes(), &oldUser) req, _ := http.NewRequest(webmachine.POST, "http://localhost/api/v1/json/account/user/create/", buf) req.Header.Set("Content-Type", webmachine.MIME_TYPE_JSON+"; charset=utf-8") req.Header.Set("Accept", webmachine.MIME_TYPE_JSON+"; charset=utf-8") req.Header.Set("Accept-Charset", "utf-8") req.Header.Set("Accept-Encoding", "identity") req.Header.Set("Accept-Language", "en-us") req.Header.Set("Connection", "close") resp := webmachine.NewMockResponseWriter(req) wm.ServeHTTP(resp, req) if resp.StatusCode != 400 { t.Error("Expected 400 status code but received ", resp.StatusCode) } if resp.Header().Get("Content-Type") != req.Header.Get("Accept") { t.Error("Expected Content-Type \"", req.Header.Get("Accept"), "\" but received ", resp.Header().Get("Content-Type")) } obj := jsonhelper.NewJSONObject() err := json.Unmarshal(resp.Buffer.Bytes(), &obj) if err != nil { t.Error("Error while unmarshaling JSON: ", err.String()) } if obj.GetAsString("status") != "error" { t.Error("Expected status = \"error\", but was \"", obj.GetAsString("status"), "\"") } result := obj.GetAsObject("result") if result == nil { t.Error("Expected result != nil, but was nil") } else { if result.GetAsArray("name").Len() == 0 { t.Error("Expected an error on attribute \"name\", but was not found") } if result.GetAsArray("username").Len() == 0 { t.Error("Expected an error on attribute \"username\", but was not found") } if result.GetAsArray("email").Len() == 0 { t.Error("Expected an error on attribute \"email\", but was not found") } } }
func (p *facebookUserInfoResult) UnmarshalJSON(data []byte) error { props := jsonhelper.NewJSONObject() err := json.Unmarshal(data, &props) p.id = props.GetAsString("id") p.name = props.GetAsString("name") p.firstName = props.GetAsString("first_name") p.lastName = props.GetAsString("last_name") p.link = props.GetAsString("link") p.username = props.GetAsString("username") p.hometown.FromJSON(props.GetAsObject("hometown")) p.location.FromJSON(props.GetAsObject("location")) p.gender = props.GetAsString("gender") p.email = props.GetAsString("email") p.timezone = props.GetAsFloat64("timezone") p.locale = props.GetAsString("locale") p.verified = props.GetAsBool("verified") p.updatedTime = props.GetAsTime("updated_time", FACEBOOK_DATETIME_FORMAT) return err }
func OutputJSONObject(obj jsonhelper.JSONObject, lastModified time.Time, etag string, statusCode int, headers http.Header) (int, http.Header, io.WriterTo) { if statusCode == 0 { statusCode = http.StatusOK } if headers == nil { headers = make(http.Header) } //headers.Set("Content-Type", wm.MIME_TYPE_JSON) if !lastModified.IsZero() { headers.Set("Last-Modified", lastModified.Format(http.TimeFormat)) } if len(etag) > 0 { headers.Set("ETag", etag) } m := jsonhelper.NewJSONObject() m.Set("status", "success") m.Set("result", obj) return statusCode, headers, newJSONWriter(m) }
func (p *JSONMediaTypeInputHandler) MediaTypeHandleInputFrom(req wm.Request, cxt wm.Context) (int, http.Header, io.WriterTo) { defer func() { if p.reader != nil { if closer, ok := p.reader.(io.Closer); ok { closer.Close() } } }() //log.Printf("[JSONMTIH]: Calling OutputTo with reader %v\n", p.reader) if p.reader == nil { return p.handler.HandleJSONObjectInputHandler(req, cxt, nil) } obj := jsonhelper.NewJSONObject() dec := json.NewDecoder(p.reader) err := dec.Decode(&obj) if err != nil { headers := make(http.Header) return OutputErrorMessage(err.Error(), nil, 500, headers) } return p.handler.HandleJSONObjectInputHandler(req, cxt, obj) }
func OutputJSONObject(writer io.Writer, obj jsonhelper.JSONObject, lastModified *time.Time, etag string, statusCode int, headers http.Header) (int, http.Header, os.Error) { if statusCode == 0 { statusCode = 200 } if headers == nil { headers = make(http.Header) } //headers.Set("Content-Type", wm.MIME_TYPE_JSON) if lastModified != nil { headers.Set("Last-Modified", lastModified.Format(http.TimeFormat)) } if len(etag) > 0 { headers.Set("ETag", etag) } m := jsonhelper.NewJSONObject() w := json.NewEncoder(writer) m.Set("status", "success") m.Set("result", obj) w.Encode(m) return statusCode, headers, nil }
func readPropertiesFile(filename string) (jsonhelper.JSONObject, error) { props := jsonhelper.NewJSONObject() propFile, err := os.Open(filename) if propFile == nil { log.Fatal("Could not open properties file: ", filename) return props, err } defer propFile.Close() if err != nil { log.Fatal("Error opening file ", filename, ": ", err.Error()) return props, err } json.NewDecoder(propFile).Decode(&props) if err != nil { log.Fatal("Error reading settings: ", err) } if len(props) <= 0 { log.Fatal("No settings found in properties file") } return props, err }
func (p *ContactField) UnmarshalJSON(data []byte) os.Error { o := jsonhelper.NewJSONObject() err := json.Unmarshal(data, &o) p.Uri = o.GetAsString("uri") p.Created = o.GetAsString("created") p.Updated = o.GetAsString("updated") p.Id = o.GetAsInt64("id") p.Type = o.GetAsString("type") p.EditedBy = o.GetAsString("editedBy") flags := o.GetAsArray("flags") lf := flags.Len() p.Flags = make([]string, lf) for i := 0; i < lf; i++ { p.Flags[i] = flags.GetAsString(i) } categories := o.GetAsArray("categories") lc := categories.Len() p.Categories = make([]string, lc) for i := 0; i < lc; i++ { p.Categories[i] = categories.GetAsString(i) } switch p.Type { case "name": var name Name name.FromJSON(o.GetAsObject("value")) p.Value = name case "birthday", "anniversary": var d Date d.FromJSON(o.GetAsObject("value")) p.Value = d case "address": var addr Address addr.FromJSON(o.GetAsObject("value")) p.Value = addr default: p.Value = o.GetAsString("value") } return err }
func TestViewUserAccount(t *testing.T) { ds, wm := initializeViewUserAccountDS() gw, _ := ds.FindUserAccountByUsername("firstpresident") accessKeys, _, _ := ds.RetrieveUserKeys(gw.Id, nil, 1000) if len(accessKeys) == 0 { t.Error("Expected to find at least one access key stored.") } accessKey := accessKeys[0] otherUser := gw req, _ := http.NewRequest(webmachine.GET, "http://localhost/api/v1/json/account/user/view/"+otherUser.Id, nil) req.Header.Set("Accept", webmachine.MIME_TYPE_JSON+"; charset=utf-8") req.Header.Set("Accept-Charset", "utf-8") req.Header.Set("Accept-Encoding", "identity") req.Header.Set("Accept-Language", "en-us") req.Header.Set("Connection", "close") apiutil.NewSigner(accessKey.Id, accessKey.PrivateKey).SignRequest(req, 0) resp := webmachine.NewMockResponseWriter(req) wm.ServeHTTP(resp, req) if resp.StatusCode != http.StatusOK { t.Error("Expected ", http.StatusOK, " status code but received ", resp.StatusCode) } if resp.Header().Get("Content-Type") != req.Header.Get("Accept") { t.Error("Expected Content-Type \"", req.Header.Get("Accept"), "\" but received ", resp.Header().Get("Content-Type")) } user := new(dm.User) obj := jsonhelper.NewJSONObject() err := json.Unmarshal(resp.Buffer.Bytes(), &obj) user.InitFromJSONObject(obj.GetAsObject("result")) if err != nil { t.Error("Error while unmarshaling JSON: ", err.Error()) } if obj.GetAsString("status") != "success" { t.Error("Expected status = \"success\", but was \"", obj.GetAsString("status"), "\"") } if user.Name != otherUser.Name { t.Error("Expected name = \"", otherUser.Name, "\", but was ", user.Name) } if user.Username != otherUser.Username { t.Error("Expected username = \"", otherUser.Username, "\", but was ", user.Username) } if user.Email != otherUser.Email { t.Error("Expected email = \"", otherUser.Email, "\", but was ", user.Email) } if user.PhoneNumber != otherUser.PhoneNumber { t.Error("Expected phone_number = \"", otherUser.PhoneNumber, "\", but was ", user.PhoneNumber) } if user.Address != otherUser.Address { t.Error("Expected address = \"", otherUser.Address, "\", but was ", user.Address) } if user.Role != otherUser.Role { t.Error("Expected role = ", otherUser.Role, " but was ", user.Role) } if user.Id != otherUser.Id { t.Error("Expected id to be ", otherUser.Id, ", but was ", user.Id) } if theuser, err := ds.RetrieveUserAccountById(otherUser.Id); err != nil || theuser == nil { if theuser == nil { t.Error("Unable to find User account by id ", otherUser.Id) } if err != nil { t.Error("Error trying to find user account by id: ", err.Error()) } } if theuser, err := ds.FindUserAccountByUsername(otherUser.Username); err != nil || theuser == nil { if theuser == nil { t.Error("Unable to find User account by username ", otherUser.Username) } if err != nil { t.Error("Error trying to find user account by username: "******"Found ", len(theusers), " User accounts by email for ", otherUser.Email, " rather than 1: ", theusers) } if err != nil { t.Error("Error trying to find user accounts by email: ", err.Error()) } } }