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 scopes <- oauth_scopes(params, app.scopes),
158 [] <- scopes -- app.scopes,
159 true <- Enum.any?(scopes),
160 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
161 {:ok, token} <- Token.exchange_token(app, auth) do
163 token_type: "Bearer",
164 access_token: token.token,
165 refresh_token: token.refresh_token,
167 scope: Enum.join(token.scopes, " "),
173 {:auth_active, false} ->
174 # Per https://github.com/tootsuite/mastodon/blob/
175 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
177 |> put_status(:forbidden)
178 |> json(%{error: "Your login is missing a confirmed e-mail address"})
181 put_status(conn, 400)
182 |> json(%{error: "Invalid credentials"})
188 %{"grant_type" => "password", "name" => name, "password" => _password} = params
192 |> Map.delete("name")
193 |> Map.put("username", name)
195 token_exchange(conn, params)
198 def token_revoke(conn, %{"token" => token} = params) do
199 with %App{} = app <- get_app_from_request(conn, params),
200 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
201 {:ok, %Token{}} <- Repo.delete(token) do
205 # RFC 7009: invalid tokens [in the request] do not cause an error response
210 @doc "Prepares OAuth request to provider for Ueberauth"
211 def prepare_request(conn, %{"provider" => provider} = params) do
213 oauth_scopes(params, [])
218 |> Map.delete("scopes")
219 |> Map.put("scope", scope)
224 |> Map.drop(~w(scope scopes client_id redirect_uri))
225 |> Map.put("state", state)
227 # Handing the request to Ueberauth
228 redirect(conn, to: o_auth_path(conn, :request, provider, params))
231 def request(conn, params) do
233 if params["provider"] do
234 "Unsupported OAuth provider: #{params["provider"]}."
240 |> put_flash(:error, message)
244 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
245 params = callback_params(params)
246 messages = for e <- Map.get(failure, :errors, []), do: e.message
247 message = Enum.join(messages, "; ")
250 |> put_flash(:error, "Failed to authenticate: #{message}.")
251 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
254 def callback(conn, params) do
255 params = callback_params(params)
257 with {:ok, registration} <- Authenticator.get_registration(conn, params) do
258 user = Repo.preload(registration, :user).user
259 auth_params = Map.take(params, ~w(client_id redirect_uri scope scopes state))
262 create_authorization(
264 %{"authorization" => auth_params},
268 registration_params =
269 Map.merge(auth_params, %{
270 "nickname" => Registration.nickname(registration),
271 "email" => Registration.email(registration)
275 |> put_session(:registration_id, registration.id)
276 |> registration_details(registration_params)
281 |> put_flash(:error, "Failed to set up user account.")
282 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
286 defp callback_params(%{"state" => state} = params) do
287 Map.merge(params, Poison.decode!(state))
290 def registration_details(conn, params) do
291 render(conn, "register.html", %{
292 client_id: params["client_id"],
293 redirect_uri: params["redirect_uri"],
294 state: params["state"],
295 scopes: oauth_scopes(params, []),
296 nickname: params["nickname"],
297 email: params["email"]
301 def register(conn, %{"op" => "connect"} = params) do
302 authorization_params = Map.put(params, "name", params["auth_name"])
303 create_authorization_params = %{"authorization" => authorization_params}
305 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
306 %Registration{} = registration <- Repo.get(Registration, registration_id),
308 {:create_authorization, do_create_authorization(conn, create_authorization_params)},
309 %User{} = user <- Repo.preload(auth, :user).user,
310 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
312 |> put_session_registration_id(nil)
313 |> after_create_authorization(auth, authorization_params)
315 {:create_authorization, error} ->
316 {:register, handle_create_authorization_error(conn, error, create_authorization_params)}
319 {:register, :generic_error}
323 def register(conn, %{"op" => "register"} = params) do
324 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
325 %Registration{} = registration <- Repo.get(Registration, registration_id),
326 {:ok, user} <- Authenticator.create_from_registration(conn, params, registration) do
328 |> put_session_registration_id(nil)
329 |> create_authorization(
331 "authorization" => %{
332 "client_id" => params["client_id"],
333 "redirect_uri" => params["redirect_uri"],
334 "scopes" => oauth_scopes(params, nil)
340 {:error, changeset} ->
342 Enum.map(changeset.errors, fn {field, {error, _}} ->
350 "ap_id has already been taken",
351 "nickname has already been taken"
355 |> put_status(:forbidden)
356 |> put_flash(:error, "Error: #{message}.")
357 |> registration_details(params)
360 {:register, :generic_error}
364 defp do_create_authorization(
369 "client_id" => client_id,
370 "redirect_uri" => redirect_uri
375 with {_, {:ok, %User{} = user}} <-
376 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn, params)},
377 %App{} = app <- Repo.get_by(App, client_id: client_id),
378 true <- redirect_uri in String.split(app.redirect_uris),
379 scopes <- oauth_scopes(auth_params, []),
380 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
381 # Note: `scope` param is intentionally not optional in this context
382 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
383 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
384 Authorization.create_authorization(app, user, scopes)
388 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
389 # decoding it. Investigate sometime.
390 defp fix_padding(token) do
393 |> Base.url_decode64!(padding: false)
394 |> Base.url_encode64(padding: false)
397 defp get_app_from_request(conn, params) do
398 # Per RFC 6749, HTTP Basic is preferred to body params
399 {client_id, client_secret} =
400 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
401 {:ok, decoded} <- Base.decode64(encoded),
403 String.split(decoded, ":")
404 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
407 _ -> {params["client_id"], params["client_secret"]}
410 if client_id && client_secret do
413 client_id: client_id,
414 client_secret: client_secret
421 # Special case: Local MastodonFE
422 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
424 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
426 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
428 defp put_session_registration_id(conn, registration_id),
429 do: put_session(conn, :registration_id, registration_id)