How to perform basic Auth in Lua - lua

I have the following partial lua script.
local config_string = [===[
]===]
local config = LuaConfig:new(config_string)
local request = LuaHttpRequest:new(config, "HTTP")
local username = "sss"
local password = "xxx"
request:set_header("Content-Type", "multipart/form-data")
request:set_header("Accept","application/json")
request:set_body("{\"RecordTitle\": { \"Value\": \"test vinay 344\" }, \"RecordRecordType\": \"2\", \"Fields\": { \"RoadSurface\" { \"Value\": \"smooth\" } } }")
request:set_url("http://ddddddd/CMServiceAPI/Record")
How do i perform basic Auth?

I don’t know which library you use, but something like this:
local username = "sss"
local password = "xxx"
local mime = require("mime")
request:set_header("authentication", "Basic " .. (mime.b64(username ..":" .. password)) )
request:set_header("content-type", "application/json" )
and at the end use a POST request

Related

Gatling - print the POST request URI

I would like to print the URI and want to verify the POST URI request is formed correctly, Can you please advise how to verify the POST URI request if URI is substituted/formed correctly?
object BidSubmission extends HttpUtil {
val orders_feeder = csv("data/Round-1.csv").circular
def orderSubmission: ChainBuilder =
pause(pauseBy(5) seconds)
.repeat(1) {
feed(orders_feeder)
.exec(postToUri(s"${Constants.orderSubmission_URL}/#{$AuctionId}/base-orders/proxy-bid", "")
.queryParam("employeeId", "#{empNo}")
.body(StringBody(session => {
println(session)
println(session.attributes("empNo"))
val empNo = session.attributes("empNo").asInstanceOf[String]
val orderNo = session.attributes("orderNo").asInstanceOf[String]
println(s"\n\n\n $orderNo \n\n\n")
var slotNos = orderNo.replace("[", "").replace("]", "").split(" +")
println(s"\n\n\n ${generatePayload(empNo, slotNos)} \n\n\n")
generatePayload(empNo, slotNos)
" "
}))
)
}
You have to tune the logback configuration file. Please have a look at the documentation: https://gatling.io/docs/gatling/reference/current/core/configuration/#logbackxml

C# WebClient.UploadData in Rails

I have a c# method that I'm trying to convert to ruby on rails . I'm using unirest but I think something is not working correctly. This is my C# method :
private static string HTTPPoster(string url, string prmSendData)
{
try
{
WebClient wUpload = new WebClient();
wUpload.Proxy = null;
Byte[] bPostArray = Encoding.UTF8.GetBytes(prmSendData);
Byte[] bResponse = wUpload.UploadData(url, "POST", bPostArray);
Char[] sReturnChars = Encoding.UTF8.GetChars(bResponse);
string sWebPage = new string(sReturnChars);
return sWebPage;
}
catch
{
return "-1";
}
}
And This is what I tried so far in rails with unirest :
def HTTPPoster(url)
xml = "My XML Goes Here"
byte_array = xml.bytes
headers = {}
headers['Content-Type'] = "application/json"
headers['Accept'] = "application/json"
response = Unirest.post(url,
headers: headers,
parameters: {
body: byte_array
})
puts "response #{response.body}"
if ![200,201].include?(response.code)
raise "Mblox Error: #{response.code}, #{response.body}"
end
end
If you also know other libraries that can achieve what I need please let me know.
I used Faraday gem and sent the data as xml and not as byte array. And now I am achieving want I wanted.
response = Faraday.post(url) do |req|
req.headers['Content-Type'] = "application/xml"
req.headers['Accept'] = "*/*"
req.headers['Accept-Encoding'] = "gzip, deflate, br"
req.body = xml
end

Lua request from Tado thermostat api

I'm building a so called 'Quickapp' in Home Center 3 (From Fibaro) in the 'Lua' programming language. I want to fetch some data from the Tado api, but it's poorly documented. I keep getting the following message from the console:
Full authentication is required to access this resourceunauthorized
I think that's because I need do assign the Bearer token from the request, but i'm a little lost how...
This is what i have so far:
function QuickApp:fetchTadoData(username,password,client_secret)
local url = "https://auth.tado.com/oauth/token"
local postdata = {
["client_id"] = "tado-web-app",
["grant_type"] = "password",
["scope"] = "home.user",
["username"] = username,
["password"] = password,
["client_secret"] = client_secret
}
local extraheaders = {
["content-type"] = "application/json"
}
self.http:request(url, {
options={
headers = extraheaders,
data = json.encode(postdata),
method = "POST"
},
success = function(status)
self:debug(status.data)
end,
error = function(error)
errorlog("Error getting data: "..error)
self:debug("hallo")
end
})
end
I know the Curl code to get the 'Bearer token' response:
curl -s "https://auth.tado.com/oauth/token" -d client_id=tado-web-app -d grant_type=password -d scope=home.user -d username="you#example.com" -d password="Password123" -d client_secret=wZa
But I don't know how to translate this to the above Lua code. Any help is appreciated!
https://manuals.fibaro.com/home-center-3-quick-apps
Looks OK, the main thing I'm noticing is this:
"self.http must have previously been created by net.HTTPClient"
function QuickApp :fetchTadoData( username, password, client_secret )
self .http = net .HTTPClient( { timeout = 5000 } ) -- 5 seconds
local url = "https://auth.tado.com/oauth/token"
local requestBody = {
action = 'create',
params = {
["client_id"] = "tado-web-app",
["grant_type"] = "password",
["scope"] = "home.user",
["username"] = username,
["password"] = password,
["client_secret"] = client_secret
}
}
local extraheaders = {
["content-type"] = "application/json",
["accept"] = "application/json"
}
self .http :request( url, {
options = {
headers = extraheaders,
data = json .encode( requestBody ),
method = "POST"
},
success = function( response )
self :debug( response .status )
self :debug( response .data )
end, -- success
error = function( msg )
self :debug( 'Error: ' ..msg )
end -- error
})
end -- :fetchTadoData()

Sending a message to discord webhook with lua

So I am trying to send a message to a discord webhook in Lua.
Currently I have this code:
local http = require("socket.http")
ltn12 = require("ltn12")
local payload = [[ {"username":"NAME","avatar_url":"","content":"MESSAGE"} ]]
http.request
{
url = "https://discordapp.com/api/webhooks/<redacted>",
method = "POST",
headers =
{
["Content-Type"] = "application/json",
["Content-Length"] = payload:len()
},
source = ltn12.source.string(payload),
}
That I found here: http://forum.micasaverde.com/index.php?topic=32035.0
But the message never arrives. What am I doing wrong?
Edit: I tested a bit and it seems like I get a 301 error code when I send this to the discord webhook.

How to get the object url with alias name from aws s3 using CloudFront

I am uploading files with unique id like 'd9127dfd01182afe7d34a37' as object name to amazon s3 and storing the file information with my local database including original name of the file. And I am using CloudFront url to download the file.
If I download the file using CloudFront url file name is d9127dfd01182afe7d34a37. But I need to change file name again to it's original name wich I have in my database. I don't want to download it. I want to give the url with original name to the client(WebUI) and client can download it through url.
serverside code
document_url = initialize_cloud_service(document.provider['primary']).get_object_url(document_id, expires_at, 'CloudFront' )
if document_url
item = {}
item['id'] = document['_id'].to_s
item['name'] = document['name']
item['mime_type'] = document['mime_type']
item['url'] = document_url
return {success: true, message: MESSAGES['get_url_succuss'],data: item}.to_json
end
client side code
download: function(response){
file = response.data
link = document.createElement('a');
link.download = file.name;
link.href = file.url;
link.click();
},
Is there any way to achieve this? Please help me out. I am using ruby on rails and mongodb as local database.
Thanks
I have achieved by doing the following changes
Server Side code
begin
expires_at = Time.now.to_i + 30.seconds.to_i
options = nil
selected_provider = provider || document.provider['primary']
case selected_provider
when "s3"
options = {"response-content-disposition" => "attachment; filename=#{document['name']}"}
downloadable_url = initialize_cloud_service(selected_provider).get_downloadable_url(document_id, expires_at, options)
when "google_cloud"
downloadable_url = initialize_cloud_service(selected_provider).get_downloadable_url(document_id, expires_at, options)
downloadable_url += "&response-content-disposition=attachment%3B%20filename%3D#{document['name']}"
end
item = {}
item['id'] = document['_id'].to_s
item['name'] = document['name']
item['mime_type'] = document['mime_type']
item['url'] = downloadable_url
return {success: true, message: MESSAGES['get_url_succuss'],data: item}.to_json
rescue Exception => e
puts 'Exception in download, message: ' + e.message
return {success: false, message: MESSAGES['default']}.to_json
end
client side code
download: function(response){
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = response.data.url;
},

Resources