# frozen_string_literal: true module Meroku # Logic related to Users login, logout etc module User def self.login(email, password) data = { 'email' => email, 'password' => password }.to_json result = RestClient.post 'https://www.meroku.com/login.json', data, content_type: :json process_error(result) process_success(result) { |x| save_token(x) } end def self.process_error(result) raise Meroku::Error, JSON.parse(result).dig('errors') \ if JSON.parse(result).dig('errors') end def self.process_success(result) id = JSON.parse(result).dig('data', 'id') if id yield(result) if block_given? puts "OK [#{id}]" end raise Meroku::Success end def self.save_token(x) token = JSON.parse(x).dig('data', 'id') IO.write("#{Dir.home}/.meroku_token", token) if token end def self.logout file = "#{Dir.home}/.meroku_token" File.delete(file) puts 'Logged out' raise Meroku::Success end def self.signup(email, password) data = { 'email' => email, 'password' => password }.to_json result = RestClient.post 'https://www.meroku.com/registrations.json', data, content_type: :json process_error(result) process_success(result) { |x| save_token(x) } end def self.unregister(options) data = { 'email' => options[:email], 'password' => options[:password] } result = RestClient::Request.execute( method: :delete, url: 'https://www.meroku.com/registrations.json', headers: { params: data } ) process_error(result) process_success(result) { delete_token } end def self.delete_token file = "#{Dir.home}/.meroku_token" File.delete(file) if File.exist?(file) end end end