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)
22 @expires_in Pleroma.Config.get([:oauth2, :token_expires_in], 600)
27 action_fallback(Pleroma.Web.OAuth.FallbackController)
29 # Note: this definition is only called from error-handling methods with `conn.params` as 2nd arg
30 def authorize(conn, %{"authorization" => _} = params) do
31 {auth_attrs, params} = Map.pop(params, "authorization")
32 authorize(conn, Map.merge(params, auth_attrs))
35 def authorize(%{assigns: %{token: %Token{} = token}} = conn, params) do
36 if ControllerHelper.truthy_param?(params["force_login"]) do
37 do_authorize(conn, params)
40 if is_binary(params["redirect_uri"]) do
41 params["redirect_uri"]
43 app = Repo.preload(token, :app).app
50 redirect(conn, external: redirect_uri(conn, redirect_uri))
54 def authorize(conn, params), do: do_authorize(conn, params)
56 defp do_authorize(conn, params) do
57 app = Repo.get_by(App, client_id: params["client_id"])
58 available_scopes = (app && app.scopes) || []
59 scopes = Scopes.fetch_scopes(params, available_scopes)
61 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
62 render(conn, Authenticator.auth_template(), %{
63 response_type: params["response_type"],
64 client_id: params["client_id"],
65 available_scopes: available_scopes,
67 redirect_uri: params["redirect_uri"],
68 state: params["state"],
73 def create_authorization(
75 %{"authorization" => _} = params,
78 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
79 after_create_authorization(conn, auth, params)
82 handle_create_authorization_error(conn, error, params)
86 def after_create_authorization(conn, auth, %{
87 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
89 redirect_uri = redirect_uri(conn, redirect_uri)
91 if redirect_uri == "urn:ietf:wg:oauth:2.0:oob" do
92 render(conn, "results.html", %{
96 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
97 url = "#{redirect_uri}#{connector}"
98 url_params = %{:code => auth.token}
101 if auth_attrs["state"] do
102 Map.put(url_params, :state, auth_attrs["state"])
107 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
109 redirect(conn, external: url)
113 defp handle_create_authorization_error(
115 {:error, scopes_issue},
116 %{"authorization" => _} = params
118 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
119 # Per https://github.com/tootsuite/mastodon/blob/
120 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
122 |> put_flash(:error, "This action is outside the authorized scopes")
123 |> put_status(:unauthorized)
127 defp handle_create_authorization_error(
129 {:auth_active, false},
130 %{"authorization" => _} = params
132 # Per https://github.com/tootsuite/mastodon/blob/
133 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
135 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
136 |> put_status(:forbidden)
140 defp handle_create_authorization_error(conn, error, %{"authorization" => _}) do
141 Authenticator.handle_error(conn, error)
144 @doc "Renew access_token with refresh_token"
147 %{"grant_type" => "refresh_token", "refresh_token" => token} = params
149 with %App{} = app <- get_app_from_request(conn, params),
150 {:ok, %{user: user} = token} <- Token.get_by_refresh_token(app, token),
151 {:ok, token} <- RefreshToken.grant(token) do
152 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
154 json(conn, response_token(user, token, response_attrs))
157 put_status(conn, 400)
158 |> json(%{error: "Invalid credentials"})
162 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
163 with %App{} = app <- get_app_from_request(conn, params),
164 fixed_token = Token.Utils.fix_padding(params["code"]),
165 {:ok, auth} <- Authorization.get_by_token(app, fixed_token),
166 %User{} = user <- User.get_cached_by_id(auth.user_id),
167 {:ok, token} <- Token.exchange_token(app, auth) do
168 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
170 json(conn, response_token(user, token, response_attrs))
173 put_status(conn, 400)
174 |> json(%{error: "Invalid credentials"})
180 %{"grant_type" => "password"} = params
182 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn)},
183 %App{} = app <- get_app_from_request(conn, params),
184 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
185 {:user_active, true} <- {:user_active, !user.info.deactivated},
186 {:ok, scopes} <- validate_scopes(app, params),
187 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
188 {:ok, token} <- Token.exchange_token(app, auth) do
189 json(conn, response_token(user, token))
191 {:auth_active, false} ->
192 # Per https://github.com/tootsuite/mastodon/blob/
193 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
195 |> put_status(:forbidden)
196 |> json(%{error: "Your login is missing a confirmed e-mail address"})
198 {:user_active, false} ->
200 |> put_status(:forbidden)
201 |> json(%{error: "Your account is currently disabled"})
204 put_status(conn, 400)
205 |> json(%{error: "Invalid credentials"})
211 %{"grant_type" => "password", "name" => name, "password" => _password} = params
215 |> Map.delete("name")
216 |> Map.put("username", name)
218 token_exchange(conn, params)
222 def token_exchange(conn, params), do: bad_request(conn, params)
224 def token_revoke(conn, %{"token" => _token} = params) do
225 with %App{} = app <- get_app_from_request(conn, params),
226 {:ok, _token} <- RevokeToken.revoke(app, params) do
230 # RFC 7009: invalid tokens [in the request] do not cause an error response
235 def token_revoke(conn, params), do: bad_request(conn, params)
237 # Response for bad request
238 defp bad_request(conn, _) do
241 |> json(%{error: "Bad request"})
244 @doc "Prepares OAuth request to provider for Ueberauth"
245 def prepare_request(conn, %{"provider" => provider, "authorization" => auth_attrs}) do
248 |> Scopes.fetch_scopes([])
249 |> Scopes.to_string()
253 |> Map.delete("scopes")
254 |> Map.put("scope", scope)
259 |> Map.drop(~w(scope scopes client_id redirect_uri))
260 |> Map.put("state", state)
262 # Handing the request to Ueberauth
263 redirect(conn, to: o_auth_path(conn, :request, provider, params))
266 def request(conn, params) do
268 if params["provider"] do
269 "Unsupported OAuth provider: #{params["provider"]}."
275 |> put_flash(:error, message)
279 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
280 params = callback_params(params)
281 messages = for e <- Map.get(failure, :errors, []), do: e.message
282 message = Enum.join(messages, "; ")
285 |> put_flash(:error, "Failed to authenticate: #{message}.")
286 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
289 def callback(conn, params) do
290 params = callback_params(params)
292 with {:ok, registration} <- Authenticator.get_registration(conn) do
293 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
295 case Repo.get_assoc(registration, :user) do
297 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
300 registration_params =
301 Map.merge(auth_attrs, %{
302 "nickname" => Registration.nickname(registration),
303 "email" => Registration.email(registration)
307 |> put_session(:registration_id, registration.id)
308 |> registration_details(%{"authorization" => registration_params})
313 |> put_flash(:error, "Failed to set up user account.")
314 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
318 defp callback_params(%{"state" => state} = params) do
319 Map.merge(params, Poison.decode!(state))
322 def registration_details(conn, %{"authorization" => auth_attrs}) do
323 render(conn, "register.html", %{
324 client_id: auth_attrs["client_id"],
325 redirect_uri: auth_attrs["redirect_uri"],
326 state: auth_attrs["state"],
327 scopes: Scopes.fetch_scopes(auth_attrs, []),
328 nickname: auth_attrs["nickname"],
329 email: auth_attrs["email"]
333 def register(conn, %{"authorization" => _, "op" => "connect"} = params) do
334 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
335 %Registration{} = registration <- Repo.get(Registration, registration_id),
337 {:create_authorization, do_create_authorization(conn, params)},
338 %User{} = user <- Repo.preload(auth, :user).user,
339 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
341 |> put_session_registration_id(nil)
342 |> after_create_authorization(auth, params)
344 {:create_authorization, error} ->
345 {:register, handle_create_authorization_error(conn, error, params)}
348 {:register, :generic_error}
352 def register(conn, %{"authorization" => _, "op" => "register"} = params) do
353 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
354 %Registration{} = registration <- Repo.get(Registration, registration_id),
355 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
357 |> put_session_registration_id(nil)
358 |> create_authorization(
363 {:error, changeset} ->
365 Enum.map(changeset.errors, fn {field, {error, _}} ->
373 "ap_id has already been taken",
374 "nickname has already been taken"
378 |> put_status(:forbidden)
379 |> put_flash(:error, "Error: #{message}.")
380 |> registration_details(params)
383 {:register, :generic_error}
387 defp do_create_authorization(
392 "client_id" => client_id,
393 "redirect_uri" => redirect_uri
398 with {_, {:ok, %User{} = user}} <-
399 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
400 %App{} = app <- Repo.get_by(App, client_id: client_id),
401 true <- redirect_uri in String.split(app.redirect_uris),
402 {:ok, scopes} <- validate_scopes(app, auth_attrs),
403 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
404 Authorization.create_authorization(app, user, scopes)
408 defp get_app_from_request(conn, params) do
410 |> fetch_client_credentials(params)
414 defp fetch_client({id, secret}) when is_binary(id) and is_binary(secret) do
415 Repo.get_by(App, client_id: id, client_secret: secret)
418 defp fetch_client({_id, _secret}), do: nil
420 defp fetch_client_credentials(conn, params) do
421 # Per RFC 6749, HTTP Basic is preferred to body params
422 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
423 {:ok, decoded} <- Base.decode64(encoded),
426 String.split(decoded, ":"),
427 fn s -> URI.decode_www_form(s) end
431 _ -> {params["client_id"], params["client_secret"]}
435 # Special case: Local MastodonFE
436 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
438 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
440 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
442 defp put_session_registration_id(conn, registration_id),
443 do: put_session(conn, :registration_id, registration_id)
445 defp response_token(%User{} = user, token, opts \\ %{}) do
447 token_type: "Bearer",
448 access_token: token.token,
449 refresh_token: token.refresh_token,
450 expires_in: @expires_in,
451 scope: Enum.join(token.scopes, " "),
457 @spec validate_scopes(App.t(), map()) ::
458 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
459 defp validate_scopes(app, params) do
461 |> Scopes.fetch_scopes(app.scopes)
462 |> Scopes.validates(app.scopes)