summaryrefslogtreecommitdiff
path: root/lib/pleroma/web/mongooseim/mongoose_im_controller.ex
blob: ee24a61c0cd6dc4e0348dbc432d3084a655daff1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Web.MongooseIM.MongooseIMController do
  use Pleroma.Web, :controller

  alias Comeonin.Pbkdf2
  alias Pleroma.Plugs.RateLimiter
  alias Pleroma.Repo
  alias Pleroma.User

  plug(RateLimiter, [name: :authentication] when action in [:user_exists, :check_password])
  plug(RateLimiter, [name: :authentication, params: ["user"]] when action == :check_password)

  def user_exists(conn, %{"user" => username}) do
    with %User{} <- Repo.get_by(User, nickname: username, local: true) do
      conn
      |> json(true)
    else
      _ ->
        conn
        |> put_status(:not_found)
        |> json(false)
    end
  end

  def check_password(conn, %{"user" => username, "pass" => password}) do
    with %User{password_hash: password_hash} <-
           Repo.get_by(User, nickname: username, local: true, deactivated: false),
         true <- Pbkdf2.checkpw(password, password_hash) do
      conn
      |> json(true)
    else
      false ->
        conn
        |> put_status(:forbidden)
        |> json(false)

      _ ->
        conn
        |> put_status(:not_found)
        |> json(false)
    end
  end
end