Skip to content

Instantly share code, notes, and snippets.

@johnjohndoe
Forked from Bomadeno/registrations_controller.rb
Last active February 12, 2020 04:43
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save johnjohndoe/6248746 to your computer and use it in GitHub Desktop.
Save johnjohndoe/6248746 to your computer and use it in GitHub Desktop.
class Api::RegistrationsController < Api::BaseController
respond_to :json
def create
user = User.new(params[:user])
if user.save
render json: user.as_json(auth_token: user.authentication_token, email: user.email), status: :created
return
else
warden.custom_failure!
render json: user.errors, status: :unprocessable_entity
end
end
end
class Api::SessionsController < Api::BaseController
before_filter :authenticate_user!, except: [:create]
before_filter :ensure_user_login_param_exists, only: [:create]
before_filter :ensure_email_param_exists, only: [:create]
before_filter :ensure_password_param_exists, only: [:create]
respond_to :json
def create
resource = User.find_for_database_authentication(email: params[:user_login][:email])
return invalid_login_attempt unless resource
if resource.valid_password?(params[:user_login][:password])
sign_in(:user, resource)
resource.ensure_authentication_token!
render json: { success: true, auth_token: resource.authentication_token, email: resource.email }, status: :created
return
end
invalid_login_attempt
end
def destroy
current_user.reset_authentication_token
render json: { success: true }, status: :ok
end
protected
def ensure_user_login_param_exists
ensure_param_exists :user_login
end
def ensure_email_param_exists
ensure_param_exists :email
end
def ensure_password_param_exists
ensure_param_exists :password
end
def ensure_param_exists(param)
return unless params[param].blank?
render json:{ success: false, message: "Missing #{param} parameter"}, status: :unprocessable_entity
end
def invalid_login_attempt
render json: { success: false, message: "Error with your login or password"}, status: :unauthorized
end
end
@alexventuraio
Copy link

Maybe I'm wrong but the ensure_params it's a bit complex. As long as user_login have the email and password nested inside the hash params[:email].blank? will not pass the bf.

The ensure_params_exists have to check the second level params.

You're right, validation fails!

{
    "success": false,
    "message": "Missing email parameter"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment