0945ebb12cd26351904d5254dd399ffa45034368
[anni] / lib / pleroma / web / mongoose_im / mongoose_im_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.MongooseIM.MongooseIMController do
6   use Pleroma.Web, :controller
7
8   alias Pleroma.Repo
9   alias Pleroma.User
10   alias Pleroma.Web.Plugs.AuthenticationPlug
11   alias Pleroma.Web.Plugs.RateLimiter
12
13   plug(RateLimiter, [name: :authentication] when action in [:user_exists, :check_password])
14   plug(RateLimiter, [name: :authentication, params: ["user"]] when action == :check_password)
15
16   def user_exists(conn, %{"user" => username}) do
17     with %User{} <- Repo.get_by(User, nickname: username, local: true, is_active: true) do
18       conn
19       |> json(true)
20     else
21       _ ->
22         conn
23         |> put_status(:not_found)
24         |> json(false)
25     end
26   end
27
28   def check_password(conn, %{"user" => username, "pass" => password}) do
29     with %User{password_hash: password_hash, is_active: true} <-
30            Repo.get_by(User, nickname: username, local: true),
31          true <- AuthenticationPlug.checkpw(password, password_hash) do
32       conn
33       |> json(true)
34     else
35       false ->
36         conn
37         |> put_status(:forbidden)
38         |> json(false)
39
40       _ ->
41         conn
42         |> put_status(:not_found)
43         |> json(false)
44     end
45   end
46 end