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.Web.Auth.Authenticator
11 alias Pleroma.Web.OAuth.App
12 alias Pleroma.Web.OAuth.Authorization
13 alias Pleroma.Web.OAuth.Token
15 import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2]
17 if Pleroma.Config.get([:auth, :oauth_consumer_enabled]), do: plug(Ueberauth)
22 action_fallback(Pleroma.Web.OAuth.FallbackController)
24 def request(conn, params) do
26 if params["provider"] do
27 "Unsupported OAuth provider: #{params["provider"]}."
33 |> put_flash(:error, message)
37 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, %{"redirect_uri" => redirect_uri}) do
38 messages = for e <- Map.get(failure, :errors, []), do: e.message
39 message = Enum.join(messages, "; ")
42 |> put_flash(:error, "Failed to authenticate: #{message}.")
43 |> redirect(external: redirect_uri(conn, redirect_uri))
48 %{"client_id" => client_id, "redirect_uri" => redirect_uri} = params
50 with {:ok, user} <- Authenticator.get_or_create_user_by_oauth(conn, params) do
51 do_create_authorization(
55 "client_id" => client_id,
56 "redirect_uri" => redirect_uri,
57 "scope" => oauth_scopes(params, nil)
65 |> put_flash(:error, "Failed to set up user account.")
66 |> redirect(external: redirect_uri(conn, redirect_uri))
70 def authorize(conn, params) do
71 app = Repo.get_by(App, client_id: params["client_id"])
72 available_scopes = (app && app.scopes) || []
73 scopes = oauth_scopes(params, nil) || available_scopes
75 render(conn, Authenticator.auth_template(), %{
76 response_type: params["response_type"],
77 client_id: params["client_id"],
78 available_scopes: available_scopes,
80 redirect_uri: params["redirect_uri"],
81 state: params["state"],
86 def create_authorization(conn, params), do: do_create_authorization(conn, params, nil)
88 defp do_create_authorization(
93 "client_id" => client_id,
94 "redirect_uri" => redirect_uri
99 with {_, {:ok, %User{} = user}} <-
100 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn, params)},
101 %App{} = app <- Repo.get_by(App, client_id: client_id),
102 true <- redirect_uri in String.split(app.redirect_uris),
103 scopes <- oauth_scopes(auth_params, []),
104 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
105 # Note: `scope` param is intentionally not optional in this context
106 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
107 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
108 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
109 redirect_uri = redirect_uri(conn, redirect_uri)
112 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
113 render(conn, "results.html", %{
118 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
119 url = "#{redirect_uri}#{connector}"
120 url_params = %{:code => auth.token}
123 if auth_params["state"] do
124 Map.put(url_params, :state, auth_params["state"])
129 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
131 redirect(conn, external: url)
134 {scopes_issue, _} when scopes_issue in [:unsupported_scopes, :missing_scopes] ->
136 |> put_flash(:error, "Permissions not specified.")
137 |> put_status(:unauthorized)
138 |> authorize(auth_params)
140 {:auth_active, false} ->
142 |> put_flash(:error, "Account confirmation pending.")
143 |> put_status(:forbidden)
144 |> authorize(auth_params)
147 Authenticator.handle_error(conn, error)
151 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
152 with %App{} = app <- get_app_from_request(conn, params),
153 fixed_token = fix_padding(params["code"]),
154 %Authorization{} = auth <-
155 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
156 %User{} = user <- Repo.get(User, auth.user_id),
157 {:ok, token} <- Token.exchange_token(app, auth),
158 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
160 token_type: "Bearer",
161 access_token: token.token,
162 refresh_token: token.refresh_token,
163 created_at: DateTime.to_unix(inserted_at),
165 scope: Enum.join(token.scopes, " "),
172 put_status(conn, 400)
173 |> json(%{error: "Invalid credentials"})
179 %{"grant_type" => "password"} = params
181 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn, params)},
182 %App{} = app <- get_app_from_request(conn, params),
183 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
184 scopes <- oauth_scopes(params, app.scopes),
185 [] <- scopes -- app.scopes,
186 true <- Enum.any?(scopes),
187 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
188 {:ok, token} <- Token.exchange_token(app, auth) do
190 token_type: "Bearer",
191 access_token: token.token,
192 refresh_token: token.refresh_token,
194 scope: Enum.join(token.scopes, " "),
200 {:auth_active, false} ->
202 |> put_status(:forbidden)
203 |> json(%{error: "Account confirmation pending"})
206 put_status(conn, 400)
207 |> json(%{error: "Invalid credentials"})
213 %{"grant_type" => "password", "name" => name, "password" => _password} = params
217 |> Map.delete("name")
218 |> Map.put("username", name)
220 token_exchange(conn, params)
223 def token_revoke(conn, %{"token" => token} = params) do
224 with %App{} = app <- get_app_from_request(conn, params),
225 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
226 {:ok, %Token{}} <- Repo.delete(token) do
230 # RFC 7009: invalid tokens [in the request] do not cause an error response
235 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
236 # decoding it. Investigate sometime.
237 defp fix_padding(token) do
240 |> Base.url_decode64!(padding: false)
241 |> Base.url_encode64(padding: false)
244 defp get_app_from_request(conn, params) do
245 # Per RFC 6749, HTTP Basic is preferred to body params
246 {client_id, client_secret} =
247 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
248 {:ok, decoded} <- Base.decode64(encoded),
250 String.split(decoded, ":")
251 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
254 _ -> {params["client_id"], params["client_secret"]}
257 if client_id && client_secret do
260 client_id: client_id,
261 client_secret: client_secret
268 # Special case: Local MastodonFE
269 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
271 defp redirect_uri(_conn, redirect_uri), do: redirect_uri