There is simple authentication from scratch and I want RESTfull API for login/logout/signup.
User signup works just as expected
curl -v -H 'Content-Type: application/json' -H 'Accept: application/vnd.greenapp.v1' -X POST http://localhost:3000/api/users/ -d "{\"user\":{\"email\":\"user1@example.com\",\"password\":\"secret\",\"password_confirmation\":\"secret\"}}"
However I couldn't make sessions#new and sessions#destroy to work. Here is my controller:
module Api
module V1
class SessionsController < ApplicationController
skip_before_filter :verify_authenticity_token,
:if => Proc.new { |c| c.request.format == 'application/json' }
respond_to :json
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
render status: :ok,
json: { success: true,
info: "Logged in sucessfully.",
data: { auth_token: user.auth_token } }
else
render status: :unprocessable_entity,
json: { success: false,
info: "Login failed." }
end
end
def destroy
cookies.delete(:auth_token)
render status: 200,
json: { success: true,
info: "Logged out sucessfully." }
end
end
end
end
Command for login
curl -v -H 'Content-Type: application/json' -H 'Accept: application/vnd.greenapp.v1' -X POST http://localhost:3000/api/sessions -d "{\"user\":{\"email\":\"user1@example.com\",\"password\":\"secret\"}}"
log:
Processing by Api::V1::SessionsController#create as JSON
Parameters: {"user"=>{"email"=>"user1@example.com", "password"=>"[FILTERED]"}, "session"=>{"user"=>{"email"=>"user1@example.com", "password"=>"[FILTERED]"}}}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."email" IS NULL LIMIT 1
Completed 422 Unprocessable Entity in 1ms (Views: 0.2ms | ActiveRecord: 0.4ms)
And do you have any idea how to handle logout? Should it be based on auth_token?
Try this
user = User.find_by_email(params[:user][:email])
if user && user.authenticate(params[:user][:password])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.