1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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
9 alias Pleroma.Registration
12 alias Pleroma.Web.Auth.Authenticator
13 alias Pleroma.Web.ControllerHelper
14 alias Pleroma.Web.OAuth.App
15 alias Pleroma.Web.OAuth.Authorization
16 alias Pleroma.Web.OAuth.Token
17 alias Pleroma.Web.OAuth.Token.Strategy.RefreshToken
18 alias Pleroma.Web.OAuth.Token.Strategy.Revoke, as: RevokeToken
19 alias Pleroma.Web.OAuth.Scopes
23 if Pleroma.Config.oauth_consumer_enabled?(), do: plug(Ueberauth)
27 plug(Pleroma.Plugs.RateLimiter, :authentication when action == :create_authorization)
29 action_fallback(Pleroma.Web.OAuth.FallbackController)
31 @oob_token_redirect_uri "urn:ietf:wg:oauth:2.0:oob"
33 # Note: this definition is only called from error-handling methods with `conn.params` as 2nd arg
34 def authorize(%Plug.Conn{} = conn, %{"authorization" => _} = params) do
35 {auth_attrs, params} = Map.pop(params, "authorization")
36 authorize(conn, Map.merge(params, auth_attrs))
39 def authorize(%Plug.Conn{assigns: %{token: %Token{}}} = conn, params) do
40 if ControllerHelper.truthy_param?(params["force_login"]) do
41 do_authorize(conn, params)
43 handle_existing_authorization(conn, params)
47 def authorize(%Plug.Conn{} = conn, params), do: do_authorize(conn, params)
49 defp do_authorize(%Plug.Conn{} = conn, params) do
50 app = Repo.get_by(App, client_id: params["client_id"])
51 available_scopes = (app && app.scopes) || []
52 scopes = Scopes.fetch_scopes(params, available_scopes)
54 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
55 render(conn, Authenticator.auth_template(), %{
56 response_type: params["response_type"],
57 client_id: params["client_id"],
58 available_scopes: available_scopes,
60 redirect_uri: params["redirect_uri"],
61 state: params["state"],
66 defp handle_existing_authorization(
67 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
68 %{"redirect_uri" => @oob_token_redirect_uri}
70 render(conn, "oob_token_exists.html", %{token: token})
73 defp handle_existing_authorization(
74 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
77 app = Repo.preload(token, :app).app
80 if is_binary(params["redirect_uri"]) do
81 params["redirect_uri"]
83 default_redirect_uri(app)
86 if redirect_uri in String.split(app.redirect_uris) do
87 redirect_uri = redirect_uri(conn, redirect_uri)
88 url_params = %{access_token: token.token}
89 url_params = UriHelper.append_param_if_present(url_params, :state, params["state"])
90 url = UriHelper.append_uri_params(redirect_uri, url_params)
91 redirect(conn, external: url)
94 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
95 |> redirect(external: redirect_uri(conn, redirect_uri))
99 def create_authorization(
101 %{"authorization" => _} = params,
104 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
105 after_create_authorization(conn, auth, params)
108 handle_create_authorization_error(conn, error, params)
112 def after_create_authorization(%Plug.Conn{} = conn, %Authorization{} = auth, %{
113 "authorization" => %{"redirect_uri" => @oob_token_redirect_uri}
115 render(conn, "oob_authorization_created.html", %{auth: auth})
118 def after_create_authorization(%Plug.Conn{} = conn, %Authorization{} = auth, %{
119 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
121 app = Repo.preload(auth, :app).app
123 # An extra safety measure before we redirect (also done in `do_create_authorization/2`)
124 if redirect_uri in String.split(app.redirect_uris) do
125 redirect_uri = redirect_uri(conn, redirect_uri)
126 url_params = %{code: auth.token}
127 url_params = UriHelper.append_param_if_present(url_params, :state, auth_attrs["state"])
128 url = UriHelper.append_uri_params(redirect_uri, url_params)
129 redirect(conn, external: url)
132 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
133 |> redirect(external: redirect_uri(conn, redirect_uri))
137 defp handle_create_authorization_error(
139 {:error, scopes_issue},
140 %{"authorization" => _} = params
142 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
143 # Per https://github.com/tootsuite/mastodon/blob/
144 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
146 |> put_flash(:error, dgettext("errors", "This action is outside the authorized scopes"))
147 |> put_status(:unauthorized)
151 defp handle_create_authorization_error(
153 {:auth_active, false},
154 %{"authorization" => _} = params
156 # Per https://github.com/tootsuite/mastodon/blob/
157 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
159 |> put_flash(:error, dgettext("errors", "Your login is missing a confirmed e-mail address"))
160 |> put_status(:forbidden)
164 defp handle_create_authorization_error(%Plug.Conn{} = conn, error, %{"authorization" => _}) do
165 Authenticator.handle_error(conn, error)
168 @doc "Renew access_token with refresh_token"
171 %{"grant_type" => "refresh_token", "refresh_token" => token} = _params
173 with {:ok, app} <- Token.Utils.fetch_app(conn),
174 {:ok, %{user: user} = token} <- Token.get_by_refresh_token(app, token),
175 {:ok, token} <- RefreshToken.grant(token) do
176 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
178 json(conn, Token.Response.build(user, token, response_attrs))
180 _error -> render_invalid_credentials_error(conn)
184 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "authorization_code"} = params) do
185 with {:ok, app} <- Token.Utils.fetch_app(conn),
186 fixed_token = Token.Utils.fix_padding(params["code"]),
187 {:ok, auth} <- Authorization.get_by_token(app, fixed_token),
188 %User{} = user <- User.get_cached_by_id(auth.user_id),
189 {:ok, token} <- Token.exchange_token(app, auth) do
190 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
192 json(conn, Token.Response.build(user, token, response_attrs))
194 _error -> render_invalid_credentials_error(conn)
200 %{"grant_type" => "password"} = params
202 with {:ok, %User{} = user} <- Authenticator.get_user(conn),
203 {:ok, app} <- Token.Utils.fetch_app(conn),
204 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
205 {:user_active, true} <- {:user_active, !user.deactivated},
206 {:password_reset_pending, false} <-
207 {:password_reset_pending, user.password_reset_pending},
208 {:ok, scopes} <- validate_scopes(app, params),
209 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
210 {:ok, token} <- Token.exchange_token(app, auth) do
211 json(conn, Token.Response.build(user, token))
213 {:auth_active, false} ->
214 # Per https://github.com/tootsuite/mastodon/blob/
215 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
219 "Your login is missing a confirmed e-mail address",
221 "missing_confirmed_email"
224 {:user_active, false} ->
228 "Your account is currently disabled",
230 "account_is_disabled"
233 {:password_reset_pending, true} ->
237 "Password reset is required",
239 "password_reset_required"
243 render_invalid_credentials_error(conn)
249 %{"grant_type" => "password", "name" => name, "password" => _password} = params
253 |> Map.delete("name")
254 |> Map.put("username", name)
256 token_exchange(conn, params)
259 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "client_credentials"} = _params) do
260 with {:ok, app} <- Token.Utils.fetch_app(conn),
261 {:ok, auth} <- Authorization.create_authorization(app, %User{}),
262 {:ok, token} <- Token.exchange_token(app, auth) do
263 json(conn, Token.Response.build_for_client_credentials(token))
265 _error -> render_invalid_credentials_error(conn)
270 def token_exchange(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
272 def token_revoke(%Plug.Conn{} = conn, %{"token" => _token} = params) do
273 with {:ok, app} <- Token.Utils.fetch_app(conn),
274 {:ok, _token} <- RevokeToken.revoke(app, params) do
278 # RFC 7009: invalid tokens [in the request] do not cause an error response
283 def token_revoke(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
285 # Response for bad request
286 defp bad_request(%Plug.Conn{} = conn, _) do
287 render_error(conn, :internal_server_error, "Bad request")
290 @doc "Prepares OAuth request to provider for Ueberauth"
291 def prepare_request(%Plug.Conn{} = conn, %{
292 "provider" => provider,
293 "authorization" => auth_attrs
297 |> Scopes.fetch_scopes([])
298 |> Scopes.to_string()
302 |> Map.delete("scopes")
303 |> Map.put("scope", scope)
308 |> Map.drop(~w(scope scopes client_id redirect_uri))
309 |> Map.put("state", state)
311 # Handing the request to Ueberauth
312 redirect(conn, to: o_auth_path(conn, :request, provider, params))
315 def request(%Plug.Conn{} = conn, params) do
317 if params["provider"] do
318 dgettext("errors", "Unsupported OAuth provider: %{provider}.",
319 provider: params["provider"]
322 dgettext("errors", "Bad OAuth request.")
326 |> put_flash(:error, message)
330 def callback(%Plug.Conn{assigns: %{ueberauth_failure: failure}} = conn, params) do
331 params = callback_params(params)
332 messages = for e <- Map.get(failure, :errors, []), do: e.message
333 message = Enum.join(messages, "; ")
338 dgettext("errors", "Failed to authenticate: %{message}.", message: message)
340 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
343 def callback(%Plug.Conn{} = conn, params) do
344 params = callback_params(params)
346 with {:ok, registration} <- Authenticator.get_registration(conn) do
347 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
349 case Repo.get_assoc(registration, :user) do
351 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
354 registration_params =
355 Map.merge(auth_attrs, %{
356 "nickname" => Registration.nickname(registration),
357 "email" => Registration.email(registration)
361 |> put_session_registration_id(registration.id)
362 |> registration_details(%{"authorization" => registration_params})
366 Logger.debug(inspect(["OAUTH_ERROR", error, conn.assigns]))
369 |> put_flash(:error, dgettext("errors", "Failed to set up user account."))
370 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
374 defp callback_params(%{"state" => state} = params) do
375 Map.merge(params, Jason.decode!(state))
378 def registration_details(%Plug.Conn{} = conn, %{"authorization" => auth_attrs}) do
379 render(conn, "register.html", %{
380 client_id: auth_attrs["client_id"],
381 redirect_uri: auth_attrs["redirect_uri"],
382 state: auth_attrs["state"],
383 scopes: Scopes.fetch_scopes(auth_attrs, []),
384 nickname: auth_attrs["nickname"],
385 email: auth_attrs["email"]
389 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "connect"} = params) do
390 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
391 %Registration{} = registration <- Repo.get(Registration, registration_id),
392 {_, {:ok, auth}} <- {:create_authorization, do_create_authorization(conn, params)},
393 %User{} = user <- Repo.preload(auth, :user).user,
394 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
396 |> put_session_registration_id(nil)
397 |> after_create_authorization(auth, params)
399 {:create_authorization, error} ->
400 {:register, handle_create_authorization_error(conn, error, params)}
403 {:register, :generic_error}
407 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "register"} = params) do
408 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
409 %Registration{} = registration <- Repo.get(Registration, registration_id),
410 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
412 |> put_session_registration_id(nil)
413 |> create_authorization(
418 {:error, changeset} ->
420 Enum.map(changeset.errors, fn {field, {error, _}} ->
428 "ap_id has already been taken",
429 "nickname has already been taken"
433 |> put_status(:forbidden)
434 |> put_flash(:error, "Error: #{message}.")
435 |> registration_details(params)
438 {:register, :generic_error}
442 defp do_create_authorization(
447 "client_id" => client_id,
448 "redirect_uri" => redirect_uri
453 with {_, {:ok, %User{} = user}} <-
454 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
455 %App{} = app <- Repo.get_by(App, client_id: client_id),
456 true <- redirect_uri in String.split(app.redirect_uris),
457 {:ok, scopes} <- validate_scopes(app, auth_attrs),
458 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
459 Authorization.create_authorization(app, user, scopes)
463 # Special case: Local MastodonFE
464 defp redirect_uri(%Plug.Conn{} = conn, "."), do: auth_url(conn, :login)
466 defp redirect_uri(%Plug.Conn{}, redirect_uri), do: redirect_uri
468 defp get_session_registration_id(%Plug.Conn{} = conn), do: get_session(conn, :registration_id)
470 defp put_session_registration_id(%Plug.Conn{} = conn, registration_id),
471 do: put_session(conn, :registration_id, registration_id)
473 @spec validate_scopes(App.t(), map()) ::
474 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
475 defp validate_scopes(app, params) do
477 |> Scopes.fetch_scopes(app.scopes)
478 |> Scopes.validate(app.scopes)
481 def default_redirect_uri(%App{} = app) do
487 defp render_invalid_credentials_error(conn) do
488 render_error(conn, :bad_request, "Invalid credentials")