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.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] ->
77 # Per https://github.com/tootsuite/mastodon/blob/
78 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
80 |> put_flash(:error, "This action is outside the authorized scopes")
81 |> put_status(:unauthorized)
82 |> authorize(auth_params)
84 {:auth_active, false} ->
85 # Per https://github.com/tootsuite/mastodon/blob/
86 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
88 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
89 |> put_status(:forbidden)
90 |> authorize(auth_params)
93 Authenticator.handle_error(conn, error)
97 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
98 with %App{} = app <- get_app_from_request(conn, params),
99 fixed_token = fix_padding(params["code"]),
100 %Authorization{} = auth <-
101 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
102 %User{} = user <- Repo.get(User, auth.user_id),
103 {:ok, token} <- Token.exchange_token(app, auth),
104 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
106 token_type: "Bearer",
107 access_token: token.token,
108 refresh_token: token.refresh_token,
109 created_at: DateTime.to_unix(inserted_at),
111 scope: Enum.join(token.scopes, " "),
118 put_status(conn, 400)
119 |> json(%{error: "Invalid credentials"})
125 %{"grant_type" => "password"} = params
127 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn, params)},
128 %App{} = app <- get_app_from_request(conn, params),
129 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
130 scopes <- oauth_scopes(params, app.scopes),
131 [] <- scopes -- app.scopes,
132 true <- Enum.any?(scopes),
133 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
134 {:ok, token} <- Token.exchange_token(app, auth) do
136 token_type: "Bearer",
137 access_token: token.token,
138 refresh_token: token.refresh_token,
140 scope: Enum.join(token.scopes, " "),
146 {:auth_active, false} ->
147 # Per https://github.com/tootsuite/mastodon/blob/
148 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
150 |> put_status(:forbidden)
151 |> json(%{error: "Your login is missing a confirmed e-mail address"})
154 put_status(conn, 400)
155 |> json(%{error: "Invalid credentials"})
161 %{"grant_type" => "password", "name" => name, "password" => _password} = params
165 |> Map.delete("name")
166 |> Map.put("username", name)
168 token_exchange(conn, params)
171 def token_revoke(conn, %{"token" => token} = params) do
172 with %App{} = app <- get_app_from_request(conn, params),
173 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
174 {:ok, %Token{}} <- Repo.delete(token) do
178 # RFC 7009: invalid tokens [in the request] do not cause an error response
183 def prepare_request(conn, %{"provider" => provider} = params) do
185 oauth_scopes(params, [])
190 |> Map.delete("scopes")
191 |> Map.put("scope", scope)
196 |> Map.drop(~w(scope scopes client_id redirect_uri))
197 |> Map.put("state", state)
199 redirect(conn, to: o_auth_path(conn, :request, provider, params))
202 def request(conn, params) do
204 if params["provider"] do
205 "Unsupported OAuth provider: #{params["provider"]}."
211 |> put_flash(:error, message)
215 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
216 params = callback_params(params)
217 messages = for e <- Map.get(failure, :errors, []), do: e.message
218 message = Enum.join(messages, "; ")
221 |> put_flash(:error, "Failed to authenticate: #{message}.")
222 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
225 def callback(conn, params) do
226 params = callback_params(params)
228 with {:ok, registration} <- Authenticator.get_registration(conn, params) do
229 user = Repo.preload(registration, :user).user
232 "client_id" => params["client_id"],
233 "redirect_uri" => params["redirect_uri"],
234 "scopes" => oauth_scopes(params, nil)
238 create_authorization(
240 %{"authorization" => auth_params},
244 registration_params =
245 Map.merge(auth_params, %{
246 "nickname" => Registration.nickname(registration),
247 "email" => Registration.email(registration)
251 |> put_session(:registration_id, registration.id)
252 |> redirect(to: o_auth_path(conn, :registration_details, registration_params))
257 |> put_flash(:error, "Failed to set up user account.")
258 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
262 defp callback_params(%{"state" => state} = params) do
263 Map.merge(params, Poison.decode!(state))
266 def registration_details(conn, params) do
267 render(conn, "register.html", %{
268 client_id: params["client_id"],
269 redirect_uri: params["redirect_uri"],
270 scopes: oauth_scopes(params, []),
271 nickname: params["nickname"],
272 email: params["email"]
276 def register(conn, %{"op" => "connect"} = params) do
277 create_authorization_params = %{
278 "authorization" => Map.merge(params, %{"name" => params["auth_name"]})
281 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
282 %Registration{} = registration <- Repo.get(Registration, registration_id),
283 {:ok, auth} <- do_create_authorization(conn, create_authorization_params),
284 %User{} = user <- Repo.preload(auth, :user).user,
285 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
287 |> put_session_registration_id(nil)
288 |> create_authorization(
289 create_authorization_params,
295 |> put_flash(:error, "Unknown error, please try again.")
296 |> redirect(to: o_auth_path(conn, :registration_details, params))
300 def register(conn, params) do
301 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
302 %Registration{} = registration <- Repo.get(Registration, registration_id),
303 {:ok, user} <- Authenticator.create_from_registration(conn, params, registration) do
305 |> put_session_registration_id(nil)
306 |> create_authorization(
308 "authorization" => %{
309 "client_id" => params["client_id"],
310 "redirect_uri" => params["redirect_uri"],
311 "scopes" => oauth_scopes(params, nil)
317 {:error, changeset} ->
319 Enum.map(changeset.errors, fn {field, {error, _}} ->
327 "ap_id has already been taken",
328 "nickname has already been taken"
332 |> put_flash(:error, "Error: #{message}.")
333 |> redirect(to: o_auth_path(conn, :registration_details, params))
337 |> put_flash(:error, "Unknown error, please try again.")
338 |> redirect(to: o_auth_path(conn, :registration_details, params))
342 defp do_create_authorization(
347 "client_id" => client_id,
348 "redirect_uri" => redirect_uri
353 with {_, {:ok, %User{} = user}} <-
354 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn, params)},
355 %App{} = app <- Repo.get_by(App, client_id: client_id),
356 true <- redirect_uri in String.split(app.redirect_uris),
357 scopes <- oauth_scopes(auth_params, []),
358 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
359 # Note: `scope` param is intentionally not optional in this context
360 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
361 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
362 Authorization.create_authorization(app, user, scopes)
366 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
367 # decoding it. Investigate sometime.
368 defp fix_padding(token) do
371 |> Base.url_decode64!(padding: false)
372 |> Base.url_encode64(padding: false)
375 defp get_app_from_request(conn, params) do
376 # Per RFC 6749, HTTP Basic is preferred to body params
377 {client_id, client_secret} =
378 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
379 {:ok, decoded} <- Base.decode64(encoded),
381 String.split(decoded, ":")
382 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
385 _ -> {params["client_id"], params["client_secret"]}
388 if client_id && client_secret do
391 client_id: client_id,
392 client_secret: client_secret
399 # Special case: Local MastodonFE
400 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
402 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
404 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
406 defp put_session_registration_id(conn, registration_id),
407 do: put_session(conn, :registration_id, registration_id)