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
17 import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2]
19 if Pleroma.Config.oauth_consumer_enabled?(), do: plug(Ueberauth)
24 action_fallback(Pleroma.Web.OAuth.FallbackController)
26 def authorize(%{assigns: %{token: %Token{} = token}} = conn, params) do
27 if ControllerHelper.truthy_param?(params["force_login"]) do
28 do_authorize(conn, params)
31 if is_binary(params["redirect_uri"]) do
32 params["redirect_uri"]
34 app = Repo.preload(token, :app).app
41 redirect(conn, external: redirect_uri(conn, redirect_uri))
45 def authorize(conn, params), do: do_authorize(conn, params)
47 defp do_authorize(conn, %{"authorization" => auth_attrs}) do
48 app = Repo.get_by(App, client_id: auth_attrs["client_id"])
49 available_scopes = (app && app.scopes) || []
50 scopes = oauth_scopes(auth_attrs, nil) || available_scopes
52 render(conn, Authenticator.auth_template(), %{
53 response_type: auth_attrs["response_type"],
54 client_id: auth_attrs["client_id"],
55 available_scopes: available_scopes,
57 redirect_uri: auth_attrs["redirect_uri"],
58 state: auth_attrs["state"],
63 defp do_authorize(conn, auth_attrs), do: do_authorize(conn, %{"authorization" => auth_attrs})
65 def create_authorization(
67 %{"authorization" => _} = params,
70 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
71 after_create_authorization(conn, auth, params)
74 handle_create_authorization_error(conn, error, params)
78 def after_create_authorization(conn, auth, %{
79 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
81 redirect_uri = redirect_uri(conn, redirect_uri)
83 if redirect_uri == "urn:ietf:wg:oauth:2.0:oob" do
84 render(conn, "results.html", %{
88 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
89 url = "#{redirect_uri}#{connector}"
90 url_params = %{:code => auth.token}
93 if auth_attrs["state"] do
94 Map.put(url_params, :state, auth_attrs["state"])
99 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
101 redirect(conn, external: url)
105 defp handle_create_authorization_error(
108 %{"authorization" => _} = params
110 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
111 # Per https://github.com/tootsuite/mastodon/blob/
112 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
114 |> put_flash(:error, "This action is outside the authorized scopes")
115 |> put_status(:unauthorized)
119 defp handle_create_authorization_error(
121 {:auth_active, false},
122 %{"authorization" => _} = params
124 # Per https://github.com/tootsuite/mastodon/blob/
125 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
127 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
128 |> put_status(:forbidden)
132 defp handle_create_authorization_error(conn, error, %{"authorization" => _}) do
133 Authenticator.handle_error(conn, error)
136 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
137 with %App{} = app <- get_app_from_request(conn, params),
138 fixed_token = fix_padding(params["code"]),
139 %Authorization{} = auth <-
140 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
141 %User{} = user <- User.get_by_id(auth.user_id),
142 {:ok, token} <- Token.exchange_token(app, auth),
143 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
145 token_type: "Bearer",
146 access_token: token.token,
147 refresh_token: token.refresh_token,
148 created_at: DateTime.to_unix(inserted_at),
150 scope: Enum.join(token.scopes, " "),
157 put_status(conn, 400)
158 |> json(%{error: "Invalid credentials"})
164 %{"grant_type" => "password"} = params
166 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn)},
167 %App{} = app <- get_app_from_request(conn, params),
168 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
169 {:user_active, true} <- {:user_active, !user.info.deactivated},
170 scopes <- oauth_scopes(params, app.scopes),
171 [] <- scopes -- app.scopes,
172 true <- Enum.any?(scopes),
173 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
174 {:ok, token} <- Token.exchange_token(app, auth) do
176 token_type: "Bearer",
177 access_token: token.token,
178 refresh_token: token.refresh_token,
180 scope: Enum.join(token.scopes, " "),
186 {:auth_active, false} ->
187 # Per https://github.com/tootsuite/mastodon/blob/
188 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
190 |> put_status(:forbidden)
191 |> json(%{error: "Your login is missing a confirmed e-mail address"})
193 {:user_active, false} ->
195 |> put_status(:forbidden)
196 |> json(%{error: "Your account is currently disabled"})
199 put_status(conn, 400)
200 |> json(%{error: "Invalid credentials"})
206 %{"grant_type" => "password", "name" => name, "password" => _password} = params
210 |> Map.delete("name")
211 |> Map.put("username", name)
213 token_exchange(conn, params)
216 def token_revoke(conn, %{"token" => token} = params) do
217 with %App{} = app <- get_app_from_request(conn, params),
218 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
219 {:ok, %Token{}} <- Repo.delete(token) do
223 # RFC 7009: invalid tokens [in the request] do not cause an error response
228 @doc "Prepares OAuth request to provider for Ueberauth"
229 def prepare_request(conn, %{"provider" => provider, "authorization" => auth_attrs}) do
231 oauth_scopes(auth_attrs, [])
236 |> Map.delete("scopes")
237 |> Map.put("scope", scope)
242 |> Map.drop(~w(scope scopes client_id redirect_uri))
243 |> Map.put("state", state)
245 # Handing the request to Ueberauth
246 redirect(conn, to: o_auth_path(conn, :request, provider, params))
249 def request(conn, params) do
251 if params["provider"] do
252 "Unsupported OAuth provider: #{params["provider"]}."
258 |> put_flash(:error, message)
262 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
263 params = callback_params(params)
264 messages = for e <- Map.get(failure, :errors, []), do: e.message
265 message = Enum.join(messages, "; ")
268 |> put_flash(:error, "Failed to authenticate: #{message}.")
269 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
272 def callback(conn, params) do
273 params = callback_params(params)
275 with {:ok, registration} <- Authenticator.get_registration(conn) do
276 user = Repo.preload(registration, :user).user
277 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
280 create_authorization(
282 %{"authorization" => auth_attrs},
286 registration_params =
287 Map.merge(auth_attrs, %{
288 "nickname" => Registration.nickname(registration),
289 "email" => Registration.email(registration)
293 |> put_session(:registration_id, registration.id)
294 |> registration_details(%{"authorization" => registration_params})
299 |> put_flash(:error, "Failed to set up user account.")
300 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
304 defp callback_params(%{"state" => state} = params) do
305 Map.merge(params, Poison.decode!(state))
308 def registration_details(conn, %{"authorization" => auth_attrs}) do
309 render(conn, "register.html", %{
310 client_id: auth_attrs["client_id"],
311 redirect_uri: auth_attrs["redirect_uri"],
312 state: auth_attrs["state"],
313 scopes: oauth_scopes(auth_attrs, []),
314 nickname: auth_attrs["nickname"],
315 email: auth_attrs["email"]
319 def register(conn, %{"authorization" => _, "op" => "connect"} = params) do
320 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
321 %Registration{} = registration <- Repo.get(Registration, registration_id),
323 {:create_authorization, do_create_authorization(conn, params)},
324 %User{} = user <- Repo.preload(auth, :user).user,
325 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
327 |> put_session_registration_id(nil)
328 |> after_create_authorization(auth, params)
330 {:create_authorization, error} ->
331 {:register, handle_create_authorization_error(conn, error, params)}
334 {:register, :generic_error}
338 def register(conn, %{"authorization" => _, "op" => "register"} = params) do
339 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
340 %Registration{} = registration <- Repo.get(Registration, registration_id),
341 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
343 |> put_session_registration_id(nil)
344 |> create_authorization(
349 {:error, changeset} ->
351 Enum.map(changeset.errors, fn {field, {error, _}} ->
359 "ap_id has already been taken",
360 "nickname has already been taken"
364 |> put_status(:forbidden)
365 |> put_flash(:error, "Error: #{message}.")
366 |> registration_details(params)
369 {:register, :generic_error}
373 defp do_create_authorization(
378 "client_id" => client_id,
379 "redirect_uri" => redirect_uri
384 with {_, {:ok, %User{} = user}} <-
385 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
386 %App{} = app <- Repo.get_by(App, client_id: client_id),
387 true <- redirect_uri in String.split(app.redirect_uris),
388 scopes <- oauth_scopes(auth_attrs, []),
389 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
390 # Note: `scope` param is intentionally not optional in this context
391 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
392 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
393 Authorization.create_authorization(app, user, scopes)
397 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
398 # decoding it. Investigate sometime.
399 defp fix_padding(token) do
402 |> Base.url_decode64!(padding: false)
403 |> Base.url_encode64(padding: false)
406 defp get_app_from_request(conn, params) do
407 # Per RFC 6749, HTTP Basic is preferred to body params
408 {client_id, client_secret} =
409 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
410 {:ok, decoded} <- Base.decode64(encoded),
412 String.split(decoded, ":")
413 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
416 _ -> {params["client_id"], params["client_secret"]}
419 if client_id && client_secret do
422 client_id: client_id,
423 client_secret: client_secret
430 # Special case: Local MastodonFE
431 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
433 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
435 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
437 defp put_session_registration_id(conn, registration_id),
438 do: put_session(conn, :registration_id, registration_id)