devise authentication via ruby script
I have small application, and I will have some external applications put data to this service over http with rest. I already have it working but without authentication. In portal I use devise, and my question is: how to (example desired) authenticate to portal from ruby script level? What to add to following script to authenticate first? I want to protect this controller with devise and then I need authentication part to following script.
require "net/http"
require "json"
@host = "localhost"
@port = 3000
@post_ws = "/external/rd"
@req_body = {
"device" => {
"name" => "device_json",
"operating_system_id" => "7",
"hash_string" => "jfsg3k4ovj0j02jv",
"user_id" => "1"
}
}.to_json
req = Net::HTTP::Post.new(@post_ws, initheader = {'Content-Type' =>'application/jso开发者_运维百科n'})
req.body = @req_body
response = Net::HTTP.new(@host, @port).start {|http| http.request(req) }
Regards, Mateusz
Here is solution:
I used token_authenticatable from devise.
Here is one great answer how to implement it with json. I had some trouble and described them in this question. There is also answer.
Here goes example code:
require "net/http"
require "json"
@host = "localhost"
@port = 3000
@post_sign = "/users/sign_in.json"
@post_ws = "/external/rd"
@req_sign = {
"user" => {
"email" => "some@email.com",
"password" => "123456"
}
}.to_json
sig = Net::HTTP::Post.new(@post_sign, initheader = {'Content-Type' => 'application/json'})
sig.body = @req_sign
http = Net::HTTP.new(@host, @port).start
resp1 = http.request(sig)
puts "Response: #{resp1.code} , Message: #{resp1.message} , Body: #{resp1.body}"
if resp1.code == "200" then
puts "logged in"
json_resp = JSON.parse(resp1.body)
@auth_token = json_resp['auth_token']
@req_body = {
"device" => {
"name" => "device_json",
"operating_system_id" => "7",
"hash_string" => "jfsg3k4ovj0j02jv"
},
"auth_token" => @auth_token
}.to_json
req = Net::HTTP::Post.new(@post_ws, initheader = {'Content-Type' =>'application/json'})
req.body = @req_body
response = http.request(req)
puts "Response: #{response.code} , Message: #{response.message} , Body: #{response.body}"
end
Regards, Mateusz
精彩评论