require "plyom_user/version" require "httparty" require "json" module Plyom class PlyomUser class_attribute :id, :name, :email, :username, :password, :password_confirmation, :password_digest, :password_reset_token, :password_reset_sent_at, :status, :token, :created_at, :updated_at def initialize(params={}) params.each { |var, val| public_send("#{var}=", val) } end def self.all list = [] response = action_by("read") objs = JSON.parse(response.body) objs.each { |obj| list << self.new(obj) } list end def self.find(id) response = action_by("read", id: id) obj = JSON.parse(response.body) self.new(obj) end def save param_names = ["name", "email", "username", "password", "password_confirmation", "status"] data = filter_params(param_names) if data.length > 0 paramters = { user: data } paramters.update({ id: @id }) if @id.to_i > 0 action = @id.to_i > 0 ? "update" : "add" response = PlyomUser.action_by(action, paramters) @id = response['id'] if action == "add" response else nil end end def remove PlyomUser.action_by("del", id: @id) end private def filter_params(names=[]) params = {} self.instance_variables.each do |var| var_name = var.to_s.delete "@" var_value = self.instance_variable_get var params.update({var_name => var_value}) if names.include?(var_name) end params end def self.action_by(action, params={}) auth_token = { "Authorization" => "Token token=\"#{ENV['plyom_user_token']}\"" } case action when "read" HTTParty.get("#{uri}/#{params[:id]}", headers: auth_token) when "add" HTTParty.post("#{uri}", query: params, headers: auth_token) when "del" HTTParty.delete("#{uri}/#{params[:id]}", headers: auth_token) when "update" HTTParty.patch("#{uri}/#{params[:id]}", query: params, headers: auth_token) if params.size > 1 HTTParty.put("#{uri}/#{params[:id]}", query: params, headers: auth_token) if params.size == 1 end end def self.uri host = ENV["plyom_user_host"] path = "/api/users" host + path end end class Authentication class_attribute :id, :token, :validation def initialize(params) @params = params end def authenticated?(token) auth_token = { "Authorization" => "Token token=\"#{token}\"" } paramters = {username_email: @params[:username], password: @params[:password]} response = HTTParty.get("#{self.uri}authentication", headers: auth_token, query: paramters) result = JSON.parse(response.body) if result["success"] @token = result["token"] @validation = 1 @id = result["id"] true else false end end def validation @validation end def check_token(token) paramters = {token: @token} auth_token = { "Authorization" => "Token token=\"#{token}\"" } response = HTTParty.get("#{self.uri}token_validation", headers: auth_token, query: paramters) response.body end def self.validates(validation) if validation == 1 true else false end end def uri host = ENV["plyom_user_host"] path = "/api/" host + path end end end