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.Registration
11 alias Pleroma.Web.Auth.Authenticator
12 alias Pleroma.Web.ControllerHelper
13 alias Pleroma.Web.OAuth.App
14 alias Pleroma.Web.OAuth.Authorization
15 alias Pleroma.Web.OAuth.Token
16 alias Pleroma.Web.OAuth.Token.Strategy.RefreshToken
17 alias Pleroma.Web.OAuth.Token.Strategy.Revoke, as: RevokeToken
18 alias Pleroma.Web.OAuth.Scopes
20 if Pleroma.Config.oauth_consumer_enabled?(), do: plug(Ueberauth)
25 action_fallback(Pleroma.Web.OAuth.FallbackController)
27 # Note: this definition is only called from error-handling methods with `conn.params` as 2nd arg
28 def authorize(conn, %{"authorization" => _} = params) do
29 {auth_attrs, params} = Map.pop(params, "authorization")
30 authorize(conn, Map.merge(params, auth_attrs))
33 def authorize(%{assigns: %{token: %Token{} = token}} = conn, params) do
34 if ControllerHelper.truthy_param?(params["force_login"]) do
35 do_authorize(conn, params)
38 if is_binary(params["redirect_uri"]) do
39 params["redirect_uri"]
41 app = Repo.preload(token, :app).app
48 redirect(conn, external: redirect_uri(conn, redirect_uri))
52 def authorize(conn, params), do: do_authorize(conn, params)
54 defp do_authorize(conn, params) do
55 app = Repo.get_by(App, client_id: params["client_id"])
56 available_scopes = (app && app.scopes) || []
57 scopes = Scopes.fetch_scopes(params, available_scopes)
59 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
60 render(conn, Authenticator.auth_template(), %{
61 response_type: params["response_type"],
62 client_id: params["client_id"],
63 available_scopes: available_scopes,
65 redirect_uri: params["redirect_uri"],
66 state: params["state"],
71 def create_authorization(
73 %{"authorization" => _} = params,
76 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
77 after_create_authorization(conn, auth, params)
80 handle_create_authorization_error(conn, error, params)
84 def after_create_authorization(conn, auth, %{
85 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
87 redirect_uri = redirect_uri(conn, redirect_uri)
89 if redirect_uri == "urn:ietf:wg:oauth:2.0:oob" do
90 render(conn, "results.html", %{
94 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
95 url = "#{redirect_uri}#{connector}"
96 url_params = %{:code => auth.token}
99 if auth_attrs["state"] do
100 Map.put(url_params, :state, auth_attrs["state"])
105 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
107 redirect(conn, external: url)
111 defp handle_create_authorization_error(
113 {:error, scopes_issue},
114 %{"authorization" => _} = params
116 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
117 # Per https://github.com/tootsuite/mastodon/blob/
118 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
120 |> put_flash(:error, "This action is outside the authorized scopes")
121 |> put_status(:unauthorized)
125 defp handle_create_authorization_error(
127 {:auth_active, false},
128 %{"authorization" => _} = params
130 # Per https://github.com/tootsuite/mastodon/blob/
131 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
133 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
134 |> put_status(:forbidden)
138 defp handle_create_authorization_error(conn, error, %{"authorization" => _}) do
139 Authenticator.handle_error(conn, error)
142 @doc "Renew access_token with refresh_token"
145 %{"grant_type" => "refresh_token", "refresh_token" => token} = _params
147 with {:ok, app} <- Token.Utils.fetch_app(conn),
148 {:ok, %{user: user} = token} <- Token.get_by_refresh_token(app, token),
149 {:ok, token} <- RefreshToken.grant(token) do
150 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
152 json(conn, Token.Response.build(user, token, response_attrs))
155 put_status(conn, 400)
156 |> json(%{error: "Invalid credentials"})
160 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
161 with {:ok, app} <- Token.Utils.fetch_app(conn),
162 fixed_token = Token.Utils.fix_padding(params["code"]),
163 {:ok, auth} <- Authorization.get_by_token(app, fixed_token),
164 %User{} = user <- User.get_cached_by_id(auth.user_id),
165 {:ok, token} <- Token.exchange_token(app, auth) do
166 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
168 json(conn, Token.Response.build(user, token, response_attrs))
171 put_status(conn, 400)
172 |> json(%{error: "Invalid credentials"})
178 %{"grant_type" => "password"} = params
180 with {:ok, %User{} = user} <- Authenticator.get_user(conn),
181 {:ok, app} <- Token.Utils.fetch_app(conn),
182 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
183 {:user_active, true} <- {:user_active, !user.info.deactivated},
184 {:ok, scopes} <- validate_scopes(app, params),
185 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
186 {:ok, token} <- Token.exchange_token(app, auth) do
187 json(conn, Token.Response.build(user, token))
189 {:auth_active, false} ->
190 # Per https://github.com/tootsuite/mastodon/blob/
191 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
193 |> put_status(:forbidden)
194 |> json(%{error: "Your login is missing a confirmed e-mail address"})
196 {:user_active, false} ->
198 |> put_status(:forbidden)
199 |> json(%{error: "Your account is currently disabled"})
202 put_status(conn, 400)
203 |> json(%{error: "Invalid credentials"})
209 %{"grant_type" => "password", "name" => name, "password" => _password} = params
213 |> Map.delete("name")
214 |> Map.put("username", name)
216 token_exchange(conn, params)
219 def token_exchange(conn, %{"grant_type" => "client_credentials"} = _params) do
220 with {:ok, app} <- Token.Utils.fetch_app(conn),
221 {:ok, auth} <- Authorization.create_authorization(app, %User{}),
222 {:ok, token} <- Token.exchange_token(app, auth) do
223 json(conn, Token.Response.build_for_client_credentials(token))
226 put_status(conn, 400)
227 |> json(%{error: "Invalid credentials"})
232 def token_exchange(conn, params), do: bad_request(conn, params)
234 def token_revoke(conn, %{"token" => _token} = params) do
235 with {:ok, app} <- Token.Utils.fetch_app(conn),
236 {:ok, _token} <- RevokeToken.revoke(app, params) do
240 # RFC 7009: invalid tokens [in the request] do not cause an error response
245 def token_revoke(conn, params), do: bad_request(conn, params)
247 # Response for bad request
248 defp bad_request(conn, _) do
251 |> json(%{error: "Bad request"})
254 @doc "Prepares OAuth request to provider for Ueberauth"
255 def prepare_request(conn, %{"provider" => provider, "authorization" => auth_attrs}) do
258 |> Scopes.fetch_scopes([])
259 |> Scopes.to_string()
263 |> Map.delete("scopes")
264 |> Map.put("scope", scope)
269 |> Map.drop(~w(scope scopes client_id redirect_uri))
270 |> Map.put("state", state)
272 # Handing the request to Ueberauth
273 redirect(conn, to: o_auth_path(conn, :request, provider, params))
276 def request(conn, params) do
278 if params["provider"] do
279 "Unsupported OAuth provider: #{params["provider"]}."
285 |> put_flash(:error, message)
289 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
290 params = callback_params(params)
291 messages = for e <- Map.get(failure, :errors, []), do: e.message
292 message = Enum.join(messages, "; ")
295 |> put_flash(:error, "Failed to authenticate: #{message}.")
296 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
299 def callback(conn, params) do
300 params = callback_params(params)
302 with {:ok, registration} <- Authenticator.get_registration(conn) do
303 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
305 case Repo.get_assoc(registration, :user) do
307 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
310 registration_params =
311 Map.merge(auth_attrs, %{
312 "nickname" => Registration.nickname(registration),
313 "email" => Registration.email(registration)
317 |> put_session(:registration_id, registration.id)
318 |> registration_details(%{"authorization" => registration_params})
323 |> put_flash(:error, "Failed to set up user account.")
324 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
328 defp callback_params(%{"state" => state} = params) do
329 Map.merge(params, Jason.decode!(state))
332 def registration_details(conn, %{"authorization" => auth_attrs}) do
333 render(conn, "register.html", %{
334 client_id: auth_attrs["client_id"],
335 redirect_uri: auth_attrs["redirect_uri"],
336 state: auth_attrs["state"],
337 scopes: Scopes.fetch_scopes(auth_attrs, []),
338 nickname: auth_attrs["nickname"],
339 email: auth_attrs["email"]
343 def register(conn, %{"authorization" => _, "op" => "connect"} = params) do
344 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
345 %Registration{} = registration <- Repo.get(Registration, registration_id),
347 {:create_authorization, do_create_authorization(conn, params)},
348 %User{} = user <- Repo.preload(auth, :user).user,
349 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
351 |> put_session_registration_id(nil)
352 |> after_create_authorization(auth, params)
354 {:create_authorization, error} ->
355 {:register, handle_create_authorization_error(conn, error, params)}
358 {:register, :generic_error}
362 def register(conn, %{"authorization" => _, "op" => "register"} = params) do
363 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
364 %Registration{} = registration <- Repo.get(Registration, registration_id),
365 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
367 |> put_session_registration_id(nil)
368 |> create_authorization(
373 {:error, changeset} ->
375 Enum.map(changeset.errors, fn {field, {error, _}} ->
383 "ap_id has already been taken",
384 "nickname has already been taken"
388 |> put_status(:forbidden)
389 |> put_flash(:error, "Error: #{message}.")
390 |> registration_details(params)
393 {:register, :generic_error}
397 defp do_create_authorization(
402 "client_id" => client_id,
403 "redirect_uri" => redirect_uri
408 with {_, {:ok, %User{} = user}} <-
409 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
410 %App{} = app <- Repo.get_by(App, client_id: client_id),
411 true <- redirect_uri in String.split(app.redirect_uris),
412 {:ok, scopes} <- validate_scopes(app, auth_attrs),
413 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
414 Authorization.create_authorization(app, user, scopes)
418 # Special case: Local MastodonFE
419 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
421 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
423 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
425 defp put_session_registration_id(conn, registration_id),
426 do: put_session(conn, :registration_id, registration_id)
428 @spec validate_scopes(App.t(), map()) ::
429 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
430 defp validate_scopes(app, params) do
432 |> Scopes.fetch_scopes(app.scopes)
433 |> Scopes.validates(app.scopes)