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 "state" => params["state"],
257 "scopes" => oauth_scopes(params, nil)
261 create_authorization(
263 %{"authorization" => auth_params},
267 registration_params =
268 Map.merge(auth_params, %{
269 "nickname" => Registration.nickname(registration),
270 "email" => Registration.email(registration)
274 |> put_session(:registration_id, registration.id)
275 |> redirect(to: o_auth_path(conn, :registration_details, registration_params))
280 |> put_flash(:error, "Failed to set up user account.")
281 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
285 defp callback_params(%{"state" => state} = params) do
286 Map.merge(params, Poison.decode!(state))
289 def registration_details(conn, params) do
290 render(conn, "register.html", %{
291 client_id: params["client_id"],
292 redirect_uri: params["redirect_uri"],
293 state: params["state"],
294 scopes: oauth_scopes(params, []),
295 nickname: params["nickname"],
296 email: params["email"]
300 def register(conn, %{"op" => "connect"} = params) do
301 create_authorization_params = %{
302 "authorization" => Map.merge(params, %{"name" => params["auth_name"]})
305 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
306 %Registration{} = registration <- Repo.get(Registration, registration_id),
307 {:ok, auth} <- do_create_authorization(conn, create_authorization_params),
308 %User{} = user <- Repo.preload(auth, :user).user,
309 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
311 |> put_session_registration_id(nil)
312 |> create_authorization(
313 create_authorization_params,
318 params = Map.delete(params, "password")
321 |> put_flash(:error, "Unknown error, please try again.")
322 |> redirect(to: o_auth_path(conn, :registration_details, params))
326 def register(conn, params) do
327 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
328 %Registration{} = registration <- Repo.get(Registration, registration_id),
329 {:ok, user} <- Authenticator.create_from_registration(conn, params, registration) do
331 |> put_session_registration_id(nil)
332 |> create_authorization(
334 "authorization" => %{
335 "client_id" => params["client_id"],
336 "redirect_uri" => params["redirect_uri"],
337 "scopes" => oauth_scopes(params, nil)
343 {:error, changeset} ->
345 Enum.map(changeset.errors, fn {field, {error, _}} ->
353 "ap_id has already been taken",
354 "nickname has already been taken"
358 |> put_flash(:error, "Error: #{message}.")
359 |> redirect(to: o_auth_path(conn, :registration_details, params))
363 |> put_flash(:error, "Unknown error, please try again.")
364 |> redirect(to: o_auth_path(conn, :registration_details, params))
368 defp do_create_authorization(
373 "client_id" => client_id,
374 "redirect_uri" => redirect_uri
379 with {_, {:ok, %User{} = user}} <-
380 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn, params)},
381 %App{} = app <- Repo.get_by(App, client_id: client_id),
382 true <- redirect_uri in String.split(app.redirect_uris),
383 scopes <- oauth_scopes(auth_params, []),
384 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
385 # Note: `scope` param is intentionally not optional in this context
386 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
387 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
388 Authorization.create_authorization(app, user, scopes)
392 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
393 # decoding it. Investigate sometime.
394 defp fix_padding(token) do
397 |> Base.url_decode64!(padding: false)
398 |> Base.url_encode64(padding: false)
401 defp get_app_from_request(conn, params) do
402 # Per RFC 6749, HTTP Basic is preferred to body params
403 {client_id, client_secret} =
404 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
405 {:ok, decoded} <- Base.decode64(encoded),
407 String.split(decoded, ":")
408 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
411 _ -> {params["client_id"], params["client_secret"]}
414 if client_id && client_secret do
417 client_id: client_id,
418 client_secret: client_secret
425 # Special case: Local MastodonFE
426 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
428 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
430 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
432 defp put_session_registration_id(conn, registration_id),
433 do: put_session(conn, :registration_id, registration_id)