diff --git a/Makefile b/Makefile index 623ddf1..3957151 100644 --- a/Makefile +++ b/Makefile @@ -12,4 +12,6 @@ test: run: @bin/rails server migrate: - @bin/rails db:migrate \ No newline at end of file + @bin/rails db:migrate +create: + @bin/rails db:create \ No newline at end of file diff --git a/app/controllers/api/v1/auth_controller.rb b/app/controllers/api/v1/auth_controller.rb index 462897c..8122817 100644 --- a/app/controllers/api/v1/auth_controller.rb +++ b/app/controllers/api/v1/auth_controller.rb @@ -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) diff --git a/config/routes.rb b/config/routes.rb index 542ed34..d521cc4 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -10,6 +10,7 @@ # V1 Namespace namespace :auth do post :register + post :login end # Root diff --git a/test/integration/api/v1/api_v1_auth_login_test.rb b/test/integration/api/v1/api_v1_auth_login_test.rb new file mode 100644 index 0000000..79b7a6d --- /dev/null +++ b/test/integration/api/v1/api_v1_auth_login_test.rb @@ -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