I'm making a internal http request, from one method to another method forwarding the info, but when i make the post the second method freeze all exactly in a query in the second method, i already try to use another another database, new project, Any ideas on what is going on?
Routes
post 'rest/login'
post 'rest/verify_user/:email', to: 'auth#verify_user', as: 'verify', constraints: { email: /.*/ }
resources :users
Method 1
class RestController < ApplicationController
protect_from_forgery with: :null_session, only: Proc.new { |c| c.request.format.json? }
def login
response = RestClient.post(verify_url(params[:email]),
{'image' => params[:image]}.to_json,
{content_type: :json, accept: :json})
end
end
Method 2
class AuthController < ApplicationController
protect_from_forgery with: :null_session, only: Proc.new { |c| c.request.format.json? }
def verify_user
email = params[:email]
user = User.find_by(email: email)
if user
image = JSON.parse(request.raw_post)
diff = distance_percent(user.image,image["image"])
if diff <= 10
render status: 200
else
render status: 40
end
else
render status: 404
end
end
end
Related
I've been stuck for days and searching but I cannot find a correct solution to logout from a devise session using JWT. I had a front made with react and everything works fine on login and searching, but when I logout the page if I don't make a refresh I can't login. I leave the code from devise session controller along side the application controller, route and my middeware build to use redux with my front (I'm working with React to). Thanks in advance and I you need something else, let me know.
Devise::SessionsController
# frozen_string_literal: true
class Api::SessionsController < Devise::SessionsController
respond_to :json, :html
# GET /resource/sign_in
# def new
# super
# end
# POST /resource/sign_in
# def create
# super
# end
# DELETE /resource/sign_out
# def destroy
# super
# end
# protected
private
def revoke_token(token)
# Decode JWT to get jti and exp values.
begin
secret = Rails.application.credentials.jwt_secret
jti = JWT.decode(token, secret, true, algorithm: 'HS256', verify_jti: true)[0]['jti']
exp = JWT.decode(token, secret, true, algorithm: 'HS256')[0]['exp']
user = User.find(JWT.decode(token, secret, true, algorithm: 'HS256')[0]['sub'])
sign_out user
# Add record to blacklist.
time_now = Time.zone.now.to_s.split(" UTC")[0]
sql_blacklist_jwt = "INSERT INTO jwt_blacklist (jti, exp, created_at, updated_at) VALUES ('#{ jti }', '#{ Time.at(exp) }', '#{time_now}', '#{time_now}');"
ActiveRecord::Base.connection.execute(sql_blacklist_jwt)
rescue JWT::ExpiredSignature, JWT::VerificationError, JWT::DecodeError
head :unauthorized
end
end
def respond_with(resource, _opts = {})
render json: resource
end
def respond_to_on_destroy
token = request.headers['Authorization'].split("Bearer ")[1]
revoke_token(token)
request.delete_header('Authorization')
render json: :ok
end
end
ApplicationController
class ApplicationController < ActionController::API
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :authenticate_user
protected
def configure_permitted_parameters
added_attrs = %i[username email password password_confirmation remember_me]
devise_parameter_sanitizer.permit(:sign_up, keys: added_attrs)
devise_parameter_sanitizer.permit(:account_update, keys: added_attrs)
end
private
def authenticate_user
if request.headers['Authorization'].present?
token = request.headers['Authorization'].split("Bearer ")[1]
begin
jwt_payload = JWT.decode(token, Rails.application.credentials.jwt_secret).first
#current_user_id = jwt_payload['sub']
rescue JWT::ExpiredSignature, JWT::VerificationError, JWT::DecodeError
head :unauthorized
end
end
end
def authenticate_user!(options = {})
head :unauthorized unless signed_in?
end
def current_user
#current_user ||= super || User.find(#current_user_id)
end
def signed_in?
#current_user_id.present?
end
end
routes.rb
Rails.application.routes.draw do
devise_for :users, skip: %i[registrations sessions passwords]
namespace :api do
devise_scope :user do
post 'signup', to: 'registrations#create'
post 'login', to: 'sessions#create'
delete 'logout', to: 'sessions#destroy'
get 'login', to: 'sessions#create'
end
resources :notes
resources :searches
get 'get_places', to: 'searches#get_places'
end
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
middleware.js
import * as constants from './constants';
import axios from 'axios';
import { logoutUser } from './actions/authActionCreators'
export const apiMiddleware = ({ dispatch, getState }) => next => action => {
if (action.type !== constants.API) return next(action);
dispatch({ type: constants.TOGGLE_LOADER });
const BASE_URL = 'http://localhost:3001';
const AUTH_TOKEN = getState().user.token;
if (AUTH_TOKEN)
axios.defaults.headers.common['Authorization'] = `Bearer ${AUTH_TOKEN}`;
const { url, method, success, data, postProcessSuccess, postProcessError } = action.payload;
console.log('AUTH_TOKEN '+AUTH_TOKEN);
console.log('url '+url);
axios({
method,
url: BASE_URL + url,
data: data ? data : null,
headers: {
'Content-Type': 'application/json', 'Accept': '*/*'
}
}).then((response) => {
dispatch({ type: constants.TOGGLE_LOADER });
if (success) dispatch(success(response));
if (postProcessSuccess) postProcessSuccess(response);
}).catch(error => {
dispatch({ type: constants.TOGGLE_LOADER });
if (typeof(error.response) === "undefined") {
console.warn(error);
postProcessError('An error has ocurred');
} else {
if (error.response && error.response.status === 403)
dispatch(logoutUser());
if (error.response.data.message) {
if (postProcessError) postProcessError(error.reponse.data.message);
}
}
})
};
I try to test an Api I am working on. I also get the right response, but the dateformat seems to have changed
from 2018-11-27 18:03:44.000000000 +0000
to 2018-11-27T18:03:44.000Z
expected: [{"created_at"=>2018-11-27 18:03:44.000000000 +0000, "email"=>"jennettesaway...UfR7oeVa5.ZaWXce2qtn6Em2oSQuH6Iljqhx61BI7cvE3CG", "updated_at"=>2018-11-27 18:03:44.000000000 +0000}]
got: [{"created_at"=>"2018-11-27T18:03:44.000Z", "email"=>"georgene#champlin.biz...4$JlzdvIUfR7oeVa5.ZaWXce2qtn6Em2oSQuH6Iljqhx61BI7cvE3CG", "updated_at"=>"2018-11-27T18:03:44.000Z"}]
Here is the spec
RSpec.describe UsersController, type: :request do
let!(:user) { Fabricate(:user) }
let(:valid_attributes) { Fabricate.attributes_for :user }
let(:invalid_attributes) { Fabricate.attributes_for :invalid_user }
# set headers for authorization
#let(:headers) { { 'Authorization' => token_generator(user.id) } }
let(:headers) { valid_headers }
describe "GET #index" do
before(:each) do
#allow(request).to receive(:headers).and_return(headers)
end
it "returns a success response" do
get "/users", params: {}, headers: valid_headers
expect(json).to eq [user.as_json]
end
end
end
That is my controller
class UsersController < ApplicationController
skip_before_action :authorize_request, only: :create
before_action :set_user, only: [:show, :update, :destroy]
# GET /users
# GET /users.json
def index
#users = User.all
render json: #users
end
end
The json method
def json
JSON.parse(response.body)
end
I never had this issue before. What do I have to change?
I'm currently working on this tutorial: AngularJS Tutorial: Learn to Build Modern Web Apps with Angular and Rails
In the tutorial project, users can create Blog Posts and Comments for those Posts. So far I've been able to create Blog Posts (which are saved into database), but when I try to create a Comment for a Post, then I get the following error:
Started POST "/posts/16/comments.json" for 127.0.0.1 at 2015-02-15 08:32:40 +0200
Processing by CommentsController#create as JSON
Parameters: {"body"=>"6", "author"=>"user", "post_id"=>"16", "comment"=>{"body"=>"6"}}
Comments create action entered... 6
Completed 500 Internal Server Error in 9ms
NameError (undefined local variable or method `post' for #<CommentsController:0xb6036e50>):
app/controllers/comments_controller.rb:6:in `create'
Note: line “Comments create action entered... 6
” is logger.info message.
Screenshot
comments_controller.rb
class CommentsController < ApplicationController
def create
logger.info "Comments create action entered... " + params[:body]
comment = post.comments.create(comment_params)
respond_with post, comment
end
def upvote
comment = post.comments.find(params[:id])
comment.increment!(:upvotes)
respond_with post, comment
end
private
def comment_params
params.require(:comment).permit(:body)
end
end
posts_controller.rb
class PostsController < ApplicationController
def index
respond_with Post.all
end
def create
respond_with Post.create(post_params)
end
def show
logger.info "show action entered... " + params[:id]
#respond_with Post.find(params[:id])
#the code below works, the line above resulted in error: 406 (Not Acceptable)
render json: Post.find(params[:id]).to_json
end
def upvote
post = Post.find(params[:id])
post.increment!(:upvotes)
respond_with post
end
private
def post_params
logger.info "post_params entered..."
params.require(:post).permit(:link, :title)
end
end
In the PostsController's show action, I had previously changed line: respond_with Post.find(params[:id]) to: render json: Post.find(params[:id]).to_json because line: respond_with Post.find(params[:id]) produced error: GET http://0.0.0.0:3000/posts/4 406 (Not Acceptable)
I'm not sure, but the above issue might be related to internal error (500) message, why post is not found. Also if I use line: respond_with Post.find(params[:id]) in the PostsController then I still end up with the same problem with the Comment creation.
application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
respond_to :json
def angular
render 'layouts/application'
end
end
routes.rb
FlapperNews::Application.routes.draw do
root to: 'application#angular'
resources :posts, only: [:create, :index, :show] do
resources :comments, only: [:show, :create] do
member do
put '/upvote' => 'comments#upvote'
end
end
member do
put '/upvote' => 'posts#upvote'
end
end
end
Below is post.js file that does the Ajax calls in which the o.addComment function's $http.post call tries to create the Comment in the following way: $http.post('/posts/' + id + '/comments.json', comment);
angular.module('flapperNews').factory('posts', ['$http',
function($http){
var o = {
posts: []
};
o.getAll = function() {
return $http.get('/posts.json').success(function(data){
angular.copy(data, o.posts);
});
};
o.create = function(post) {
console.log("o.create");
return $http.post('/posts.json', post).success(function(data){
o.posts.push(data);
});
};
o.upvote = function(post) {
return $http.put('/posts/' + post.id + '/upvote.json')
.success(function(data){
post.upvotes += 1;
});
};
o.get = function(id) {
return $http.get('/posts/' + id).then(function(res){
return res.data;
});
};
o.addComment = function(id, comment) {
console.log("addComment " + id + ", comments " + comment )
return $http.post('/posts/' + id + '/comments.json', comment);
};
o.upvoteComment = function(post, comment) {
console.log("o.upvoteComment " + post.id + ", comments " +comment.id)
return $http.put('/posts/' + post.id + '/comments/'+ comment.id + '/upvote.json')
.success(function(data){
comment.upvotes += 1;
});
};
return o;
}
]);
app.js
angular.module('flapperNews', ['ui.router', 'templates'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home/_home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['posts', function(posts){
return posts.getAll();
}]
}
})
.state('posts', {
url: '/posts/{id}',
templateUrl: 'posts/_posts.html',
controller: 'PostsCtrl',
resolve: {
post: ['$stateParams', 'posts', function($stateParams, posts) {
console.log( "$stateParams.id " +$stateParams.id)
return posts.get($stateParams.id);
}]
}
})
$urlRouterProvider.otherwise('home')
}]);
My rails version is 4.0.2
Any help would be appreciated, because I've been struggling with the code for a couple of hours :-) Anyway, I'm glad that there is Stackoverflow forum where one can ask some advice :-)
First, this has nothing to do with angular. You don't have the post defined, so add:
post = Post.find params[:post_id]
also, i think your comment belongs_to post, you should set the post as the comment's post before saving the comment, so:
#comment.post = post
I am setting up an ember app that is backed by ruby on rails. I am running into issues with my sign in action using simple-auth and simple-auth-devise. I successfully retrieve the sessions authentication token and username when I submit a correct username and password, but I am still given a 401 access denied error and I can't figure out why. I suspect that it may have to do with the naming of email versus user_email and token vs user_token business. I am taking this code mostly from dayjot, so you'd think it would be trivial to track down this bug but I am having tons of issues finding the exact issue. Thanks for any help you can give me!
The exact error I get in the rails server is:
Started GET "/users/me" for 127.0.0.1 at 2015-02-17 10:25:31 -0600
Processing by UsersController#me as JSON
Parameters: {"user"=>{}}
Filter chain halted as :authenticate_user! rendered or redirected
Completed 401 Unauthorized in 5ms (Views: 4.1ms | ActiveRecord: 0.0ms)
In rails, this is my application controller:
This is my application controller:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
# protect_from_forgery with: :null_session
before_action :authenticate_user_from_token!, :handle_html
around_action :user_time_zone, if: :current_user
def index
render file: 'public/index.html'
end
protected
def authenticate_user!
render(json: {}, status: 401) unless current_user
end
private
def authenticate_user_from_token!
authenticate_with_http_token do |token, options|
user_email = options[:user_email].presence
user = user_email && User.find_by_email(user_email)
if user && Devise.secure_compare(user.authentication_token, token)
request.env['devise.skip_trackable'] = true
sign_in user, store: false
end
end
end
def user_time_zone(&block)
Time.use_zone(current_user.time_zone, &block)
end
# If this is a get request for HTML, just render the ember app.
def handle_html
render 'public/index.html' if request.method == 'GET' && request.headers['Accept'].match(/html/)
end
end
My sessions controller looks like this:
class SessionsController < Devise::SessionsController
def create
self.resource = warden.authenticate!(auth_options)
sign_in(resource_name, resource)
data = {
user_token: self.resource.authentication_token,
user_email: self.resource.email
}
render json: data, status: 201
end
def destroy
sign_out :user
render json: {}, status: :accepted
end
end
My serializers are these:
class UserSerializer < ActiveModel::Serializer
attributes :id, :password, :user_email, :email, :user_token, :passwordConfirmation
end
class UserSerializer < ActiveModel::Serializer
attributes :id, :email, :email_times, :last_export_time, :plan,
:plan_started, :plan_canceled, :plan_status, :trial_end,
:time_zone, :status, :created_at, :include_email_memory
end
My route is:
Rails.application.routes.draw do
# PLANS
post 'update_plan' => 'plans#update_plan', as: :update_plan
post 'update_card' => 'plans#update_card', as: :update_card
post 'cancel_plan' => 'plans#cancel_plan', as: :cancel_plan
# PASSWORDS
post 'start_password_reset' => 'users#start_password_reset'
put 'finish_password_reset' => 'users#finish_password_reset'
get 'password-reset' => 'application#index', as: :edit_user_password
# USERS
devise_for :users, controllers: { sessions: 'sessions' }, :skip => [:passwords]
resources :users, only: [:create, :update] do
get 'me' => 'users#me', on: :collection
end
# background processing admin
match "/delayed_job" => DelayedJobWeb, :anchor => false, via: [:get, :post]
# catch-all for ember app
get '*path' => 'application#index', :constraints => { :format => 'html' }
end
In the ember-cli app itself, my login controller is:
import Ember from "ember";
export default Ember.Controller.extend({
authenticator: 'simple-auth-authenticator:devise',
identification: null,
password: null,
error: null,
working: false,
actions: {
authenticate: function() {
var _this = this,
data = this.getProperties('identification', 'password');
this.setProperties({
working: true,
password: null,
error: null
});
this.get('session').authenticate('simple-auth-authenticator:devise', data).then(function() {
// authentication was successful
}, function(data) {
_this.set('working', false);
_this.set('error', data.error);
});
}
}
});
My application route is:
// ember-simple-auth
import Ember from "ember";
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
import Notify from 'ember-notify';
import ENV from 'front-end/config/environment';
export default Ember.Route.extend(ApplicationRouteMixin, {
beforeModel: function(transition) {
this._super(transition);
return this.setCurrentUser();
},
actions: {
sessionAuthenticationFailed: function(data) {
this.controllerFor('login').set('working', false);
this.controllerFor('login').set('loginErrorMessage', data.message);
},
sessionInvalidationSucceeded: function() {
this.transitionTo('index');
},
sessionAuthenticationSucceeded: function() {
var _this = this;
this.controllerFor('login').set('working', false);
this.setCurrentUser().then(function() {
if (_this.get('session.currentUser.mustSubscribe')) {
_this.transitionTo('plans');
} else {
_this.transitionTo('courses');
}
});
},
authorizationFailed: function() {
Notify.error("Could not be authenticated.. signing out.", {closeAfter: 5000});
this.get('session').invalidate();
}
},
setCurrentUser: function() {
var _this = this,
adapter = this.get('store').adapterFor('user');
if (this.get('session.isAuthenticated')) {
return new Ember.RSVP.Promise(function(resolve) {
adapter.ajax(ENV.APP.API_HOST + "/users/me", "GET", {}).then(
function(response){
_this.store.pushPayload(response);
var user = _this.store.find('user', response.user.id);
resolve(user);
},
function(response){
resolve(response);
}
);
}).then(function(user) {
_this.set('session.currentUser', user);
}, function() {
Notify.error("Could not be authenticated.. signing out.", {closeAfter: 5000});
_this.get('session').invalidate();
});
} else {
return new Ember.RSVP.Promise(function(resolve){ resolve(); });
}
}
});
Finally my login route is:
import Ember from "ember";
export default Ember.Route.extend({
activate: function() {
if (this.get('session').isAuthenticated) {
this.transitionTo('courses');
}
}
});
And Template is:
<form {{action 'register' on='submit'}} class='d-auth-form fade-in'>
{{#each errors}}
<div class="d-error">
{{this}}
</div>
{{/each}}
{{input placeholder='Email' type='email' value=email autocomplete='off' autocapitalize="none"}}
{{input placeholder='Password' type='password' value=password autocomplete='off'}}
<button type="submit" class='d-btn d-btn--success' {{bind-attr disabled=working}}>
{{#if working}}
Registering..
{{else}}
Sign up for DayJot for free
{{/if}}
</button>
<ul class='d-links'>
<li>{{#link-to 'login'}}Login to existing account{{/link-to}}</li>
</ul>
</form>
The important parts of environment.js are:
'simple-auth': {
crossOriginWhitelist: ['http://localhost:3000','http://localhost:4202','https://api.dayjot.com'],
authorizer: 'simple-auth-authorizer:devise',
authenticationRoute: 'index'
}
and
ENV['simple-auth-devise'] = {
serverTokenEndpoint: ENV.APP.API_HOST+'/users/sign_in',
identificationAttributeName: 'email'
}
Checkout the README - Ember Simple Auth Devise expects the token to be returned as token, you're using user_token however. Thus, the session will never actually be authenticated in Ember and the token won't be included in requests which leads to the 401 response.
I'm looking at this code, I can see that is says actions: show and index but where are the methods show and index??
http://github.com/railsdog/spree/blob/master/core/app/controllers/products_controller.rb
class ProductsController < Spree::BaseController
HTTP_REFERER_REGEXP = /^https?:\/\/[^\/]+\/t\/([a-z0-9\-\/]+\/)$/
#prepend_before_filter :reject_unknown_object, :only => [:show]
before_filter :load_data, :only => :show
resource_controller
helper :taxons
actions :show, :index
private
def load_data
load_object
#variants = Variant.active.find_all_by_product_id(#product.id,
:include => [:option_values, :images])
#product_properties = ProductProperty.find_all_by_product_id(#product.id,
:include => [:property])
#selected_variant = #variants.detect { |v| v.available? }
referer = request.env['HTTP_REFERER']
if referer && referer.match(HTTP_REFERER_REGEXP)
#taxon = Taxon.find_by_permalink($1)
end
end
def collection
#searcher = Spree::Config.searcher_class.new(params)
#products = #searcher.retrieve_products
end
def accurate_title
#product ? #product.name : nil
end
end
My guess is that the actions method is loaded with resource_controller as a module from the lib directory. Then calling the actions method creates the index and show methods.
The class inherits from Spree::BaseController and ActionController. Spree::BaseController has method action which takes method names as messages.