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, params) do
39 if ControllerHelper.truthy_param?(params["force_login"]) do
40 do_authorize(conn, params)
42 handle_existing_authorization(conn, params)
46 def authorize(%Plug.Conn{} = conn, params), do: do_authorize(conn, params)
48 defp do_authorize(%Plug.Conn{} = conn, params) do
49 app = Repo.get_by(App, client_id: params["client_id"])
50 available_scopes = (app && app.scopes) || []
51 scopes = Scopes.fetch_scopes(params, available_scopes)
53 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
54 render(conn, Authenticator.auth_template(), %{
55 response_type: params["response_type"],
56 client_id: params["client_id"],
57 available_scopes: available_scopes,
59 redirect_uri: params["redirect_uri"],
60 state: params["state"],
65 defp handle_existing_authorization(
66 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
67 %{"redirect_uri" => @oob_token_redirect_uri}
69 render(conn, "oob_token_exists.html", %{token: token})
72 defp handle_existing_authorization(
73 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
76 app = Repo.preload(token, :app).app
79 if is_binary(params["redirect_uri"]) do
80 params["redirect_uri"]
82 default_redirect_uri(app)
85 if redirect_uri in String.split(app.redirect_uris) do
86 redirect_uri = redirect_uri(conn, redirect_uri)
87 url_params = %{access_token: token.token}
88 url_params = UriHelper.append_param_if_present(url_params, :state, params["state"])
89 url = UriHelper.append_uri_params(redirect_uri, url_params)
90 redirect(conn, external: url)
93 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
94 |> redirect(external: redirect_uri(conn, redirect_uri))
98 def create_authorization(
100 %{"authorization" => _} = params,
103 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
104 after_create_authorization(conn, auth, params)
107 handle_create_authorization_error(conn, error, params)
111 def after_create_authorization(%Plug.Conn{} = conn, %Authorization{} = auth, %{
112 "authorization" => %{"redirect_uri" => @oob_token_redirect_uri}
114 render(conn, "oob_authorization_created.html", %{auth: auth})
117 def after_create_authorization(%Plug.Conn{} = conn, %Authorization{} = auth, %{
118 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
120 app = Repo.preload(auth, :app).app
122 # An extra safety measure before we redirect (also done in `do_create_authorization/2`)
123 if redirect_uri in String.split(app.redirect_uris) do
124 redirect_uri = redirect_uri(conn, redirect_uri)
125 url_params = %{code: auth.token}
126 url_params = UriHelper.append_param_if_present(url_params, :state, auth_attrs["state"])
127 url = UriHelper.append_uri_params(redirect_uri, url_params)
128 redirect(conn, external: url)
131 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
132 |> redirect(external: redirect_uri(conn, redirect_uri))
136 defp handle_create_authorization_error(
138 {:error, scopes_issue},
139 %{"authorization" => _} = params
141 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
142 # Per https://github.com/tootsuite/mastodon/blob/
143 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
145 |> put_flash(:error, dgettext("errors", "This action is outside the authorized scopes"))
146 |> put_status(:unauthorized)
150 defp handle_create_authorization_error(
152 {:auth_active, false},
153 %{"authorization" => _} = params
155 # Per https://github.com/tootsuite/mastodon/blob/
156 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
158 |> put_flash(:error, dgettext("errors", "Your login is missing a confirmed e-mail address"))
159 |> put_status(:forbidden)
163 defp handle_create_authorization_error(%Plug.Conn{} = conn, error, %{"authorization" => _}) do
164 Authenticator.handle_error(conn, error)
167 @doc "Renew access_token with refresh_token"
170 %{"grant_type" => "refresh_token", "refresh_token" => token} = _params
172 with {:ok, app} <- Token.Utils.fetch_app(conn),
173 {:ok, %{user: user} = token} <- Token.get_by_refresh_token(app, token),
174 {:ok, token} <- RefreshToken.grant(token) do
175 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
177 json(conn, Token.Response.build(user, token, response_attrs))
179 _error -> render_invalid_credentials_error(conn)
183 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "authorization_code"} = params) do
184 with {:ok, app} <- Token.Utils.fetch_app(conn),
185 fixed_token = Token.Utils.fix_padding(params["code"]),
186 {:ok, auth} <- Authorization.get_by_token(app, fixed_token),
187 %User{} = user <- User.get_cached_by_id(auth.user_id),
188 {:ok, token} <- Token.exchange_token(app, auth) do
189 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
191 json(conn, Token.Response.build(user, token, response_attrs))
193 _error -> render_invalid_credentials_error(conn)
199 %{"grant_type" => "password"} = params
201 with {:ok, %User{} = user} <- Authenticator.get_user(conn),
202 {:ok, app} <- Token.Utils.fetch_app(conn),
203 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
204 {:user_active, true} <- {:user_active, !user.info.deactivated},
205 {:ok, scopes} <- validate_scopes(app, params),
206 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
207 {:ok, token} <- Token.exchange_token(app, auth) do
208 json(conn, Token.Response.build(user, token))
210 {:auth_active, false} ->
211 # Per https://github.com/tootsuite/mastodon/blob/
212 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
213 render_error(conn, :forbidden, "Your login is missing a confirmed e-mail address")
215 {:user_active, false} ->
216 render_error(conn, :forbidden, "Your account is currently disabled")
219 render_invalid_credentials_error(conn)
225 %{"grant_type" => "password", "name" => name, "password" => _password} = params
229 |> Map.delete("name")
230 |> Map.put("username", name)
232 token_exchange(conn, params)
235 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "client_credentials"} = _params) do
236 with {:ok, app} <- Token.Utils.fetch_app(conn),
237 {:ok, auth} <- Authorization.create_authorization(app, %User{}),
238 {:ok, token} <- Token.exchange_token(app, auth) do
239 json(conn, Token.Response.build_for_client_credentials(token))
241 _error -> render_invalid_credentials_error(conn)
246 def token_exchange(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
248 def token_revoke(%Plug.Conn{} = conn, %{"token" => _token} = params) do
249 with {:ok, app} <- Token.Utils.fetch_app(conn),
250 {:ok, _token} <- RevokeToken.revoke(app, params) do
254 # RFC 7009: invalid tokens [in the request] do not cause an error response
259 def token_revoke(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
261 # Response for bad request
262 defp bad_request(%Plug.Conn{} = conn, _) do
263 render_error(conn, :internal_server_error, "Bad request")
266 @doc "Prepares OAuth request to provider for Ueberauth"
267 def prepare_request(%Plug.Conn{} = conn, %{
268 "provider" => provider,
269 "authorization" => auth_attrs
273 |> Scopes.fetch_scopes([])
274 |> Scopes.to_string()
278 |> Map.delete("scopes")
279 |> Map.put("scope", scope)
284 |> Map.drop(~w(scope scopes client_id redirect_uri))
285 |> Map.put("state", state)
287 # Handing the request to Ueberauth
288 redirect(conn, to: o_auth_path(conn, :request, provider, params))
291 def request(%Plug.Conn{} = conn, params) do
293 if params["provider"] do
294 dgettext("errors", "Unsupported OAuth provider: %{provider}.",
295 provider: params["provider"]
298 dgettext("errors", "Bad OAuth request.")
302 |> put_flash(:error, message)
306 def callback(%Plug.Conn{assigns: %{ueberauth_failure: failure}} = conn, params) do
307 params = callback_params(params)
308 messages = for e <- Map.get(failure, :errors, []), do: e.message
309 message = Enum.join(messages, "; ")
314 dgettext("errors", "Failed to authenticate: %{message}.", message: message)
316 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
319 def callback(%Plug.Conn{} = conn, params) do
320 params = callback_params(params)
322 with {:ok, registration} <- Authenticator.get_registration(conn) do
323 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
325 case Repo.get_assoc(registration, :user) do
327 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
330 registration_params =
331 Map.merge(auth_attrs, %{
332 "nickname" => Registration.nickname(registration),
333 "email" => Registration.email(registration)
337 |> put_session_registration_id(registration.id)
338 |> registration_details(%{"authorization" => registration_params})
342 Logger.debug(inspect(["OAUTH_ERROR", error, conn.assigns]))
345 |> put_flash(:error, dgettext("errors", "Failed to set up user account."))
346 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
350 defp callback_params(%{"state" => state} = params) do
351 Map.merge(params, Jason.decode!(state))
354 def registration_details(%Plug.Conn{} = conn, %{"authorization" => auth_attrs}) do
355 render(conn, "register.html", %{
356 client_id: auth_attrs["client_id"],
357 redirect_uri: auth_attrs["redirect_uri"],
358 state: auth_attrs["state"],
359 scopes: Scopes.fetch_scopes(auth_attrs, []),
360 nickname: auth_attrs["nickname"],
361 email: auth_attrs["email"]
365 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "connect"} = params) do
366 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
367 %Registration{} = registration <- Repo.get(Registration, registration_id),
369 {:create_authorization, do_create_authorization(conn, params)},
370 %User{} = user <- Repo.preload(auth, :user).user,
371 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
373 |> put_session_registration_id(nil)
374 |> after_create_authorization(auth, params)
376 {:create_authorization, error} ->
377 {:register, handle_create_authorization_error(conn, error, params)}
380 {:register, :generic_error}
384 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "register"} = params) do
385 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
386 %Registration{} = registration <- Repo.get(Registration, registration_id),
387 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
389 |> put_session_registration_id(nil)
390 |> create_authorization(
395 {:error, changeset} ->
397 Enum.map(changeset.errors, fn {field, {error, _}} ->
405 "ap_id has already been taken",
406 "nickname has already been taken"
410 |> put_status(:forbidden)
411 |> put_flash(:error, "Error: #{message}.")
412 |> registration_details(params)
415 {:register, :generic_error}
419 defp do_create_authorization(
424 "client_id" => client_id,
425 "redirect_uri" => redirect_uri
430 with {_, {:ok, %User{} = user}} <-
431 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
432 %App{} = app <- Repo.get_by(App, client_id: client_id),
433 true <- redirect_uri in String.split(app.redirect_uris),
434 {:ok, scopes} <- validate_scopes(app, auth_attrs),
435 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
436 Authorization.create_authorization(app, user, scopes)
440 # Special case: Local MastodonFE
441 defp redirect_uri(%Plug.Conn{} = conn, "."), do: mastodon_api_url(conn, :login)
443 defp redirect_uri(%Plug.Conn{}, redirect_uri), do: redirect_uri
445 defp get_session_registration_id(%Plug.Conn{} = conn), do: get_session(conn, :registration_id)
447 defp put_session_registration_id(%Plug.Conn{} = conn, registration_id),
448 do: put_session(conn, :registration_id, registration_id)
450 @spec validate_scopes(App.t(), map()) ::
451 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
452 defp validate_scopes(app, params) do
454 |> Scopes.fetch_scopes(app.scopes)
455 |> Scopes.validates(app.scopes)
458 def default_redirect_uri(%App{} = app) do
464 defp render_invalid_credentials_error(conn) do
465 render_error(conn, :bad_request, "Invalid credentials")