Rails: External API Integration using RestClient (

2019-08-24 18:18发布

I am building a digital library, and I have completed a lot of the functionalities needed. I am currently having an issue with integrating the digital library with a Learning Management System (LMS).

I already have an admin authentication system for the digital library using the Devise gem. My goal is to allow users who want to access the digital library to login to the digital library using their Learning Management System (LMS) credentials (username and password).

I have been provided with the Login API endpoint and other needed parameters of the Learning Management System (LMS), and I have created the User Model, the Sessions Controller and the Sessions View Templates.

I am currently using the RestClient Gem for the API call, but I having an error 400 Bad Request. The login works (when 200), but when the username or password is not correct (when 422) it will throw an error 400 Bad Request. I have tried to debug the issue but no success yet.

Below is my source code

Sessions Controller

require 'rest-client'

class SessionsController < ApplicationController
  def new
  end

  def create
    response = RestClient::Request.execute(
      method: :post,
      url: 'https://newapi.example.com/token',
      payload: { 'username': params[:username],
                 'password': params[:password],
                 'grant_type':'password' },
      headers: { apiCode: '93de0db8-333b-4f478-aa92-2b43cdb7aa9f' }
    )

    case response.code
    when 200
      [:success, JSON.parse(response.to_str)]
      redirect_to root_url, notice: 'Logged in!'
    when 422
      [:unprocessable_entity, JSON.parse(response.to_str)]
      flash.now[:alert] = 'Email or password is invalid'
      render 'new'
    else
      raise "Invalid response #{response.to_str} received."
    end
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url, notice: 'Logged out!'
  end
end

Sessions New View

<p id=”alert”><%= alert %></p>
<h1>Login</h1>
<%= form_tag sessions_path do %>
  <div class="field">
    <%= label_tag :username %>
    <%= text_field_tag :username %>
  </div>
  <div class="field">
    <%= label_tag :password %>
    <%= password_field_tag :password %>
  </div>
  <div class="actions">
    <%= submit_tag 'Login' %>
  </div>
<% end %>

User Model

class User < ApplicationRecord
  has_secure_password

  validates :username, presence: true, uniqueness: true
end

Any form of help with code samples will be greatly appreciated. I am also open to providing more information about this integration if required. Thank you in advance.

0条回答
登录 后发表回答