1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.OAuth.OAuthController do
6 use Pleroma.Web, :controller
8 alias Pleroma.Helpers.UriHelper
11 alias Pleroma.Registration
14 alias Pleroma.Web.Auth.WrapperAuthenticator, as: Authenticator
15 alias Pleroma.Web.OAuth.App
16 alias Pleroma.Web.OAuth.Authorization
17 alias Pleroma.Web.OAuth.MFAController
18 alias Pleroma.Web.OAuth.MFAView
19 alias Pleroma.Web.OAuth.OAuthView
20 alias Pleroma.Web.OAuth.Scopes
21 alias Pleroma.Web.OAuth.Token
22 alias Pleroma.Web.OAuth.Token.Strategy.RefreshToken
23 alias Pleroma.Web.OAuth.Token.Strategy.Revoke, as: RevokeToken
24 alias Pleroma.Web.Plugs.RateLimiter
25 alias Pleroma.Web.Utils.Params
29 if Pleroma.Config.oauth_consumer_enabled?(), do: plug(Ueberauth)
36 plug(RateLimiter, [name: :authentication] when action == :create_authorization)
38 action_fallback(Pleroma.Web.OAuth.FallbackController)
40 @oob_token_redirect_uri "urn:ietf:wg:oauth:2.0:oob"
42 # Note: this definition is only called from error-handling methods with `conn.params` as 2nd arg
43 def authorize(%Plug.Conn{} = conn, %{"authorization" => _} = params) do
44 {auth_attrs, params} = Map.pop(params, "authorization")
45 authorize(conn, Map.merge(params, auth_attrs))
48 def authorize(%Plug.Conn{assigns: %{token: %Token{}}} = conn, %{"force_login" => _} = params) do
49 if Params.truthy_param?(params["force_login"]) do
50 do_authorize(conn, params)
52 handle_existing_authorization(conn, params)
56 # Note: the token is set in oauth_plug, but the token and client do not always go together.
57 # For example, MastodonFE's token is set if user requests with another client,
58 # after user already authorized to MastodonFE.
59 # So we have to check client and token.
61 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
62 %{"client_id" => client_id} = params
64 with %Token{} = t <- Repo.get_by(Token, token: token.token) |> Repo.preload(:app),
65 ^client_id <- t.app.client_id do
66 handle_existing_authorization(conn, params)
68 _ -> do_authorize(conn, params)
72 def authorize(%Plug.Conn{} = conn, params), do: do_authorize(conn, params)
74 defp maybe_remove_token(%Plug.Conn{assigns: %{token: %{app: id}}} = conn, %App{id: id}) do
78 defp maybe_remove_token(conn, _app) do
80 |> assign(:token, nil)
83 defp do_authorize(%Plug.Conn{} = conn, params) do
84 app = Repo.get_by(App, client_id: params["client_id"])
85 conn = maybe_remove_token(conn, app)
86 available_scopes = (app && app.scopes) || []
87 scopes = Scopes.fetch_scopes(params, available_scopes)
89 # if we already have a token for this specific setup, we can use that
90 with false <- Params.truthy_param?(params["force_login"]),
92 %{assigns: %{user: %Pleroma.User{} = user}} <- conn,
93 {:ok, %Token{} = token} <- Token.get_preexisting_by_app_and_user(app, user),
94 true <- scopes == token.scopes do
95 token = Repo.preload(token, :app)
98 |> assign(:token, token)
99 |> handle_existing_authorization(params)
103 with %{assigns: %{user: %User{} = user}} <- conn do
116 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
117 render(conn, Authenticator.auth_template(), %{
119 app: app && Map.delete(app, :client_secret),
120 response_type: params["response_type"],
121 client_id: params["client_id"],
122 available_scopes: available_scopes,
124 redirect_uri: params["redirect_uri"],
125 state: params["state"],
127 view_module: OAuthView
132 defp handle_existing_authorization(
133 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
134 %{"redirect_uri" => @oob_token_redirect_uri}
136 render(conn, "oob_token_exists.html", %{token: token})
139 defp handle_existing_authorization(
140 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
143 app = Repo.preload(token, :app).app
146 if is_binary(params["redirect_uri"]) do
147 params["redirect_uri"]
149 default_redirect_uri(app)
152 if redirect_uri in String.split(app.redirect_uris) do
153 redirect_uri = redirect_uri(conn, redirect_uri)
154 url_params = %{access_token: token.token}
155 url_params = Maps.put_if_present(url_params, :state, params["state"])
156 url = UriHelper.modify_uri_params(redirect_uri, url_params)
157 redirect(conn, external: url)
160 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
161 |> redirect(external: redirect_uri(conn, redirect_uri))
165 def create_authorization(_, _, opts \\ [])
167 def create_authorization(%Plug.Conn{assigns: %{user: %User{} = user}} = conn, params, []) do
168 create_authorization(conn, params, user: user)
171 def create_authorization(%Plug.Conn{} = conn, %{"authorization" => _} = params, opts) do
172 with {:ok, auth, user} <- do_create_authorization(conn, params, opts[:user]),
173 {:mfa_required, _, _, false} <- {:mfa_required, user, auth, MFA.require?(user)} do
174 after_create_authorization(conn, auth, params)
177 handle_create_authorization_error(conn, error, params)
181 def after_create_authorization(%Plug.Conn{} = conn, %Authorization{} = auth, %{
182 "authorization" => %{"redirect_uri" => @oob_token_redirect_uri}
184 # Enforcing the view to reuse the template when calling from other controllers
186 |> put_view(OAuthView)
187 |> render("oob_authorization_created.html", %{auth: auth, view_module: OAuthView})
190 def after_create_authorization(%Plug.Conn{} = conn, %Authorization{} = auth, %{
191 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
193 app = Repo.preload(auth, :app).app
195 # An extra safety measure before we redirect (also done in `do_create_authorization/2`)
196 if redirect_uri in String.split(app.redirect_uris) do
197 redirect_uri = redirect_uri(conn, redirect_uri)
198 url_params = %{code: auth.token}
199 url_params = Maps.put_if_present(url_params, :state, auth_attrs["state"])
200 url = UriHelper.modify_uri_params(redirect_uri, url_params)
201 redirect(conn, external: url)
204 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
205 |> redirect(external: redirect_uri(conn, redirect_uri))
209 defp handle_create_authorization_error(
211 {:error, scopes_issue},
212 %{"authorization" => _} = params
214 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
215 # Per https://github.com/tootsuite/mastodon/blob/
216 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
218 |> put_flash(:error, dgettext("errors", "This action is outside the authorized scopes"))
219 |> put_status(:unauthorized)
223 defp handle_create_authorization_error(
225 {:account_status, :confirmation_pending},
226 %{"authorization" => _} = params
229 |> put_flash(:error, dgettext("errors", "Your login is missing a confirmed e-mail address"))
230 |> put_status(:forbidden)
234 defp handle_create_authorization_error(
236 {:mfa_required, user, auth, _},
239 {:ok, token} = MFA.Token.create(user, auth)
242 "mfa_token" => token.token,
243 "redirect_uri" => params["authorization"]["redirect_uri"],
244 "state" => params["authorization"]["state"]
247 MFAController.show(conn, data)
250 defp handle_create_authorization_error(
252 {:account_status, :password_reset_pending},
253 %{"authorization" => _} = params
256 |> put_flash(:error, dgettext("errors", "Password reset is required"))
257 |> put_status(:forbidden)
261 defp handle_create_authorization_error(
263 {:account_status, :deactivated},
264 %{"authorization" => _} = params
267 |> put_flash(:error, dgettext("errors", "Your account is currently disabled"))
268 |> put_status(:forbidden)
272 defp handle_create_authorization_error(%Plug.Conn{} = conn, error, %{"authorization" => _}) do
273 Authenticator.handle_error(conn, error)
276 @doc "Renew access_token with refresh_token"
279 %{"grant_type" => "refresh_token", "refresh_token" => token} = _params
281 with {:ok, app} <- Token.Utils.fetch_app(conn),
282 {:ok, %{user: user} = token} <- Token.get_by_refresh_token(app, token),
283 {:ok, token} <- RefreshToken.grant(token) do
284 after_token_exchange(conn, %{user: user, token: token})
286 _error -> render_invalid_credentials_error(conn)
290 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "authorization_code"} = params) do
291 with {:ok, app} <- Token.Utils.fetch_app(conn),
292 fixed_token = Token.Utils.fix_padding(params["code"]),
293 {:ok, auth} <- Authorization.get_by_token(app, fixed_token),
294 %User{} = user <- User.get_cached_by_id(auth.user_id),
295 {:ok, token} <- Token.exchange_token(app, auth) do
296 after_token_exchange(conn, %{user: user, token: token})
299 handle_token_exchange_error(conn, error)
305 %{"grant_type" => "password"} = params
307 with {:ok, %User{} = user} <- Authenticator.get_user(conn),
308 {:ok, app} <- Token.Utils.fetch_app(conn),
309 requested_scopes <- Scopes.fetch_scopes(params, app.scopes),
310 {:ok, token} <- login(user, app, requested_scopes) do
311 after_token_exchange(conn, %{user: user, token: token})
314 handle_token_exchange_error(conn, error)
320 %{"grant_type" => "password", "name" => name, "password" => _password} = params
324 |> Map.delete("name")
325 |> Map.put("username", name)
327 token_exchange(conn, params)
330 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "client_credentials"} = _params) do
331 with {:ok, app} <- Token.Utils.fetch_app(conn),
332 {:ok, auth} <- Authorization.create_authorization(app, %User{}),
333 {:ok, token} <- Token.exchange_token(app, auth) do
334 after_token_exchange(conn, %{token: token})
337 handle_token_exchange_error(conn, :invalid_credentails)
342 def token_exchange(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
344 def after_token_exchange(%Plug.Conn{} = conn, %{token: _token} = view_params) do
346 |> json(OAuthView.render("token.json", view_params))
349 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:mfa_required, user, auth, _}) do
351 |> put_status(:forbidden)
352 |> json(build_and_response_mfa_token(user, auth))
355 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:account_status, :deactivated}) do
359 "Your account is currently disabled",
361 "account_is_disabled"
365 defp handle_token_exchange_error(
367 {:account_status, :password_reset_pending}
372 "Password reset is required",
374 "password_reset_required"
378 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:account_status, :confirmation_pending}) do
382 "Your login is missing a confirmed e-mail address",
384 "missing_confirmed_email"
388 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:account_status, :approval_pending}) do
392 "Your account is awaiting approval.",
398 defp handle_token_exchange_error(%Plug.Conn{} = conn, _error) do
399 render_invalid_credentials_error(conn)
402 def token_revoke(%Plug.Conn{} = conn, %{"token" => token}) do
403 with {:ok, %Token{} = oauth_token} <- Token.get_by_token(token),
404 {:ok, _oauth_token} <- RevokeToken.revoke(oauth_token) do
408 # RFC 7009: invalid tokens [in the request] do not cause an error response
413 def token_revoke(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
415 # Response for bad request
416 defp bad_request(%Plug.Conn{} = conn, _) do
417 render_error(conn, :internal_server_error, "Bad request")
420 @doc "Prepares OAuth request to provider for Ueberauth"
421 def prepare_request(%Plug.Conn{} = conn, %{
422 "provider" => provider,
423 "authorization" => auth_attrs
427 |> Scopes.fetch_scopes([])
428 |> Scopes.to_string()
432 |> Map.delete("scopes")
433 |> Map.put("scope", scope)
438 |> Map.drop(~w(scope scopes client_id redirect_uri))
439 |> Map.put("state", state)
441 # Handing the request to Ueberauth
442 redirect(conn, to: Routes.o_auth_path(conn, :request, provider, params))
445 def request(%Plug.Conn{} = conn, params) do
447 if params["provider"] do
448 dgettext("errors", "Unsupported OAuth provider: %{provider}.",
449 provider: params["provider"]
452 dgettext("errors", "Bad OAuth request.")
456 |> put_flash(:error, message)
460 def callback(%Plug.Conn{assigns: %{ueberauth_failure: failure}} = conn, params) do
461 params = callback_params(params)
462 messages = for e <- Map.get(failure, :errors, []), do: e.message
463 message = Enum.join(messages, "; ")
468 dgettext("errors", "Failed to authenticate: %{message}.", message: message)
470 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
473 def callback(%Plug.Conn{} = conn, params) do
474 params = callback_params(params)
476 with {:ok, registration} <- Authenticator.get_registration(conn) do
477 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
479 case Repo.get_assoc(registration, :user) do
481 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
484 registration_params =
485 Map.merge(auth_attrs, %{
486 "nickname" => Registration.nickname(registration),
487 "email" => Registration.email(registration)
491 |> put_session_registration_id(registration.id)
492 |> registration_details(%{"authorization" => registration_params})
496 Logger.debug(inspect(["OAUTH_ERROR", error, conn.assigns]))
499 |> put_flash(:error, dgettext("errors", "Failed to set up user account."))
500 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
504 defp callback_params(%{"state" => state} = params) do
505 Map.merge(params, Jason.decode!(state))
508 def registration_details(%Plug.Conn{} = conn, %{"authorization" => auth_attrs}) do
509 render(conn, "register.html", %{
510 client_id: auth_attrs["client_id"],
511 redirect_uri: auth_attrs["redirect_uri"],
512 state: auth_attrs["state"],
513 scopes: Scopes.fetch_scopes(auth_attrs, []),
514 nickname: auth_attrs["nickname"],
515 email: auth_attrs["email"]
519 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "connect"} = params) do
520 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
521 %Registration{} = registration <- Repo.get(Registration, registration_id),
522 {_, {:ok, auth, _user}} <-
523 {:create_authorization, do_create_authorization(conn, params)},
524 %User{} = user <- Repo.preload(auth, :user).user,
525 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
527 |> put_session_registration_id(nil)
528 |> after_create_authorization(auth, params)
530 {:create_authorization, error} ->
531 {:register, handle_create_authorization_error(conn, error, params)}
534 {:register, :generic_error}
538 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "register"} = params) do
539 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
540 %Registration{} = registration <- Repo.get(Registration, registration_id),
541 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
543 |> put_session_registration_id(nil)
544 |> create_authorization(
549 {:error, changeset} ->
551 Enum.map(changeset.errors, fn {field, {error, _}} ->
559 "ap_id has already been taken",
560 "nickname has already been taken"
564 |> put_status(:forbidden)
565 |> put_flash(:error, "Error: #{message}.")
566 |> registration_details(params)
569 {:register, :generic_error}
573 defp do_create_authorization(conn, auth_attrs, user \\ nil)
575 defp do_create_authorization(
580 "client_id" => client_id,
581 "redirect_uri" => redirect_uri
586 with {_, {:ok, %User{} = user}} <-
587 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
588 %App{} = app <- Repo.get_by(App, client_id: client_id),
589 true <- redirect_uri in String.split(app.redirect_uris),
590 requested_scopes <- Scopes.fetch_scopes(auth_attrs, app.scopes),
591 {:ok, auth} <- do_create_authorization(user, app, requested_scopes) do
596 defp do_create_authorization(%User{} = user, %App{} = app, requested_scopes)
597 when is_list(requested_scopes) do
598 with {:account_status, :active} <- {:account_status, User.account_status(user)},
599 {:ok, scopes} <- validate_scopes(app, requested_scopes),
600 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
605 # Note: intended to be a private function but opened for AccountController that logs in on signup
606 @doc "If checks pass, creates authorization and token for given user, app and requested scopes."
607 def login(%User{} = user, %App{} = app, requested_scopes) when is_list(requested_scopes) do
608 with {:ok, auth} <- do_create_authorization(user, app, requested_scopes),
609 {:mfa_required, _, _, false} <- {:mfa_required, user, auth, MFA.require?(user)},
610 {:ok, token} <- Token.exchange_token(app, auth) do
615 # Special case: Local MastodonFE
616 defp redirect_uri(%Plug.Conn{} = conn, "."), do: Routes.auth_url(conn, :login)
618 defp redirect_uri(%Plug.Conn{}, redirect_uri), do: redirect_uri
620 defp get_session_registration_id(%Plug.Conn{} = conn), do: get_session(conn, :registration_id)
622 defp put_session_registration_id(%Plug.Conn{} = conn, registration_id),
623 do: put_session(conn, :registration_id, registration_id)
625 defp build_and_response_mfa_token(user, auth) do
626 with {:ok, token} <- MFA.Token.create(user, auth) do
627 MFAView.render("mfa_response.json", %{token: token, user: user})
631 @spec validate_scopes(App.t(), map() | list()) ::
632 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
633 defp validate_scopes(%App{} = app, params) when is_map(params) do
634 requested_scopes = Scopes.fetch_scopes(params, app.scopes)
635 validate_scopes(app, requested_scopes)
638 defp validate_scopes(%App{} = app, requested_scopes) when is_list(requested_scopes) do
639 Scopes.validate(requested_scopes, app.scopes)
642 def default_redirect_uri(%App{} = app) do
648 defp render_invalid_credentials_error(conn) do
649 render_error(conn, :bad_request, "Invalid credentials")