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, params) do
48 app = Repo.get_by(App, client_id: params["client_id"])
49 available_scopes = (app && app.scopes) || []
50 scopes = oauth_scopes(params, nil) || available_scopes
52 render(conn, Authenticator.auth_template(), %{
53 response_type: params["response_type"],
54 client_id: params["client_id"],
55 available_scopes: available_scopes,
57 redirect_uri: params["redirect_uri"],
58 state: params["state"],
63 def create_authorization(
65 %{"authorization" => auth_params} = params,
68 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
69 after_create_authorization(conn, auth, auth_params)
72 handle_create_authorization_error(conn, error, auth_params)
76 def after_create_authorization(conn, auth, %{"redirect_uri" => redirect_uri} = auth_params) do
77 redirect_uri = redirect_uri(conn, redirect_uri)
79 if redirect_uri == "urn:ietf:wg:oauth:2.0:oob" do
80 render(conn, "results.html", %{
84 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
85 url = "#{redirect_uri}#{connector}"
86 url_params = %{:code => auth.token}
89 if auth_params["state"] do
90 Map.put(url_params, :state, auth_params["state"])
95 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
97 redirect(conn, external: url)
101 defp handle_create_authorization_error(conn, {scopes_issue, _}, auth_params)
102 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
103 # Per https://github.com/tootsuite/mastodon/blob/
104 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
106 |> put_flash(:error, "This action is outside the authorized scopes")
107 |> put_status(:unauthorized)
108 |> authorize(auth_params)
111 defp handle_create_authorization_error(conn, {:auth_active, false}, auth_params) do
112 # Per https://github.com/tootsuite/mastodon/blob/
113 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
115 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
116 |> put_status(:forbidden)
117 |> authorize(auth_params)
120 defp handle_create_authorization_error(conn, error, _auth_params) do
121 Authenticator.handle_error(conn, error)
124 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
125 with %App{} = app <- get_app_from_request(conn, params),
126 fixed_token = fix_padding(params["code"]),
127 %Authorization{} = auth <-
128 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
129 %User{} = user <- User.get_by_id(auth.user_id),
130 {:ok, token} <- Token.exchange_token(app, auth),
131 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
133 token_type: "Bearer",
134 access_token: token.token,
135 refresh_token: token.refresh_token,
136 created_at: DateTime.to_unix(inserted_at),
138 scope: Enum.join(token.scopes, " "),
145 put_status(conn, 400)
146 |> json(%{error: "Invalid credentials"})
152 %{"grant_type" => "password"} = params
154 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn, params)},
155 %App{} = app <- get_app_from_request(conn, params),
156 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
157 {:user_active, true} <- {:user_active, !user.info.deactivated},
158 scopes <- oauth_scopes(params, app.scopes),
159 [] <- scopes -- app.scopes,
160 true <- Enum.any?(scopes),
161 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
162 {:ok, token} <- Token.exchange_token(app, auth) do
164 token_type: "Bearer",
165 access_token: token.token,
166 refresh_token: token.refresh_token,
168 scope: Enum.join(token.scopes, " "),
174 {:auth_active, false} ->
175 # Per https://github.com/tootsuite/mastodon/blob/
176 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
178 |> put_status(:forbidden)
179 |> json(%{error: "Your login is missing a confirmed e-mail address"})
181 {:user_active, false} ->
183 |> put_status(:forbidden)
184 |> json(%{error: "Your account is currently disabled"})
187 put_status(conn, 400)
188 |> json(%{error: "Invalid credentials"})
194 %{"grant_type" => "password", "name" => name, "password" => _password} = params
198 |> Map.delete("name")
199 |> Map.put("username", name)
201 token_exchange(conn, params)
204 def token_revoke(conn, %{"token" => token} = params) do
205 with %App{} = app <- get_app_from_request(conn, params),
206 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
207 {:ok, %Token{}} <- Repo.delete(token) do
211 # RFC 7009: invalid tokens [in the request] do not cause an error response
216 @doc "Prepares OAuth request to provider for Ueberauth"
217 def prepare_request(conn, %{"provider" => provider} = params) do
219 oauth_scopes(params, [])
224 |> Map.delete("scopes")
225 |> Map.put("scope", scope)
230 |> Map.drop(~w(scope scopes client_id redirect_uri))
231 |> Map.put("state", state)
233 # Handing the request to Ueberauth
234 redirect(conn, to: o_auth_path(conn, :request, provider, params))
237 def request(conn, params) do
239 if params["provider"] do
240 "Unsupported OAuth provider: #{params["provider"]}."
246 |> put_flash(:error, message)
250 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
251 params = callback_params(params)
252 messages = for e <- Map.get(failure, :errors, []), do: e.message
253 message = Enum.join(messages, "; ")
256 |> put_flash(:error, "Failed to authenticate: #{message}.")
257 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
260 def callback(conn, params) do
261 params = callback_params(params)
263 with {:ok, registration} <- Authenticator.get_registration(conn, params) do
264 user = Repo.preload(registration, :user).user
265 auth_params = Map.take(params, ~w(client_id redirect_uri scope scopes state))
268 create_authorization(
270 %{"authorization" => auth_params},
274 registration_params =
275 Map.merge(auth_params, %{
276 "nickname" => Registration.nickname(registration),
277 "email" => Registration.email(registration)
281 |> put_session(:registration_id, registration.id)
282 |> registration_details(registration_params)
287 |> put_flash(:error, "Failed to set up user account.")
288 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
292 defp callback_params(%{"state" => state} = params) do
293 Map.merge(params, Poison.decode!(state))
296 def registration_details(conn, params) do
297 render(conn, "register.html", %{
298 client_id: params["client_id"],
299 redirect_uri: params["redirect_uri"],
300 state: params["state"],
301 scopes: oauth_scopes(params, []),
302 nickname: params["nickname"],
303 email: params["email"]
307 def register(conn, %{"op" => "connect"} = params) do
308 authorization_params = Map.put(params, "name", params["auth_name"])
309 create_authorization_params = %{"authorization" => authorization_params}
311 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
312 %Registration{} = registration <- Repo.get(Registration, registration_id),
314 {:create_authorization, do_create_authorization(conn, create_authorization_params)},
315 %User{} = user <- Repo.preload(auth, :user).user,
316 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
318 |> put_session_registration_id(nil)
319 |> after_create_authorization(auth, authorization_params)
321 {:create_authorization, error} ->
322 {:register, handle_create_authorization_error(conn, error, create_authorization_params)}
325 {:register, :generic_error}
329 def register(conn, %{"op" => "register"} = params) do
330 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
331 %Registration{} = registration <- Repo.get(Registration, registration_id),
332 {:ok, user} <- Authenticator.create_from_registration(conn, params, registration) do
334 |> put_session_registration_id(nil)
335 |> create_authorization(
337 "authorization" => %{
338 "client_id" => params["client_id"],
339 "redirect_uri" => params["redirect_uri"],
340 "scopes" => oauth_scopes(params, nil)
346 {:error, changeset} ->
348 Enum.map(changeset.errors, fn {field, {error, _}} ->
356 "ap_id has already been taken",
357 "nickname has already been taken"
361 |> put_status(:forbidden)
362 |> put_flash(:error, "Error: #{message}.")
363 |> registration_details(params)
366 {:register, :generic_error}
370 defp do_create_authorization(
375 "client_id" => client_id,
376 "redirect_uri" => redirect_uri
381 with {_, {:ok, %User{} = user}} <-
382 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn, params)},
383 %App{} = app <- Repo.get_by(App, client_id: client_id),
384 true <- redirect_uri in String.split(app.redirect_uris),
385 scopes <- oauth_scopes(auth_params, []),
386 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
387 # Note: `scope` param is intentionally not optional in this context
388 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
389 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
390 Authorization.create_authorization(app, user, scopes)
394 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
395 # decoding it. Investigate sometime.
396 defp fix_padding(token) do
399 |> Base.url_decode64!(padding: false)
400 |> Base.url_encode64(padding: false)
403 defp get_app_from_request(conn, params) do
404 # Per RFC 6749, HTTP Basic is preferred to body params
405 {client_id, client_secret} =
406 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
407 {:ok, decoded} <- Base.decode64(encoded),
409 String.split(decoded, ":")
410 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
413 _ -> {params["client_id"], params["client_secret"]}
416 if client_id && client_secret do
419 client_id: client_id,
420 client_secret: client_secret
427 # Special case: Local MastodonFE
428 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
430 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
432 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
434 defp put_session_registration_id(conn, registration_id),
435 do: put_session(conn, :registration_id, registration_id)