module Session extend self @@http = nil @@cookie = nil def login(user: 'admin', pass: 'A1d2m3i4n5', server: 'localhost:443') host, port = server.split(':') @@http = Net::HTTP.new(host, port) @@http.use_ssl = true @@http.verify_mode = OpenSSL::SSL::VERIFY_NONE account = {user: user, pass: pass, version: '9999123101'} puts "Logging in as #{account[:user]}" resp = @@http.request_post('/auth/login', account.to_json, nil) raise "Cannot login " unless resp['Set-Cookie'] @@cookie = resp['Set-Cookie'] puts "Logged in" rescue Exception => e puts e.message exit! end def logout res = @@http.request_post('/auth/logout', nil, {'Cookie' => @@cookie}) puts "Logged out" if res.kind_of? Net::HTTPSuccess rescue Exception => e puts e.message exit! end def post(uri, content, options: {json: true}) content = content.to_json if options[:json] reply = @@http.request_post(uri, content, {'Cookie' => @@cookie}) raise "Error from server: #{reply.body}" unless reply.kind_of? Net::HTTPOK reply.body = JSON.parse(reply.body) if options[:json] and reply.body.size > 2 return reply.body rescue Exception => e puts e.message exit! end def get(uri, options: {json: true}) reply = @@http.request_get(uri, {'Cookie' => @@cookie}) raise "Error from server: #{reply.body}" unless reply.kind_of? Net::HTTPOK reply.body = JSON.parse(reply.body) if options[:json] and reply.body.size > 2 return reply.body rescue Exception => e puts e.message exit! end end # global scope for DSL def login(params) Session.login(params) end def logout Session.logout end .