1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.OAuth.MFAController do
7 The model represents api to use Multi Factor authentications.
10 use Pleroma.Web, :controller
13 alias Pleroma.Web.Auth.TOTPAuthenticator
14 alias Pleroma.Web.OAuth.MFAView, as: View
15 alias Pleroma.Web.OAuth.OAuthController
16 alias Pleroma.Web.OAuth.Token
18 plug(:fetch_session when action in [:show, :verify])
19 plug(:fetch_flash when action in [:show, :verify])
22 Display form to input mfa code or recovery code.
24 def show(conn, %{"mfa_token" => mfa_token} = params) do
25 template = Map.get(params, "challenge_type", "totp")
29 |> render("#{template}.html", %{
31 redirect_uri: params["redirect_uri"],
32 state: params["state"]
37 Verification code and continue authorization.
39 def verify(conn, %{"mfa" => %{"mfa_token" => mfa_token} = mfa_params} = _) do
40 with {:ok, %{user: user, authorization: auth}} <- MFA.Token.validate(mfa_token),
41 {:ok, _} <- validates_challenge(user, mfa_params) do
43 |> OAuthController.after_create_authorization(auth, %{
45 "redirect_uri" => mfa_params["redirect_uri"],
46 "state" => mfa_params["state"]
52 |> put_flash(:error, "Two-factor authentication failed.")
53 |> put_status(:unauthorized)
59 Verification second step of MFA (or recovery) and returns access token.
62 POST /oauth/mfa/challenge
67 `mfa_token` - access token to check second step of mfa
68 `challenge_type` - 'totp' or 'recovery'
72 def challenge(conn, %{"mfa_token" => mfa_token} = params) do
73 with {:ok, app} <- Token.Utils.fetch_app(conn),
74 {:ok, %{user: user, authorization: auth}} <- MFA.Token.validate(mfa_token),
75 {:ok, _} <- validates_challenge(user, params),
76 {:ok, token} <- Token.exchange_token(app, auth) do
77 OAuthController.after_token_exchange(conn, %{user: user, token: token})
82 |> json(%{error: "Invalid code"})
87 defp validates_challenge(user, %{"challenge_type" => "totp", "code" => code} = _) do
88 TOTPAuthenticator.verify(code, user)
91 # Verify Recovery Code
92 defp validates_challenge(user, %{"challenge_type" => "recovery", "code" => code} = _) do
93 TOTPAuthenticator.verify_recovery_code(user, code)
96 defp validates_challenge(_, _), do: {:error, :unsupported_challenge_type}