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.AuthHelper
9 alias Pleroma.Helpers.UriHelper
12 alias Pleroma.Registration
15 alias Pleroma.Web.Auth.WrapperAuthenticator, as: Authenticator
16 alias Pleroma.Web.OAuth.App
17 alias Pleroma.Web.OAuth.Authorization
18 alias Pleroma.Web.OAuth.MFAController
19 alias Pleroma.Web.OAuth.MFAView
20 alias Pleroma.Web.OAuth.OAuthView
21 alias Pleroma.Web.OAuth.Scopes
22 alias Pleroma.Web.OAuth.Token
23 alias Pleroma.Web.OAuth.Token.Strategy.RefreshToken
24 alias Pleroma.Web.OAuth.Token.Strategy.Revoke, as: RevokeToken
25 alias Pleroma.Web.Plugs.RateLimiter
26 alias Pleroma.Web.Utils.Params
30 if Pleroma.Config.oauth_consumer_enabled?(), do: plug(Ueberauth)
37 plug(RateLimiter, [name: :authentication] when action == :create_authorization)
39 action_fallback(Pleroma.Web.OAuth.FallbackController)
41 @oob_token_redirect_uri "urn:ietf:wg:oauth:2.0:oob"
43 # Note: this definition is only called from error-handling methods with `conn.params` as 2nd arg
44 def authorize(%Plug.Conn{} = conn, %{"authorization" => _} = params) do
45 {auth_attrs, params} = Map.pop(params, "authorization")
46 authorize(conn, Map.merge(params, auth_attrs))
49 def authorize(%Plug.Conn{assigns: %{token: %Token{}}} = conn, %{"force_login" => _} = params) do
50 if Params.truthy_param?(params["force_login"]) do
51 do_authorize(conn, params)
53 handle_existing_authorization(conn, params)
57 # Note: the token is set in oauth_plug, but the token and client do not always go together.
58 # For example, MastodonFE's token is set if user requests with another client,
59 # after user already authorized to MastodonFE.
60 # So we have to check client and token.
62 %Plug.Conn{assigns: %{token: %Token{} = token, user: %User{} = user}} = conn,
63 %{"client_id" => client_id} = params
65 with %Token{} = t <- Repo.get_by(Token, token: token.token) |> Repo.preload(:app),
66 ^client_id <- t.app.client_id do
67 handle_existing_authorization(conn, params)
70 maybe_reuse_token(conn, params, user.id)
74 def authorize(%Plug.Conn{} = conn, params) do
75 # if we have a user in the session, attempt to authenticate as them
76 # otherwise show the login form
77 maybe_reuse_token(conn, params, AuthHelper.get_session_user(conn))
80 defp maybe_reuse_token(conn, params, user_id) when is_binary(user_id) do
81 with %User{} = user <- User.get_cached_by_id(user_id),
82 %App{} = app <- Repo.get_by(App, client_id: params["client_id"]),
83 {:ok, %Token{} = token} <- Token.get_preeexisting_by_app_and_user(app, user),
84 {:ok, %Authorization{} = auth} <-
85 Authorization.get_preeexisting_by_app_and_user(app, user) do
87 |> assign(:token, token)
88 |> after_create_authorization(auth, %{"authorization" => params})
90 _ -> do_authorize(conn, params)
94 defp maybe_reuse_token(conn, params, _user), do: do_authorize(conn, params)
96 defp do_authorize(%Plug.Conn{} = conn, params) do
97 app = Repo.get_by(App, client_id: params["client_id"])
98 available_scopes = (app && app.scopes) || []
99 scopes = Scopes.fetch_scopes(params, available_scopes)
102 with %{assigns: %{user: %User{} = user}} <- conn do
115 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
116 render(conn, Authenticator.auth_template(), %{
118 app: app && Map.delete(app, :client_secret),
119 response_type: params["response_type"],
120 client_id: params["client_id"],
121 available_scopes: available_scopes,
123 redirect_uri: params["redirect_uri"],
124 state: params["state"],
126 view_module: OAuthView
130 defp handle_existing_authorization(
131 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
132 %{"redirect_uri" => @oob_token_redirect_uri}
134 render(conn, "oob_token_exists.html", %{token: token})
137 defp handle_existing_authorization(
138 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
141 app = Repo.preload(token, :app).app
144 if is_binary(params["redirect_uri"]) do
145 params["redirect_uri"]
147 default_redirect_uri(app)
150 if redirect_uri in String.split(app.redirect_uris) do
151 redirect_uri = redirect_uri(conn, redirect_uri)
152 url_params = %{access_token: token.token}
153 url_params = Maps.put_if_present(url_params, :state, params["state"])
154 url = UriHelper.modify_uri_params(redirect_uri, url_params)
155 redirect(conn, external: url)
158 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
159 |> redirect(external: redirect_uri(conn, redirect_uri))
163 def create_authorization(_, _, opts \\ [])
165 def create_authorization(%Plug.Conn{assigns: %{user: %User{} = user}} = conn, params, []) do
166 create_authorization(conn, params, user: user)
169 def create_authorization(%Plug.Conn{} = conn, %{"authorization" => _} = params, opts) do
170 with {:ok, auth, user} <- do_create_authorization(conn, params, opts[:user]),
171 {:mfa_required, _, _, false} <- {:mfa_required, user, auth, MFA.require?(user)} do
173 |> AuthHelper.put_session_user(user.id)
174 |> after_create_authorization(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, :user_is_not_an_admin] 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 of 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.get_or_exchange_token(auth, app, user) 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 |> AuthHelper.put_session_token(token.token)
347 |> AuthHelper.put_session_user(token.user_id)
348 |> json(OAuthView.render("token.json", view_params))
351 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:mfa_required, user, auth, _}) do
353 |> put_status(:forbidden)
354 |> json(build_and_response_mfa_token(user, auth))
357 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:account_status, :deactivated}) do
361 "Your account is currently disabled",
363 "account_is_disabled"
367 defp handle_token_exchange_error(
369 {:account_status, :password_reset_pending}
374 "Password reset is required",
376 "password_reset_required"
380 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:account_status, :confirmation_pending}) do
384 "Your login is missing a confirmed e-mail address",
386 "missing_confirmed_email"
390 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:account_status, :approval_pending}) do
394 "Your account is awaiting approval.",
400 defp handle_token_exchange_error(%Plug.Conn{} = conn, _error) do
401 render_invalid_credentials_error(conn)
404 def token_revoke(%Plug.Conn{} = conn, %{"token" => token}) do
405 with {:ok, %Token{} = oauth_token} <- Token.get_by_token(token),
406 {:ok, oauth_token} <- RevokeToken.revoke(oauth_token) do
408 with session_token = AuthHelper.get_session_token(conn),
409 %Token{token: ^session_token} <- oauth_token do
410 AuthHelper.delete_session_token(conn)
418 # RFC 7009: invalid tokens [in the request] do not cause an error response
423 def token_revoke(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
425 # Response for bad request
426 defp bad_request(%Plug.Conn{} = conn, _) do
427 render_error(conn, :internal_server_error, "Bad request")
430 @doc "Prepares OAuth request to provider for Ueberauth"
431 def prepare_request(%Plug.Conn{} = conn, %{
432 "provider" => provider,
433 "authorization" => auth_attrs
437 |> Scopes.fetch_scopes([])
438 |> Scopes.to_string()
442 |> Map.delete("scopes")
443 |> Map.put("scope", scope)
448 |> Map.drop(~w(scope scopes client_id redirect_uri))
449 |> Map.put("state", state)
451 # Handing the request to Ueberauth
452 redirect(conn, to: Routes.o_auth_path(conn, :request, provider, params))
455 def request(%Plug.Conn{} = conn, params) do
457 if params["provider"] do
458 dgettext("errors", "Unsupported OAuth provider: %{provider}.",
459 provider: params["provider"]
462 dgettext("errors", "Bad OAuth request.")
466 |> put_flash(:error, message)
470 def callback(%Plug.Conn{assigns: %{ueberauth_failure: failure}} = conn, params) do
471 params = callback_params(params)
472 messages = for e <- Map.get(failure, :errors, []), do: e.message
473 message = Enum.join(messages, "; ")
478 dgettext("errors", "Failed to authenticate: %{message}.", message: message)
480 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
483 def callback(%Plug.Conn{} = conn, params) do
484 params = callback_params(params)
486 with {:ok, registration} <- Authenticator.get_registration(conn) do
487 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
489 case Repo.get_assoc(registration, :user) do
491 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
494 registration_params =
495 Map.merge(auth_attrs, %{
496 "nickname" => Registration.nickname(registration),
497 "email" => Registration.email(registration)
501 |> put_session_registration_id(registration.id)
502 |> registration_details(%{"authorization" => registration_params})
506 Logger.debug(inspect(["OAUTH_ERROR", error, conn.assigns]))
509 |> put_flash(:error, dgettext("errors", "Failed to set up user account."))
510 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
514 defp callback_params(%{"state" => state} = params) do
515 Map.merge(params, Jason.decode!(state))
518 def registration_details(%Plug.Conn{} = conn, %{"authorization" => auth_attrs}) do
519 render(conn, "register.html", %{
520 client_id: auth_attrs["client_id"],
521 redirect_uri: auth_attrs["redirect_uri"],
522 state: auth_attrs["state"],
523 scopes: Scopes.fetch_scopes(auth_attrs, []),
524 nickname: auth_attrs["nickname"],
525 email: auth_attrs["email"]
529 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "connect"} = params) do
530 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
531 %Registration{} = registration <- Repo.get(Registration, registration_id),
532 {_, {:ok, auth, _user}} <-
533 {:create_authorization, do_create_authorization(conn, params)},
534 %User{} = user <- Repo.preload(auth, :user).user,
535 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
537 |> put_session_registration_id(nil)
538 |> after_create_authorization(auth, params)
540 {:create_authorization, error} ->
541 {:register, handle_create_authorization_error(conn, error, params)}
544 {:register, :generic_error}
548 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "register"} = params) do
549 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
550 %Registration{} = registration <- Repo.get(Registration, registration_id),
551 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
553 |> put_session_registration_id(nil)
554 |> create_authorization(
559 {:error, changeset} ->
561 Enum.map_join(changeset.errors, "; ", fn {field, {error, _}} ->
568 "ap_id has already been taken",
569 "nickname has already been taken"
573 |> put_status(:forbidden)
574 |> put_flash(:error, "Error: #{message}.")
575 |> registration_details(params)
578 {:register, :generic_error}
582 defp do_create_authorization(conn, auth_attrs, user \\ nil)
584 defp do_create_authorization(
589 "client_id" => client_id,
590 "redirect_uri" => redirect_uri
595 with {_, {:ok, %User{} = user}} <-
596 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
597 %App{} = app <- Repo.get_by(App, client_id: client_id),
598 true <- redirect_uri in String.split(app.redirect_uris),
599 requested_scopes <- Scopes.fetch_scopes(auth_attrs, app.scopes),
600 {:ok, auth} <- do_create_authorization(user, app, requested_scopes) do
605 defp do_create_authorization(%User{} = user, %App{} = app, requested_scopes)
606 when is_list(requested_scopes) do
607 with {:account_status, :active} <- {:account_status, User.account_status(user)},
608 requested_scopes <- Scopes.filter_admin_scopes(requested_scopes, user),
609 {:ok, scopes} <- validate_scopes(user, app, requested_scopes),
610 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
615 # Note: intended to be a private function but opened for AccountController that logs in on signup
616 @doc "If checks pass, creates authorization and token for given user, app and requested scopes."
617 def login(%User{} = user, %App{} = app, requested_scopes) when is_list(requested_scopes) do
618 with {:ok, auth} <- do_create_authorization(user, app, requested_scopes),
619 {:mfa_required, _, _, false} <- {:mfa_required, user, auth, MFA.require?(user)},
620 {:ok, token} <- Token.exchange_token(app, auth) do
625 # Special case: Local MastodonFE
626 defp redirect_uri(%Plug.Conn{} = conn, "."), do: Routes.auth_url(conn, :login)
628 defp redirect_uri(%Plug.Conn{}, redirect_uri), do: redirect_uri
630 defp get_session_registration_id(%Plug.Conn{} = conn), do: get_session(conn, :registration_id)
632 defp put_session_registration_id(%Plug.Conn{} = conn, registration_id),
633 do: put_session(conn, :registration_id, registration_id)
635 defp build_and_response_mfa_token(user, auth) do
636 with {:ok, token} <- MFA.Token.create(user, auth) do
637 MFAView.render("mfa_response.json", %{token: token, user: user})
641 @spec validate_scopes(User.t(), App.t(), map() | list()) ::
642 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
643 defp validate_scopes(%User{} = user, %App{} = app, params) when is_map(params) do
644 requested_scopes = Scopes.fetch_scopes(params, app.scopes)
645 validate_scopes(user, app, requested_scopes)
648 defp validate_scopes(%User{} = user, %App{} = app, requested_scopes)
649 when is_list(requested_scopes) do
650 Scopes.validate(requested_scopes, app.scopes, user)
653 def default_redirect_uri(%App{} = app) do
659 defp render_invalid_credentials_error(conn) do
660 render_error(conn, :bad_request, "Invalid credentials")