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.get([:auth, :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(
66 "authorization" => %{"redirect_uri" => redirect_uri} = auth_params
71 (opts[:auth] && {:ok, opts[:auth]}) ||
72 do_create_authorization(conn, params, opts[:user]) do
73 redirect_uri = redirect_uri(conn, redirect_uri)
76 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
77 render(conn, "results.html", %{
82 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
83 url = "#{redirect_uri}#{connector}"
84 url_params = %{:code => auth.token}
87 if auth_params["state"] do
88 Map.put(url_params, :state, auth_params["state"])
93 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
95 redirect(conn, external: url)
98 {scopes_issue, _} when scopes_issue in [:unsupported_scopes, :missing_scopes] ->
99 # Per https://github.com/tootsuite/mastodon/blob/
100 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
102 |> put_flash(:error, "This action is outside the authorized scopes")
103 |> put_status(:unauthorized)
104 |> authorize(auth_params)
106 {:auth_active, false} ->
107 # Per https://github.com/tootsuite/mastodon/blob/
108 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
110 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
111 |> put_status(:forbidden)
112 |> authorize(auth_params)
115 Authenticator.handle_error(conn, error)
119 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
120 with %App{} = app <- get_app_from_request(conn, params),
121 fixed_token = fix_padding(params["code"]),
122 %Authorization{} = auth <-
123 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
124 %User{} = user <- User.get_by_id(auth.user_id),
125 {:ok, token} <- Token.exchange_token(app, auth),
126 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
128 token_type: "Bearer",
129 access_token: token.token,
130 refresh_token: token.refresh_token,
131 created_at: DateTime.to_unix(inserted_at),
133 scope: Enum.join(token.scopes, " "),
140 put_status(conn, 400)
141 |> json(%{error: "Invalid credentials"})
147 %{"grant_type" => "password"} = params
149 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn, params)},
150 %App{} = app <- get_app_from_request(conn, params),
151 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
152 scopes <- oauth_scopes(params, app.scopes),
153 [] <- scopes -- app.scopes,
154 true <- Enum.any?(scopes),
155 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
156 {:ok, token} <- Token.exchange_token(app, auth) do
158 token_type: "Bearer",
159 access_token: token.token,
160 refresh_token: token.refresh_token,
162 scope: Enum.join(token.scopes, " "),
168 {:auth_active, false} ->
169 # Per https://github.com/tootsuite/mastodon/blob/
170 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
172 |> put_status(:forbidden)
173 |> json(%{error: "Your login is missing a confirmed e-mail address"})
176 put_status(conn, 400)
177 |> json(%{error: "Invalid credentials"})
183 %{"grant_type" => "password", "name" => name, "password" => _password} = params
187 |> Map.delete("name")
188 |> Map.put("username", name)
190 token_exchange(conn, params)
193 def token_revoke(conn, %{"token" => token} = params) do
194 with %App{} = app <- get_app_from_request(conn, params),
195 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
196 {:ok, %Token{}} <- Repo.delete(token) do
200 # RFC 7009: invalid tokens [in the request] do not cause an error response
205 def prepare_request(conn, %{"provider" => provider} = params) do
207 oauth_scopes(params, [])
212 |> Map.delete("scopes")
213 |> Map.put("scope", scope)
218 |> Map.drop(~w(scope scopes client_id redirect_uri))
219 |> Map.put("state", state)
221 redirect(conn, to: o_auth_path(conn, :request, provider, params))
224 def request(conn, params) do
226 if params["provider"] do
227 "Unsupported OAuth provider: #{params["provider"]}."
233 |> put_flash(:error, message)
237 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
238 params = callback_params(params)
239 messages = for e <- Map.get(failure, :errors, []), do: e.message
240 message = Enum.join(messages, "; ")
243 |> put_flash(:error, "Failed to authenticate: #{message}.")
244 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
247 def callback(conn, params) do
248 params = callback_params(params)
250 with {:ok, registration} <- Authenticator.get_registration(conn, params) do
251 user = Repo.preload(registration, :user).user
254 "client_id" => params["client_id"],
255 "redirect_uri" => params["redirect_uri"],
256 "scopes" => oauth_scopes(params, nil)
260 create_authorization(
262 %{"authorization" => auth_params},
266 registration_params =
267 Map.merge(auth_params, %{
268 "nickname" => Registration.nickname(registration),
269 "email" => Registration.email(registration)
273 |> put_session(:registration_id, registration.id)
274 |> redirect(to: o_auth_path(conn, :registration_details, registration_params))
279 |> put_flash(:error, "Failed to set up user account.")
280 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
284 defp callback_params(%{"state" => state} = params) do
285 Map.merge(params, Poison.decode!(state))
288 def registration_details(conn, params) do
289 render(conn, "register.html", %{
290 client_id: params["client_id"],
291 redirect_uri: params["redirect_uri"],
292 scopes: oauth_scopes(params, []),
293 nickname: params["nickname"],
294 email: params["email"]
298 def register(conn, %{"op" => "connect"} = params) do
299 create_authorization_params = %{
300 "authorization" => Map.merge(params, %{"name" => params["auth_name"]})
303 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
304 %Registration{} = registration <- Repo.get(Registration, registration_id),
305 {:ok, auth} <- do_create_authorization(conn, create_authorization_params),
306 %User{} = user <- Repo.preload(auth, :user).user,
307 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
309 |> put_session_registration_id(nil)
310 |> create_authorization(
311 create_authorization_params,
317 |> put_flash(:error, "Unknown error, please try again.")
318 |> redirect(to: o_auth_path(conn, :registration_details, params))
322 def register(conn, params) do
323 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
324 %Registration{} = registration <- Repo.get(Registration, registration_id),
325 {:ok, user} <- Authenticator.create_from_registration(conn, params, registration) do
327 |> put_session_registration_id(nil)
328 |> create_authorization(
330 "authorization" => %{
331 "client_id" => params["client_id"],
332 "redirect_uri" => params["redirect_uri"],
333 "scopes" => oauth_scopes(params, nil)
339 {:error, changeset} ->
341 Enum.map(changeset.errors, fn {field, {error, _}} ->
349 "ap_id has already been taken",
350 "nickname has already been taken"
354 |> put_flash(:error, "Error: #{message}.")
355 |> redirect(to: o_auth_path(conn, :registration_details, params))
359 |> put_flash(:error, "Unknown error, please try again.")
360 |> redirect(to: o_auth_path(conn, :registration_details, params))
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)