about summary refs log tree commit diff
path: root/app/controllers/matrix/identity/v1/check_credentials_controller.rb
diff options
context:
space:
mode:
authorFire Demon <firedemon@creature.cafe>2020-09-07 19:07:46 -0500
committerFire Demon <firedemon@creature.cafe>2020-09-08 03:37:23 -0500
commit9344b77b95decedf5e5db7af99f6af4db2b27ffb (patch)
tree4523430aa66a6f50d6237dae5e4aacbd26b138d9 /app/controllers/matrix/identity/v1/check_credentials_controller.rb
parent57f74d8da4f4906fde07caa6cb05cbb824edcbc4 (diff)
[SSO, API] Add Matrix auth API (https://monsterware.dev/monsterpit/matrix-synapse-rest-password-provider)
Diffstat (limited to 'app/controllers/matrix/identity/v1/check_credentials_controller.rb')
-rw-r--r--app/controllers/matrix/identity/v1/check_credentials_controller.rb53
1 files changed, 53 insertions, 0 deletions
diff --git a/app/controllers/matrix/identity/v1/check_credentials_controller.rb b/app/controllers/matrix/identity/v1/check_credentials_controller.rb
new file mode 100644
index 000000000..1969d354b
--- /dev/null
+++ b/app/controllers/matrix/identity/v1/check_credentials_controller.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+class Matrix::Identity::V1::CheckCredentialsController < Matrix::BaseController
+  def create
+    matrix_profile = matrix_profile_json
+    return render json: fail_json, status: 403 if matrix_profile.blank?
+
+    render json: matrix_profile
+  rescue ActionController::ParameterMissing, ActiveRecord::RecordNotFound
+    render json: fail_json, status: 403
+  end
+
+  private
+
+  def resource_params
+    params.require(:user).permit(:id, :password)
+  end
+
+  def matrix_domains
+    ENV.fetch('MATRIX_AUTH_DOMAINS', '').delete(',').split.to_set
+  end
+
+  def matrix_profile_json
+    user_params = resource_params
+    return unless user_params[:id].present? && user_params[:password].present? && user_params[:id][0] == '@'
+
+    (username, domain) = user_params[:id].downcase.split(':', 2)
+    return unless matrix_domains.include?(domain)
+
+    user = User.find_by_lower_username!(username[1..-1])
+    return unless user.valid_password?(user_params[:password])
+
+    {
+      auth: {
+        success: true,
+        mxid: user_params[:id],
+        profile: {
+          display_name: user.account.display_name.presence || user.username,
+          three_pids: [
+            {
+              medium: 'email',
+              address: user.email,
+            },
+          ]
+        }
+      }
+    }
+  end
+
+  def fail_json
+    { auth: { success: false } }
+  end
+end