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.info.deactivated},
206 {:ok, scopes} <- validate_scopes(app, params),
207 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
208 {:ok, token} <- Token.exchange_token(app, auth) do
209 json(conn, Token.Response.build(user, token))
211 {:auth_active, false} ->
212 # Per https://github.com/tootsuite/mastodon/blob/
213 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
214 render_error(conn, :forbidden, "Your login is missing a confirmed e-mail address")
216 {:user_active, false} ->
217 render_error(conn, :forbidden, "Your account is currently disabled")
220 render_invalid_credentials_error(conn)
226 %{"grant_type" => "password", "name" => name, "password" => _password} = params
230 |> Map.delete("name")
231 |> Map.put("username", name)
233 token_exchange(conn, params)
236 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "client_credentials"} = _params) do
237 with {:ok, app} <- Token.Utils.fetch_app(conn),
238 {:ok, auth} <- Authorization.create_authorization(app, %User{}),
239 {:ok, token} <- Token.exchange_token(app, auth) do
240 json(conn, Token.Response.build_for_client_credentials(token))
242 _error -> render_invalid_credentials_error(conn)
247 def token_exchange(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
249 def token_revoke(%Plug.Conn{} = conn, %{"token" => _token} = params) do
250 with {:ok, app} <- Token.Utils.fetch_app(conn),
251 {:ok, _token} <- RevokeToken.revoke(app, params) do
255 # RFC 7009: invalid tokens [in the request] do not cause an error response
260 def token_revoke(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
262 # Response for bad request
263 defp bad_request(%Plug.Conn{} = conn, _) do
264 render_error(conn, :internal_server_error, "Bad request")
267 @doc "Prepares OAuth request to provider for Ueberauth"
268 def prepare_request(%Plug.Conn{} = conn, %{
269 "provider" => provider,
270 "authorization" => auth_attrs
274 |> Scopes.fetch_scopes([])
275 |> Scopes.to_string()
279 |> Map.delete("scopes")
280 |> Map.put("scope", scope)
285 |> Map.drop(~w(scope scopes client_id redirect_uri))
286 |> Map.put("state", state)
288 # Handing the request to Ueberauth
289 redirect(conn, to: o_auth_path(conn, :request, provider, params))
292 def request(%Plug.Conn{} = conn, params) do
294 if params["provider"] do
295 dgettext("errors", "Unsupported OAuth provider: %{provider}.",
296 provider: params["provider"]
299 dgettext("errors", "Bad OAuth request.")
303 |> put_flash(:error, message)
307 def callback(%Plug.Conn{assigns: %{ueberauth_failure: failure}} = conn, params) do
308 params = callback_params(params)
309 messages = for e <- Map.get(failure, :errors, []), do: e.message
310 message = Enum.join(messages, "; ")
315 dgettext("errors", "Failed to authenticate: %{message}.", message: message)
317 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
320 def callback(%Plug.Conn{} = conn, params) do
321 params = callback_params(params)
323 with {:ok, registration} <- Authenticator.get_registration(conn) do
324 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
326 case Repo.get_assoc(registration, :user) do
328 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
331 registration_params =
332 Map.merge(auth_attrs, %{
333 "nickname" => Registration.nickname(registration),
334 "email" => Registration.email(registration)
338 |> put_session_registration_id(registration.id)
339 |> registration_details(%{"authorization" => registration_params})
343 Logger.debug(inspect(["OAUTH_ERROR", error, conn.assigns]))
346 |> put_flash(:error, dgettext("errors", "Failed to set up user account."))
347 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
351 defp callback_params(%{"state" => state} = params) do
352 Map.merge(params, Jason.decode!(state))
355 def registration_details(%Plug.Conn{} = conn, %{"authorization" => auth_attrs}) do
356 render(conn, "register.html", %{
357 client_id: auth_attrs["client_id"],
358 redirect_uri: auth_attrs["redirect_uri"],
359 state: auth_attrs["state"],
360 scopes: Scopes.fetch_scopes(auth_attrs, []),
361 nickname: auth_attrs["nickname"],
362 email: auth_attrs["email"]
366 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "connect"} = params) do
367 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
368 %Registration{} = registration <- Repo.get(Registration, registration_id),
369 {_, {:ok, auth}} <- {: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")