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
19 import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2]
21 if Pleroma.Config.oauth_consumer_enabled?(), do: plug(Ueberauth)
23 @expires_in Pleroma.Config.get([:oauth2, :token_expires_in], 600)
28 action_fallback(Pleroma.Web.OAuth.FallbackController)
30 # Note: this definition is only called from error-handling methods with `conn.params` as 2nd arg
31 def authorize(conn, %{"authorization" => _} = params) do
32 {auth_attrs, params} = Map.pop(params, "authorization")
33 authorize(conn, Map.merge(params, auth_attrs))
36 def authorize(%{assigns: %{token: %Token{} = token}} = conn, params) do
37 if ControllerHelper.truthy_param?(params["force_login"]) do
38 do_authorize(conn, params)
41 if is_binary(params["redirect_uri"]) do
42 params["redirect_uri"]
44 app = Repo.preload(token, :app).app
51 redirect(conn, external: redirect_uri(conn, redirect_uri))
55 def authorize(conn, params), do: do_authorize(conn, params)
57 defp do_authorize(conn, params) do
58 app = Repo.get_by(App, client_id: params["client_id"])
59 available_scopes = (app && app.scopes) || []
60 scopes = oauth_scopes(params, nil) || available_scopes
62 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
63 render(conn, Authenticator.auth_template(), %{
64 response_type: params["response_type"],
65 client_id: params["client_id"],
66 available_scopes: available_scopes,
68 redirect_uri: params["redirect_uri"],
69 state: params["state"],
74 def create_authorization(
76 %{"authorization" => _} = params,
79 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
80 after_create_authorization(conn, auth, params)
83 handle_create_authorization_error(conn, error, params)
87 def after_create_authorization(conn, auth, %{
88 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
90 redirect_uri = redirect_uri(conn, redirect_uri)
92 if redirect_uri == "urn:ietf:wg:oauth:2.0:oob" do
93 render(conn, "results.html", %{
97 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
98 url = "#{redirect_uri}#{connector}"
99 url_params = %{:code => auth.token}
102 if auth_attrs["state"] do
103 Map.put(url_params, :state, auth_attrs["state"])
108 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
110 redirect(conn, external: url)
114 defp handle_create_authorization_error(
117 %{"authorization" => _} = params
119 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
120 # Per https://github.com/tootsuite/mastodon/blob/
121 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
123 |> put_flash(:error, "This action is outside the authorized scopes")
124 |> put_status(:unauthorized)
128 defp handle_create_authorization_error(
130 {:auth_active, false},
131 %{"authorization" => _} = params
133 # Per https://github.com/tootsuite/mastodon/blob/
134 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
136 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
137 |> put_status(:forbidden)
141 defp handle_create_authorization_error(conn, error, %{"authorization" => _}) do
142 Authenticator.handle_error(conn, error)
145 @doc "Renew access_token with refresh_token"
148 %{"grant_type" => "refresh_token", "refresh_token" => token} = params
150 with %App{} = app <- get_app_from_request(conn, params),
151 {:ok, %{user: user} = token} <- Token.get_by_refresh_token(app, token),
152 {:ok, token} <- RefreshToken.grant(token) do
153 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
155 json(conn, response_token(user, token, response_attrs))
158 put_status(conn, 400)
159 |> json(%{error: "Invalid credentials"})
163 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
164 with %App{} = app <- get_app_from_request(conn, params),
165 fixed_token = Token.Utils.fix_padding(params["code"]),
166 {:ok, auth} <- Authorization.get_by_token(app, fixed_token),
167 %User{} = user <- User.get_cached_by_id(auth.user_id),
168 {:ok, token} <- Token.exchange_token(app, auth) do
169 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
171 json(conn, response_token(user, token, response_attrs))
174 put_status(conn, 400)
175 |> json(%{error: "Invalid credentials"})
181 %{"grant_type" => "password"} = params
183 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn)},
184 %App{} = app <- get_app_from_request(conn, params),
185 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
186 {:user_active, true} <- {:user_active, !user.info.deactivated},
187 scopes <- oauth_scopes(params, app.scopes),
188 [] <- scopes -- app.scopes,
189 true <- Enum.any?(scopes),
190 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
191 {:ok, token} <- Token.exchange_token(app, auth) do
192 json(conn, response_token(user, token))
194 {:auth_active, false} ->
195 # Per https://github.com/tootsuite/mastodon/blob/
196 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
198 |> put_status(:forbidden)
199 |> json(%{error: "Your login is missing a confirmed e-mail address"})
201 {:user_active, false} ->
203 |> put_status(:forbidden)
204 |> json(%{error: "Your account is currently disabled"})
207 put_status(conn, 400)
208 |> json(%{error: "Invalid credentials"})
214 %{"grant_type" => "password", "name" => name, "password" => _password} = params
218 |> Map.delete("name")
219 |> Map.put("username", name)
221 token_exchange(conn, params)
225 def token_exchange(conn, params), do: bad_request(conn, params)
227 def token_revoke(conn, %{"token" => _token} = params) do
228 with %App{} = app <- get_app_from_request(conn, params),
229 {:ok, _token} <- RevokeToken.revoke(app, params) do
233 # RFC 7009: invalid tokens [in the request] do not cause an error response
238 def token_revoke(conn, params), do: bad_request(conn, params)
240 # Response for bad request
241 defp bad_request(conn, _) do
244 |> json(%{error: "Bad request"})
247 @doc "Prepares OAuth request to provider for Ueberauth"
248 def prepare_request(conn, %{"provider" => provider, "authorization" => auth_attrs}) do
250 oauth_scopes(auth_attrs, [])
255 |> Map.delete("scopes")
256 |> Map.put("scope", scope)
261 |> Map.drop(~w(scope scopes client_id redirect_uri))
262 |> Map.put("state", state)
264 # Handing the request to Ueberauth
265 redirect(conn, to: o_auth_path(conn, :request, provider, params))
268 def request(conn, params) do
270 if params["provider"] do
271 "Unsupported OAuth provider: #{params["provider"]}."
277 |> put_flash(:error, message)
281 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
282 params = callback_params(params)
283 messages = for e <- Map.get(failure, :errors, []), do: e.message
284 message = Enum.join(messages, "; ")
287 |> put_flash(:error, "Failed to authenticate: #{message}.")
288 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
291 def callback(conn, params) do
292 params = callback_params(params)
294 with {:ok, registration} <- Authenticator.get_registration(conn) do
295 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
297 case Repo.get_assoc(registration, :user) do
299 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
302 registration_params =
303 Map.merge(auth_attrs, %{
304 "nickname" => Registration.nickname(registration),
305 "email" => Registration.email(registration)
309 |> put_session(:registration_id, registration.id)
310 |> registration_details(%{"authorization" => registration_params})
315 |> put_flash(:error, "Failed to set up user account.")
316 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
320 defp callback_params(%{"state" => state} = params) do
321 Map.merge(params, Poison.decode!(state))
324 def registration_details(conn, %{"authorization" => auth_attrs}) do
325 render(conn, "register.html", %{
326 client_id: auth_attrs["client_id"],
327 redirect_uri: auth_attrs["redirect_uri"],
328 state: auth_attrs["state"],
329 scopes: oauth_scopes(auth_attrs, []),
330 nickname: auth_attrs["nickname"],
331 email: auth_attrs["email"]
335 def register(conn, %{"authorization" => _, "op" => "connect"} = params) do
336 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
337 %Registration{} = registration <- Repo.get(Registration, registration_id),
339 {:create_authorization, do_create_authorization(conn, params)},
340 %User{} = user <- Repo.preload(auth, :user).user,
341 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
343 |> put_session_registration_id(nil)
344 |> after_create_authorization(auth, params)
346 {:create_authorization, error} ->
347 {:register, handle_create_authorization_error(conn, error, params)}
350 {:register, :generic_error}
354 def register(conn, %{"authorization" => _, "op" => "register"} = params) do
355 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
356 %Registration{} = registration <- Repo.get(Registration, registration_id),
357 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
359 |> put_session_registration_id(nil)
360 |> create_authorization(
365 {:error, changeset} ->
367 Enum.map(changeset.errors, fn {field, {error, _}} ->
375 "ap_id has already been taken",
376 "nickname has already been taken"
380 |> put_status(:forbidden)
381 |> put_flash(:error, "Error: #{message}.")
382 |> registration_details(params)
385 {:register, :generic_error}
389 defp do_create_authorization(
394 "client_id" => client_id,
395 "redirect_uri" => redirect_uri
400 with {_, {:ok, %User{} = user}} <-
401 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
402 %App{} = app <- Repo.get_by(App, client_id: client_id),
403 true <- redirect_uri in String.split(app.redirect_uris),
404 scopes <- oauth_scopes(auth_attrs, []),
405 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
406 # Note: `scope` param is intentionally not optional in this context
407 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
408 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
409 Authorization.create_authorization(app, user, scopes)
413 defp get_app_from_request(conn, params) do
415 |> fetch_client_credentials(params)
419 defp fetch_client({id, secret}) when is_binary(id) and is_binary(secret) do
420 Repo.get_by(App, client_id: id, client_secret: secret)
423 defp fetch_client({_id, _secret}), do: nil
425 defp fetch_client_credentials(conn, params) do
426 # Per RFC 6749, HTTP Basic is preferred to body params
427 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
428 {:ok, decoded} <- Base.decode64(encoded),
431 String.split(decoded, ":"),
432 fn s -> URI.decode_www_form(s) end
436 _ -> {params["client_id"], params["client_secret"]}
440 # Special case: Local MastodonFE
441 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
443 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
445 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
447 defp put_session_registration_id(conn, registration_id),
448 do: put_session(conn, :registration_id, registration_id)
450 defp response_token(%User{} = user, token, opts \\ %{}) do
452 token_type: "Bearer",
453 access_token: token.token,
454 refresh_token: token.refresh_token,
455 expires_in: @expires_in,
456 scope: Enum.join(token.scopes, " "),