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
10 alias Pleroma.Registration
11 alias Pleroma.Web.Auth.Authenticator
12 alias Pleroma.Web.OAuth.App
13 alias Pleroma.Web.OAuth.Authorization
14 alias Pleroma.Web.OAuth.Token
16 import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2]
18 if Pleroma.Config.get([:auth, :oauth_consumer_enabled]), do: plug(Ueberauth)
23 action_fallback(Pleroma.Web.OAuth.FallbackController)
25 def authorize(conn, params) do
26 app = Repo.get_by(App, client_id: params["client_id"])
27 available_scopes = (app && app.scopes) || []
28 scopes = oauth_scopes(params, nil) || available_scopes
30 render(conn, Authenticator.auth_template(), %{
31 response_type: params["response_type"],
32 client_id: params["client_id"],
33 available_scopes: available_scopes,
35 redirect_uri: params["redirect_uri"],
36 state: params["state"],
41 def create_authorization(
44 "authorization" => %{"redirect_uri" => redirect_uri} = auth_params
49 (opts[:auth] && {:ok, opts[:auth]}) ||
50 do_create_authorization(conn, params, opts[:user]) do
51 redirect_uri = redirect_uri(conn, redirect_uri)
54 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
55 render(conn, "results.html", %{
60 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
61 url = "#{redirect_uri}#{connector}"
62 url_params = %{:code => auth.token}
65 if auth_params["state"] do
66 Map.put(url_params, :state, auth_params["state"])
71 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
73 redirect(conn, external: url)
76 {scopes_issue, _} when scopes_issue in [:unsupported_scopes, :missing_scopes] ->
78 |> put_flash(:error, "Permissions not specified.")
79 |> put_status(:unauthorized)
80 |> authorize(auth_params)
82 {:auth_active, false} ->
84 |> put_flash(:error, "Account confirmation pending.")
85 |> put_status(:forbidden)
86 |> authorize(auth_params)
89 Authenticator.handle_error(conn, error)
93 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
94 with %App{} = app <- get_app_from_request(conn, params),
95 fixed_token = fix_padding(params["code"]),
96 %Authorization{} = auth <-
97 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
98 %User{} = user <- Repo.get(User, auth.user_id),
99 {:ok, token} <- Token.exchange_token(app, auth),
100 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
102 token_type: "Bearer",
103 access_token: token.token,
104 refresh_token: token.refresh_token,
105 created_at: DateTime.to_unix(inserted_at),
107 scope: Enum.join(token.scopes, " "),
114 put_status(conn, 400)
115 |> json(%{error: "Invalid credentials"})
121 %{"grant_type" => "password"} = params
123 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn, params)},
124 %App{} = app <- get_app_from_request(conn, params),
125 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
126 scopes <- oauth_scopes(params, app.scopes),
127 [] <- scopes -- app.scopes,
128 true <- Enum.any?(scopes),
129 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
130 {:ok, token} <- Token.exchange_token(app, auth) do
132 token_type: "Bearer",
133 access_token: token.token,
134 refresh_token: token.refresh_token,
136 scope: Enum.join(token.scopes, " "),
142 {:auth_active, false} ->
144 |> put_status(:forbidden)
145 |> json(%{error: "Account confirmation pending"})
148 put_status(conn, 400)
149 |> json(%{error: "Invalid credentials"})
155 %{"grant_type" => "password", "name" => name, "password" => _password} = params
159 |> Map.delete("name")
160 |> Map.put("username", name)
162 token_exchange(conn, params)
165 def token_revoke(conn, %{"token" => token} = params) do
166 with %App{} = app <- get_app_from_request(conn, params),
167 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
168 {:ok, %Token{}} <- Repo.delete(token) do
172 # RFC 7009: invalid tokens [in the request] do not cause an error response
177 def prepare_request(conn, %{"provider" => provider} = params) do
179 oauth_scopes(params, [])
184 |> Map.delete("scopes")
185 |> Map.put("scope", scope)
190 |> Map.drop(~w(scope scopes client_id redirect_uri))
191 |> Map.put("state", state)
193 redirect(conn, to: o_auth_path(conn, :request, provider, params))
196 def request(conn, params) do
198 if params["provider"] do
199 "Unsupported OAuth provider: #{params["provider"]}."
205 |> put_flash(:error, message)
209 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
210 params = callback_params(params)
211 messages = for e <- Map.get(failure, :errors, []), do: e.message
212 message = Enum.join(messages, "; ")
215 |> put_flash(:error, "Failed to authenticate: #{message}.")
216 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
219 def callback(conn, params) do
220 params = callback_params(params)
222 with {:ok, registration} <- Authenticator.get_registration(conn, params) do
223 user = Repo.preload(registration, :user).user
226 "client_id" => params["client_id"],
227 "redirect_uri" => params["redirect_uri"],
228 "scopes" => oauth_scopes(params, nil)
232 create_authorization(
234 %{"authorization" => auth_params},
238 registration_params =
239 Map.merge(auth_params, %{
240 "nickname" => Registration.nickname(registration),
241 "email" => Registration.email(registration)
245 |> put_session(:registration_id, registration.id)
246 |> redirect(to: o_auth_path(conn, :registration_details, registration_params))
251 |> put_flash(:error, "Failed to set up user account.")
252 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
256 defp callback_params(%{"state" => state} = params) do
257 Map.merge(params, Poison.decode!(state))
260 def registration_details(conn, params) do
261 render(conn, "register.html", %{
262 client_id: params["client_id"],
263 redirect_uri: params["redirect_uri"],
264 scopes: oauth_scopes(params, []),
265 nickname: params["nickname"],
266 email: params["email"]
270 def register(conn, %{"op" => "connect"} = params) do
271 create_authorization_params = %{
272 "authorization" => Map.merge(params, %{"name" => params["auth_name"]})
275 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
276 %Registration{} = registration <- Repo.get(Registration, registration_id),
277 {:ok, auth} <- do_create_authorization(conn, create_authorization_params),
278 %User{} = user <- Repo.preload(auth, :user).user,
279 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
281 |> put_session_registration_id(nil)
282 |> create_authorization(
283 create_authorization_params,
289 |> put_flash(:error, "Unknown error, please try again.")
290 |> redirect(to: o_auth_path(conn, :registration_details, params))
294 def register(conn, params) do
295 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
296 %Registration{} = registration <- Repo.get(Registration, registration_id),
297 {:ok, user} <- Authenticator.create_from_registration(conn, params, registration) do
299 |> put_session_registration_id(nil)
300 |> create_authorization(
302 "authorization" => %{
303 "client_id" => params["client_id"],
304 "redirect_uri" => params["redirect_uri"],
305 "scopes" => oauth_scopes(params, nil)
311 {:error, changeset} ->
313 Enum.map(changeset.errors, fn {field, {error, _}} ->
321 "ap_id has already been taken",
322 "nickname has already been taken"
326 |> put_flash(:error, "Error: #{message}.")
327 |> redirect(to: o_auth_path(conn, :registration_details, params))
331 |> put_flash(:error, "Unknown error, please try again.")
332 |> redirect(to: o_auth_path(conn, :registration_details, params))
336 defp do_create_authorization(
341 "client_id" => client_id,
342 "redirect_uri" => redirect_uri
347 with {_, {:ok, %User{} = user}} <-
348 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn, params)},
349 %App{} = app <- Repo.get_by(App, client_id: client_id),
350 true <- redirect_uri in String.split(app.redirect_uris),
351 scopes <- oauth_scopes(auth_params, []),
352 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
353 # Note: `scope` param is intentionally not optional in this context
354 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
355 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
356 Authorization.create_authorization(app, user, scopes)
360 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
361 # decoding it. Investigate sometime.
362 defp fix_padding(token) do
365 |> Base.url_decode64!(padding: false)
366 |> Base.url_encode64(padding: false)
369 defp get_app_from_request(conn, params) do
370 # Per RFC 6749, HTTP Basic is preferred to body params
371 {client_id, client_secret} =
372 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
373 {:ok, decoded} <- Base.decode64(encoded),
375 String.split(decoded, ":")
376 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
379 _ -> {params["client_id"], params["client_secret"]}
382 if client_id && client_secret do
385 client_id: client_id,
386 client_secret: client_secret
393 # Special case: Local MastodonFE
394 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
396 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
398 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
400 defp put_session_registration_id(conn, registration_id),
401 do: put_session(conn, :registration_id, registration_id)