I have the following code in my sessions_controller.rb
file:
module V1
class Users::SessionsController < Devise::SessionsController
# POST /sign_in
def new
user = User.find_by_email(params[:user][:email]) if params[:user]
if user && user.valid_password?(params[:user][:password])
sign_in(:user, user)
current_user.remember_me!
head 200
else
render status: 200, json: {errors: ["Incorrect email / username or password."]}.as_json
end
end
# ...
end
end
The above code seems to work fine, however, after signing in and visiting my /posts
route and I get an error telling me "You need to sign in or sign up before continuing."
The structure of my app:
controllers
├── v1
| ├── users
| | ├── registrations_controller.rb
| | ├── sessions_controller.rb
| | ├── api_controller.rb
| ├── posts_controller.rb
application_controller.rb
In my posts controller I have set before_action :authenticate_v1_user!
. I'm using rails to build an API and I'm testing the above routes by sending requests from a tool called Postman. I've also tried testing from my AngularJS app (on a different subdomain than the API). Why would I get an error telling me to log in when I just logged in by sending the correct credentials to /sign_in
. Are there special considerations since this is just an API?
EDIT:
My user.rb
file:
class User < ActiveRecord::Base
has_many :posts
has_many :comments
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :email, presence: true, uniqueness: true
validates :password, confirmation: true, presence: true
validates :password_confirmation, presence: true
end
My routes.rb
file:
Rails.application.routes.draw do
devise_for :users, controllers: { sessions: "users/sessions", registrations: "users/registrations" }
devise_scope :user do
post "sign_in", to: "v1/users/sessions#new"
delete "sign_out", to: "v1/users/sessions#destroy"
post "register", to: "v1/users/registrations#create"
end
namespace :v1, defaults: {format: 'json'} do
devise_for :users, controllers: { sessions: "users/sessions", registrations: "users/registrations" }
# Routes for posts
get 'posts(/index)', :to => 'posts#index'
post 'posts/create'
delete 'posts/:id', :to => 'posts#destroy'
get 'posts/show'
put 'posts/:id', :to => 'posts#update'
end
end