Custom devise sign_up: json response after sign up - json

i want customize devise sign_up in order that after a json sign up post request, i get a json response.
So, in app/controllers i have created session_controller.rb:
class SessionsController < Devise::SessionsController
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
respond_to do |format|
format.html do
respond_with resource, :location => after_sign_in_path_for(resource)
end
format.json do
render :json => { :response => 'ok'}.to_json, :status => :ok
end
end
end
end
and in routes.rb:
devise_for(:users, :controllers => { :sessions => "sessions" })
Now i want make a json post request to sign up a user and get a json response.
I set the URL: localhost:3000/users.json
Method: Post
Header: Content-Type: application/json
Data: {"user":{"email":"test#gmail.com", "password":"password123", "password_confirmation":"password123"}}
Why i don't receive the correct json response?
I receive:
Staus:406 Not Acceptable
X-Runtime: 0.102006
Date: Tue, 02 Apr 2013 16:03:03 GMT
Server: WEBrick/1.3.1 (Ruby/1.9.3/2012-02-16)
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache
Connection: Keep-Alive
Content-Length: 1
X-Request-Id: 24f5d66b1de09560b88e332e06b33c1b
X-Ua-Compatible: IE=Edge

Related

Extract broken JSON from response

I am using requests in python3 to send post request to yahoo login website, in Burpsuite I got the following response:
HTTP/1.0 200 OK
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Age: 0
Pragma: no-cache
Expires: 0
Referrer-Policy: origin-when-cross-origin
Cache-Control: no-cache, no-store, must-revalidate
set-cookie: AS=v=1&s=8ZJenFRo&d=A611b9f16|50....OXCxVzImJQI-~A; path=/; domain=login.yahoo.com; secure; HttpOnly
Content-Type: application/json; charset=utf-8
Content-Length: 149
Vary: Accept-Encoding
Date: Tue, 17 Aug 2021 11:20:50 GMT
Strict-Transport-Security: max-age=15552000
Server: ATS
{"location":"/account/challenge/recaptcha?done=https%3A%2F%2Fwww.yahoo.com%2F&sessionIndex=QQ--&acrumb=8ZJenFRo&display=login&authMechanism=primary"}
The goal is to get this line in python
{"location":"/account/challenge/recaptcha?done=https%3A%2F%2Fwww.yahoo.com%2F&sessionIndex=QQ--&acrumb=8ZJenFRo&display=login&authMechanism=primary"}
I wrote a simple script to do the post request but it crashes when response.json() is called
import requests
from user_agent import generate_user_agent
def check_yahoo(email):
yahoo_url = "https://login.yahoo.com"
data= {"username":f"{email}"}
heads = {"User-Agent":f"{generate_user_agent()}"}
response = requests.post(yahoo_url , params=data , headers=heads)
print (response.json())
return
#driver code
check_yahoo("some.one#yahoo.com")
How do you extract json data if it was broken
Error
File "/home/kali/Desktop/yah00/yah00.py", line 49, in <module>
check_yahoo(item)
File "/home/kali/Desktop/yah00/yah00.py", line 37, in check_yahoo
print (response.json())
File "/usr/lib/python3/dist-packages/requests/models.py", line 900, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3/dist-packages/simplejson/__init__.py", line 525, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The json looks ok so it might be that the empty line is throwing it off. What is the content of response.text? If that includes the empty line, something like
json.loads(response.text.strip())
might be enough.
You can use a try/except to debug your error, like:
def some_function(data):
try:
*enter your success code*
except:
*enter in error statement*
see more information in https://docs.python.org/3/tutorial/errors.html

Consuming JSON response to Deserialize

I'm getting a response in JSON and I'm trying to use the
DeserializeStoreInfoResponse(Storeresponse As String) As String
Dim obj As New JSON_resultStorePos
obj = JsonConvert.DeserializeObject(Of JSON_resultStorePos)(Storeresponse)
the initial response is a HttpResponseMessage and all I need is the JSON string info. When it's a nice neat string in Json format everything deserializes fine into the JSON_resultStorePos table. But I'm trying to view the initial response to see if everything is there in their response and can't quite figure out where the actual JSON content is written in the HttpResponseMessage?
here's some of the response:
?aResponse
{StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Strict-Transport-Security: max-age=7776000; includeSubDomains
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Pragma: no-cache
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Cache-Control: no-store
Date: Thu, 10 Nov 2016 13:37:39 GMT
Set-Cookie: SERVERID=04-97JSNQEU5RG2G; path=/; HttpOnly
Server: Apache
X-Powered-By: Express
Content-Length: 71
Content-Type: application/json
?aResponse.Content
{System.Net.Http.StreamContent}
Headers: {Content-Length: 71
Content-Type: application/json
}
IsBuffered: True
bufferSize: 4096
bufferedContent: {System.Net.Http.HttpContent.LimitMemoryStream}
canCalculateLength: True
content: {System.Net.Http.HttpClientHandler.WebExceptionWrapperStream}
contentConsumed: True
contentReadStream: Nothing
disposed: False
headers: {Content-Length: 71
Content-Type: application/json
How can I see the JSON string I'm deserializing ?

How to read json data of a bad request (status code 400) using Alamofire

I was calling a Rest API locally from terminal. This was like below:
http -v -f --timeout=60 GET 'http://localhost:8080/api/v1/public/users/signin?email=myemail#email.com&password=mypassword'
It is returning following output:
GET /api/v1/public/users/signin?email=myemail#email.com&password=mypassword HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Host: localhost:8080
User-Agent: HTTPie/0.8.0
HTTP/1.1 400 Bad Request
Content-Type: application/json
Date: Mon, 28 Mar 2016 16:59:08 GMT
Set-Cookie: rememberMe=deleteMe; Path=/; Max-Age=0; Expires=Sun, 27- Mar-2016 16:59:13 GMT
Transfer-Encoding: chunked
{
"debugMessage": "Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - najmul#qianalysis.com, rememberMe=true] did not match the expected credentials.Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - najmul#qianalysis.com, rememberMe=true] did not match the expected credentials.: The subject was expected to be true, but was false",
"errorCode": "INCORRECT_CREDENTIALS",
"logId": "50a695c1a81e0542",
"stackTrace": "org.niopack.r.....
}
Now I want to read this JSON data using Alamofire. I tried with responseJSON serialiser with following way:
Alamofire.request(method, urlString, parameters: parameters, encoding: .URL, headers: cookieHeader)
.validate()
.responseJSON {
alamofireResponse in
let jsonData = alamofireResponse.result.value
}
But this I am getting jsonData as nil. What you will do if you were are here?
Thanks.
For me removing the validate() allowed me to see the reason the request was failing. For some reason when validate fails, the data of the response is not parsed.

cURL post to server resulting in a UnknownFormat error

I am very new at rails and having a hard time doing a cURL post to my server. Any help would be apreciated.
I am posting JSON data to my server.
this is my curl post curl -X POST -H "Content-Type: application/json" -d '[{"photo":[{ "location": "location", "userID": "userid" },{ "location": "location", "userID": "userid" },{"location": "location", "userID": "userid"}]}]' http://localhost:3000/photo/create
this is my controller:
class SendphotoController < ApplicationController
def create
#photo = Photo.new(:photo => params[:location], :photo => params[:userID])
respond_to do |format|
if #photo.save
puts "Done"
else
puts "NOPE"
end
end
end
I get the error of ActionController::UnknownFormat (ActionController::UnknownFormat):
This is the full log:
Started POST "/photo/create" for 127.0.0.1 at 2013-09-08 22:03:56 -0400
Processing by SendphotoController#create as */*
Parameters: {"_json"=>[{"photo"=>[{"location"=>"location", "userID"=>"userid"}, {"location"=>"location", "userID"=>"userid"}, {"location"=>"location", "userID"=>"userid"}]}], "sendphoto"=>{"_json"=>[{"photo"=>[{"location"=>"location", "userID"=>"userid"}, {"location"=>"location", "userID"=>"userid"}, {"location"=>"location", "userID"=>"userid"}]}]}}
WARNING: Can't mass-assign protected attributes for Photo: photo
app/controllers/sendphoto_controller.rb:4:in `create'
(0.0ms) begin transaction
SQL (0.3ms) INSERT INTO "photos" ("created_at", "updated_at") VALUES (?, ?) [["created_at", Mon, 09 Sep 2013 02:03:56 UTC +00:00], ["updated_at", Mon, 09 Sep 2013 02:03:56 UTC +00:00]]
(215.8ms) commit transaction
Done
Completed 406 Not Acceptable in 235ms
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/sendphoto_controller.rb:5:in `create'
You're using a respond_to block, but not any formats. Your block should look something like this:
respond_to do |format|
format.html {
# respond to a web form with HTML
}
format.json {
# respond to API request
}
end
If you just want a generic response for all formats, you can drop the respond_to bit altogether. But puts isn't going to work in a Controller context (or pretty much anywhere in Rails for that matter); you have to render something.
That might look something like this
def create
if Photo.create # ...
render text: "done"
else
render text: "nope"
end
end

Rails mailer mimepart visible as text in message body

I'm sending test mail using ActionMailer. The template is being rendered and mail is being delivered fine. The only problem is the mimepart and other header data is displayed by Google in message body.
Here is the code that mails..
def testing
mail(:to => "apoorvparijat#gmail.com",:subject => "html mailer", :content_type => "text/html") do |format|
format.html { render 'testing' }
format.text { render :text => "bing" }
end
end
and Here's the email received.
----==_mimepart_508fd46252b8c_8023fe595835ad0479a6 Date: Tue, 30 Oct 2012 18:51:38 +0530
Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit
Content-ID: <508fd46254ea7_8023fe595835ad0480b8#Apoorv-Parijats-MacBook-Pro-2.local.mail>
bing ----==_mimepart_508fd46252b8c_8023fe595835ad0479a6 Date: Tue, 30 Oct 2012 18:51:38
+0530 Mime-Version: 1.0 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding:
7bit Content-ID: <508fd46256465_8023fe595835ad04819c#Apoorv-Parijats-MacBook-Pro-
2.local.mail> Hi bing
column 1 column 2
----==_mimepart_508fd46252b8c_8023fe595835ad0479a6--
Output of the console -
Loading development environment (Rails 3.2.2)
1.9.3-p125 :001 > RankMailer.testing.deliver
I, [2012-10-30T18:51:38.331238 #2050] INFO -- : Rendered rank_mailer/testing.html.erb
(1.8ms)
I, [2012-10-30T18:51:38.333117 #2050] INFO -- : Rendered text template (0.0ms)
I, [2012-10-30T18:51:45.824962 #2050] INFO -- :
Sent mail to apoorvparijat#gmail.com (7484ms)
D, [2012-10-30T18:51:45.825125 #2050] DEBUG -- : Date: Tue, 30 Oct 2012 18:51:38 +0530
From: admin#rankdemon.com
To: apoorvparijat#gmail.com
Message-ID: <508fd462572ec_8023fe595835ad0482c0#Apoorv-Parijats-MacBook-Pro-2.local.mail>
Subject: html mailer
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
----==_mimepart_508fd46252b8c_8023fe595835ad0479a6
Date: Tue, 30 Oct 2012 18:51:38 +0530
Mime-Version: 1.0
Content-Type: text/plain;
charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-ID: <508fd46254ea7_8023fe595835ad0480b8#Apoorv-Parijats-MacBook-Pro-2.local.mail>
bing
----==_mimepart_508fd46252b8c_8023fe595835ad0479a6
Date: Tue, 30 Oct 2012 18:51:38 +0530
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-ID: <508fd46256465_8023fe595835ad04819c#Apoorv-Parijats-MacBook-Pro-2.local.mail>
Hi bing
<table style="border:1px solid red">
<tr>
<td>column 1</td>
<td>column 2</td>
</tr>
</table>
----==_mimepart_508fd46252b8c_8023fe595835ad0479a6--
=> #<Mail::Message:70255316899740, Multipart: false, Headers: <Date: Tue, 30 Oct 2012 18:51:38 +0530>, <From: admin#rankdemon.com>, <To: apoorvparijat#gmail.com>, <Message-ID: <508fd462572ec_8023fe595835ad0482c0#Apoorv-Parijats-MacBook-Pro-2.local.mail>>, <Subject: html mailer>, <Mime-Version: 1.0>, <Content-Type: text/html>, <Content-Transfer-Encoding: 7bit>>
Don't specify :content_type => "text/html" in your mail method. Since you're using format block, rails will automatically pick up mime type.
MORE DETAILS:
Try this to send out multipart email (ie. both html and text formats of email). Notice the order of formats.
mail(:to => "apoorvparijat#gmail.com", :subject => "html mailer") do |format|
format.text { render :text => "bing" }
format.html { render 'testing' }
end