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)
28 action_fallback(Pleroma.Web.OAuth.FallbackController)
30 @oob_token_redirect_uri "urn:ietf:wg:oauth:2.0:oob"
32 # Note: this definition is only called from error-handling methods with `conn.params` as 2nd arg
33 def authorize(%Plug.Conn{} = conn, %{"authorization" => _} = params) do
34 {auth_attrs, params} = Map.pop(params, "authorization")
35 authorize(conn, Map.merge(params, auth_attrs))
38 def authorize(%Plug.Conn{assigns: %{token: %Token{}}} = conn, %{"force_login" => _} = params) do
39 if ControllerHelper.truthy_param?(params["force_login"]) do
40 do_authorize(conn, params)
42 handle_existing_authorization(conn, params)
46 # Note: the token is set in oauth_plug, but the token and client do not always go together.
47 # For example, MastodonFE's token is set if user requests with another client,
48 # after user already authorized to MastodonFE.
49 # So we have to check client and token.
51 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
52 %{"client_id" => client_id} = params
54 with %Token{} = t <- Repo.get_by(Token, token: token.token) |> Repo.preload(:app),
55 ^client_id <- t.app.client_id do
56 handle_existing_authorization(conn, params)
58 _ -> do_authorize(conn, params)
62 def authorize(%Plug.Conn{} = conn, params), do: do_authorize(conn, params)
64 defp do_authorize(%Plug.Conn{} = conn, params) do
65 app = Repo.get_by(App, client_id: params["client_id"])
66 available_scopes = (app && app.scopes) || []
67 scopes = Scopes.fetch_scopes(params, available_scopes)
69 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
70 render(conn, Authenticator.auth_template(), %{
71 response_type: params["response_type"],
72 client_id: params["client_id"],
73 available_scopes: available_scopes,
75 redirect_uri: params["redirect_uri"],
76 state: params["state"],
81 defp handle_existing_authorization(
82 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
83 %{"redirect_uri" => @oob_token_redirect_uri}
85 render(conn, "oob_token_exists.html", %{token: token})
88 defp handle_existing_authorization(
89 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
92 app = Repo.preload(token, :app).app
95 if is_binary(params["redirect_uri"]) do
96 params["redirect_uri"]
98 default_redirect_uri(app)
101 if redirect_uri in String.split(app.redirect_uris) do
102 redirect_uri = redirect_uri(conn, redirect_uri)
103 url_params = %{access_token: token.token}
104 url_params = UriHelper.append_param_if_present(url_params, :state, params["state"])
105 url = UriHelper.append_uri_params(redirect_uri, url_params)
106 redirect(conn, external: url)
109 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
110 |> redirect(external: redirect_uri(conn, redirect_uri))
114 def create_authorization(
116 %{"authorization" => _} = params,
119 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
120 after_create_authorization(conn, auth, params)
123 handle_create_authorization_error(conn, error, params)
127 def after_create_authorization(%Plug.Conn{} = conn, %Authorization{} = auth, %{
128 "authorization" => %{"redirect_uri" => @oob_token_redirect_uri}
130 render(conn, "oob_authorization_created.html", %{auth: auth})
133 def after_create_authorization(%Plug.Conn{} = conn, %Authorization{} = auth, %{
134 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
136 app = Repo.preload(auth, :app).app
138 # An extra safety measure before we redirect (also done in `do_create_authorization/2`)
139 if redirect_uri in String.split(app.redirect_uris) do
140 redirect_uri = redirect_uri(conn, redirect_uri)
141 url_params = %{code: auth.token}
142 url_params = UriHelper.append_param_if_present(url_params, :state, auth_attrs["state"])
143 url = UriHelper.append_uri_params(redirect_uri, url_params)
144 redirect(conn, external: url)
147 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
148 |> redirect(external: redirect_uri(conn, redirect_uri))
152 defp handle_create_authorization_error(
154 {:error, scopes_issue},
155 %{"authorization" => _} = params
157 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
158 # Per https://github.com/tootsuite/mastodon/blob/
159 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
161 |> put_flash(:error, dgettext("errors", "This action is outside the authorized scopes"))
162 |> put_status(:unauthorized)
166 defp handle_create_authorization_error(
168 {:auth_active, false},
169 %{"authorization" => _} = params
171 # Per https://github.com/tootsuite/mastodon/blob/
172 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
174 |> put_flash(:error, dgettext("errors", "Your login is missing a confirmed e-mail address"))
175 |> put_status(:forbidden)
179 defp handle_create_authorization_error(%Plug.Conn{} = conn, error, %{"authorization" => _}) do
180 Authenticator.handle_error(conn, error)
183 @doc "Renew access_token with refresh_token"
186 %{"grant_type" => "refresh_token", "refresh_token" => token} = _params
188 with {:ok, app} <- Token.Utils.fetch_app(conn),
189 {:ok, %{user: user} = token} <- Token.get_by_refresh_token(app, token),
190 {:ok, token} <- RefreshToken.grant(token) do
191 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
193 json(conn, Token.Response.build(user, token, response_attrs))
195 _error -> render_invalid_credentials_error(conn)
199 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "authorization_code"} = params) do
200 with {:ok, app} <- Token.Utils.fetch_app(conn),
201 fixed_token = Token.Utils.fix_padding(params["code"]),
202 {:ok, auth} <- Authorization.get_by_token(app, fixed_token),
203 %User{} = user <- User.get_cached_by_id(auth.user_id),
204 {:ok, token} <- Token.exchange_token(app, auth) do
205 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
207 json(conn, Token.Response.build(user, token, response_attrs))
209 _error -> render_invalid_credentials_error(conn)
215 %{"grant_type" => "password"} = params
217 with {:ok, %User{} = user} <- Authenticator.get_user(conn),
218 {:ok, app} <- Token.Utils.fetch_app(conn),
219 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
220 {:user_active, true} <- {:user_active, !user.info.deactivated},
221 {:ok, scopes} <- validate_scopes(app, params),
222 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
223 {:ok, token} <- Token.exchange_token(app, auth) do
224 json(conn, Token.Response.build(user, token))
226 {:auth_active, false} ->
227 # Per https://github.com/tootsuite/mastodon/blob/
228 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
229 render_error(conn, :forbidden, "Your login is missing a confirmed e-mail address")
231 {:user_active, false} ->
232 render_error(conn, :forbidden, "Your account is currently disabled")
235 render_invalid_credentials_error(conn)
241 %{"grant_type" => "password", "name" => name, "password" => _password} = params
245 |> Map.delete("name")
246 |> Map.put("username", name)
248 token_exchange(conn, params)
251 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "client_credentials"} = _params) do
252 with {:ok, app} <- Token.Utils.fetch_app(conn),
253 {:ok, auth} <- Authorization.create_authorization(app, %User{}),
254 {:ok, token} <- Token.exchange_token(app, auth) do
255 json(conn, Token.Response.build_for_client_credentials(token))
257 _error -> render_invalid_credentials_error(conn)
262 def token_exchange(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
264 def token_revoke(%Plug.Conn{} = conn, %{"token" => _token} = params) do
265 with {:ok, app} <- Token.Utils.fetch_app(conn),
266 {:ok, _token} <- RevokeToken.revoke(app, params) do
270 # RFC 7009: invalid tokens [in the request] do not cause an error response
275 def token_revoke(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
277 # Response for bad request
278 defp bad_request(%Plug.Conn{} = conn, _) do
279 render_error(conn, :internal_server_error, "Bad request")
282 @doc "Prepares OAuth request to provider for Ueberauth"
283 def prepare_request(%Plug.Conn{} = conn, %{
284 "provider" => provider,
285 "authorization" => auth_attrs
289 |> Scopes.fetch_scopes([])
290 |> Scopes.to_string()
294 |> Map.delete("scopes")
295 |> Map.put("scope", scope)
300 |> Map.drop(~w(scope scopes client_id redirect_uri))
301 |> Map.put("state", state)
303 # Handing the request to Ueberauth
304 redirect(conn, to: o_auth_path(conn, :request, provider, params))
307 def request(%Plug.Conn{} = conn, params) do
309 if params["provider"] do
310 dgettext("errors", "Unsupported OAuth provider: %{provider}.",
311 provider: params["provider"]
314 dgettext("errors", "Bad OAuth request.")
318 |> put_flash(:error, message)
322 def callback(%Plug.Conn{assigns: %{ueberauth_failure: failure}} = conn, params) do
323 params = callback_params(params)
324 messages = for e <- Map.get(failure, :errors, []), do: e.message
325 message = Enum.join(messages, "; ")
330 dgettext("errors", "Failed to authenticate: %{message}.", message: message)
332 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
335 def callback(%Plug.Conn{} = conn, params) do
336 params = callback_params(params)
338 with {:ok, registration} <- Authenticator.get_registration(conn) do
339 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
341 case Repo.get_assoc(registration, :user) do
343 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
346 registration_params =
347 Map.merge(auth_attrs, %{
348 "nickname" => Registration.nickname(registration),
349 "email" => Registration.email(registration)
353 |> put_session_registration_id(registration.id)
354 |> registration_details(%{"authorization" => registration_params})
358 Logger.debug(inspect(["OAUTH_ERROR", error, conn.assigns]))
361 |> put_flash(:error, dgettext("errors", "Failed to set up user account."))
362 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
366 defp callback_params(%{"state" => state} = params) do
367 Map.merge(params, Jason.decode!(state))
370 def registration_details(%Plug.Conn{} = conn, %{"authorization" => auth_attrs}) do
371 render(conn, "register.html", %{
372 client_id: auth_attrs["client_id"],
373 redirect_uri: auth_attrs["redirect_uri"],
374 state: auth_attrs["state"],
375 scopes: Scopes.fetch_scopes(auth_attrs, []),
376 nickname: auth_attrs["nickname"],
377 email: auth_attrs["email"]
381 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "connect"} = params) do
382 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
383 %Registration{} = registration <- Repo.get(Registration, registration_id),
384 {_, {:ok, auth}} <- {:create_authorization, do_create_authorization(conn, params)},
385 %User{} = user <- Repo.preload(auth, :user).user,
386 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
388 |> put_session_registration_id(nil)
389 |> after_create_authorization(auth, params)
391 {:create_authorization, error} ->
392 {:register, handle_create_authorization_error(conn, error, params)}
395 {:register, :generic_error}
399 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "register"} = params) do
400 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
401 %Registration{} = registration <- Repo.get(Registration, registration_id),
402 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
404 |> put_session_registration_id(nil)
405 |> create_authorization(
410 {:error, changeset} ->
412 Enum.map(changeset.errors, fn {field, {error, _}} ->
420 "ap_id has already been taken",
421 "nickname has already been taken"
425 |> put_status(:forbidden)
426 |> put_flash(:error, "Error: #{message}.")
427 |> registration_details(params)
430 {:register, :generic_error}
434 defp do_create_authorization(
439 "client_id" => client_id,
440 "redirect_uri" => redirect_uri
445 with {_, {:ok, %User{} = user}} <-
446 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
447 %App{} = app <- Repo.get_by(App, client_id: client_id),
448 true <- redirect_uri in String.split(app.redirect_uris),
449 {:ok, scopes} <- validate_scopes(app, auth_attrs),
450 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
451 Authorization.create_authorization(app, user, scopes)
455 # Special case: Local MastodonFE
456 defp redirect_uri(%Plug.Conn{} = conn, "."), do: mastodon_api_url(conn, :login)
458 defp redirect_uri(%Plug.Conn{}, redirect_uri), do: redirect_uri
460 defp get_session_registration_id(%Plug.Conn{} = conn), do: get_session(conn, :registration_id)
462 defp put_session_registration_id(%Plug.Conn{} = conn, registration_id),
463 do: put_session(conn, :registration_id, registration_id)
465 @spec validate_scopes(App.t(), map()) ::
466 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
467 defp validate_scopes(app, params) do
469 |> Scopes.fetch_scopes(app.scopes)
470 |> Scopes.validates(app.scopes)
473 def default_redirect_uri(%App{} = app) do
479 defp render_invalid_credentials_error(conn) do
480 render_error(conn, :bad_request, "Invalid credentials")