Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ test:
run:
@bin/rails server
migrate:
@bin/rails db:migrate
@bin/rails db:migrate
create:
@bin/rails db:create
15 changes: 15 additions & 0 deletions app/controllers/api/v1/auth_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@ def register
end
end

def login
user = User.find_by(email: user_params[:email])

if user&.authenticate(user_params[:password])
session = Session.create!(user_id: user.id)

render json: {
token: session.token,
user_id: user.id
}, status: :ok
else
render json: { error: "Invalid email or password" }, status: :unauthorized
end
end

private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
Expand Down
1 change: 1 addition & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
# V1 Namespace
namespace :auth do
post :register
post :login
end

# Root
Expand Down
68 changes: 68 additions & 0 deletions test/integration/api/v1/api_v1_auth_login_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
require "test_helper"

class ApiV1AuthLoginTest < ActionDispatch::IntegrationTest
def setup
Session.delete_all
User.delete_all
end

test "username and password provided is correct" do
user = User.create!(email: "test@example.com", password: "password")

post "/api/v1/auth/login", params: {
user: {
email: "test@example.com",
password: "password"
}
}

assert_response :success
body = JSON.parse(response.body)
assert body["token"].present?, "expected response to include a session token"
assert_equal user.id, body["user_id"]
end

test "session is created upon successful login" do
user = User.create!(email: "test@example.com", password: "password")

assert_difference "Session.count", 1 do
post "/api/v1/auth/login", params: {
user: {
email: "test@example.com",
password: "password"
}
}
end
end

test "incorrect password" do
User.create!(email: "test@example.com", password: "password")

post "/api/v1/auth/login", params: {
user: {
email: "test@example.com",
password: "wrongpassword"
}
}

assert_response :unauthorized
end

test "non-existent email" do
post "/api/v1/auth/login", params: {
user: {
email: "nonexistent@example.com",
password: "password"
}
}

assert_response :unauthorized
end

test "missing parameters" do
post "/api/v1/auth/login", params: {}

assert_response :unauthorized
assert_equal "Invalid email or password", JSON.parse(response.body)["error"]
end
end