class Oauth
RESPONSE_TYPE = 'response_type'
CLIENT_ID = 'client_id'
REDIRECT_URI = 'redirect_uri'
AUTHORIZATION_TOKEN = 'authorization_token'
REQUIRED_PARAMS = [RESPONSE_TYPE, CLIENT_ID, REDIRECT_URI]
VALID_PARAMS = REQUIRED_PARAMS
attr_reader :errors
def initialize(params)
#params = params
#errors = []
end
def valid?
REQUIRED_PARAMS.all?{ |param| valid_params.has_key?(param) }
end
# private
def valid_params
#params.slice(*VALID_PARAMS)
end
end
I would like to collect missing #{param} key errors after calling valid? method.
You can try to make your OAuth Object an ActiveModel it behaves like an ActiveRecord Model but is not backed via DB. ActiveModel allows you to use validations as you would in an AR model, so fetching the validation errors would be likewise.
Related
Under the commands folder, I'd like to initialize a controller
but Sinatra reports this error in the logs
ArgumentError: wrong number of arguments (given 1, expected 2)
/home/daniel/sinatraApi/app/commands/authenticate_user.rb:6:in `initialize'
/home/daniel/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/rack-2.0.7/lib/rack/builder.rb:86:in `new'
2.0.7/lib/rack/builder.rb:147:in `to_app'
config.ru:15:in `inner_app'
/
The controllers are called
use AuthenticateUser
run ApplicationController
I've tried to add
use Commands::AuthenticateUser
or require
require "./app/commands/authenticate_user"
on config.ru
Authenticate_user
require 'jwt'
#require './app/controllers/application'
class AuthenticateUser
prepend SimpleCommand
def initialize(email, password)
#email = email
#password = password
end
def call
JsonWebToken.encode(user_id: user.id) if user
end
private
attr_accessor :email, :password
def user
user = User.find_by_email(email)
return user if user && user.authenticate(password)
errors.add :user_authentication, 'invalid credentials'
nil
end
end
How can I setup the namespace or nested controllers in Sinatra?
I've got a method sitting in a Services class. This method is going to take the name of a service and a key:value pair of an attribute I want to build a string query for to call out to the service i'm passing in.
I'm sending this build string query to the service via RestClient and capturing the response in a variable: #response
I want to carry this variable out of the Services class and use it. I've got attr_reader included in my class but i keep getting nil for #response when I try to access the response outside of Services.
What am I missing?
Example of my code:
class Services
attr_reader :response
def query_method(service,key,value)
where = "#{key}=#{value}"
#url = root_url + service + where
#response = RestClient::Request.execute(:method => :get, :url => #url)
end
end
I have a Sinatra app with this route that is requested by an Android app and returns some Json with connection information.
post '/getConnection' do
content_type :json
#session and tokens
session_id = 123
agent_token = 456
user_token = 789
#Create new room based on session and store
newRoom = Room.new
newRoom.attributes = {:sessionID => session_id,
:agentToken => agent_token,
:userToken => user_token}
newRoom.save
#Json
{:con =>[:session =>session_id,:token =>user_token]}.to_json
end
Everything works properly without the new room creation and database store(Using Datamapper by the way). However when I add it, or even a function that contains the code is messes up the response.
Here is the Room model:
class Room
include DataMapper::Resource
property :id, Serial
property :sessionID, String
property :agentToken, String
property :userToken, String
end
DataMapper.finalize
DataMapper.auto_upgrade!
Is there a way to implement a callback function or something that will return the Json and store the information without messing up the Json being sent?
I have resolved this issue.
The problem was with DataMapper not being required and configured in my app.rb file. I ended up with:
require 'data_mapper'
DataMapper.setup(:default, 'postgres://database-uri')
post '/getConnection' do
content_type :json
#session and tokens
session_id = 123
agent_token = 456
user_token = 789
#Create new room based on session and store
Room.create(
:sessionID => session_id,
:agentToken => agent_token,
:userToken => user_token
)
#Json
{:con =>[:session =>session_id,:token =>user_token]}.to_json
end
How can I stub private/protected methods to be passed in functional controller tests?
Having the following code for example:
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def create
#user = User.from_omniauth(auth_hash)
reset_session
session[:user_nickname] = #user.nickname
if #user.email.blank?
redirect_to edit_user_path(#user.nickname), :alert => "Please enter your email address."
else
redirect_to show_user_path(#user.nickname), :notice => 'Signed in!'
end
end
private
def auth_hash
request.env['omniauth.auth']
end
end
I tried the following :
test/controllers/sessions_controller_unit_test.rb
require 'test_helper'
class SessionsControllerTest < ActionController::TestCase
test "should create new user" do
# get the same 'request.env['omniauth.auth'] hash
auth_h = OmniAuth.config.mock_auth[:github]
# but auth_hash is never passed in User.find_or_create_from_auth_hash(auth_hash)
# method, which result to be nil breaking the User model call
get :create, provider: 'github', nickname: 'willishake', auth_hash: auth_h
assert_redirected_to show_user_path(nickname: 'willishake')
assert_equal session[:user_id], "willishake"
end
end
but when get :create (the test method) calls
the model User.find_or_create_from_auth_hash(auth_hash), auth_hash is nil, breaking the functional test.
So what's the right way to stub auth_hash private method and passing to User model call User.from_omniauth(auth_hash) ?
UPDATE:
after blowmage suggestion, it works like the following:
require 'test_helper'
class SessionsControllerTest < ActionController::TestCase
def setup
request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:github]
end
test "should create new user" do
get :create, provider: 'github', nickname: 'willishake'
assert_equal session[:user_id], "willishake"
assert_redirected_to show_user_path(nickname: 'willishake')
end
end
Try this:
# set the request.env['omniauth.auth'] hash
auth_h = OmniAuth.config.mock_auth[:github]
request.env['omniauth.auth'] = auth_h
Some of attributes specified in ActiveModel are non db attributes which are just defined as getter setter. Problem is that these attributes values are not reflected on activeresource record on client side.
#server side code
class Item < ActiveRecord::Base
#not null name attribute defined on db
end
class SpecialItem < ActiveRecord::Base
#nullable item_name attribute defined on db
#association many to one for item defined here
#name accessor
def name
if !item_name.nil?
return item_name
else
return item.name
end
end
end
#client side code
class SpecialItem < ActiveResource::Base
schema do
attribute 'name', 'string'
end
end
I am getting nil value for attribute name for SepcialItem record on client. Basically i am trying to map accessor method name to name attribute on client side.
What is possible solution?
ActiveResource is a means of communicating with a RESTful service and requires the class variable site to be defined, i.e.
class SpecialItem < ActiveResource::Base
self.site = 'http://example.com/'
self.schema = { 'name' => :string}
end
This would utilize the default Rails collection and element conventions. So for a call to SpecialItem.find(1), ActiveResource would route to GET http://example.com/specialitems/1.json