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.ControllerHelper
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]
21 action_fallback(Pleroma.Web.OAuth.FallbackController)
23 def authorize(%{assigns: %{token: %Token{} = token}} = conn, params) do
24 if ControllerHelper.truthy_param?(params["force_login"]) do
25 do_authorize(conn, params)
28 if is_binary(params["redirect_uri"]) do
29 params["redirect_uri"]
31 app = Repo.preload(token, :app).app
38 redirect(conn, external: redirect_uri(conn, redirect_uri))
42 def authorize(conn, params), do: do_authorize(conn, params)
44 defp do_authorize(conn, params) do
45 app = Repo.get_by(App, client_id: params["client_id"])
46 available_scopes = (app && app.scopes) || []
47 scopes = oauth_scopes(params, nil) || available_scopes
49 render(conn, Authenticator.auth_template(), %{
50 response_type: params["response_type"],
51 client_id: params["client_id"],
52 available_scopes: available_scopes,
54 redirect_uri: params["redirect_uri"],
55 state: params["state"],
60 def create_authorization(conn, %{
63 "client_id" => client_id,
64 "redirect_uri" => redirect_uri
67 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn)},
68 %App{} = app <- Repo.get_by(App, client_id: client_id),
69 true <- redirect_uri in String.split(app.redirect_uris),
70 scopes <- oauth_scopes(auth_params, []),
71 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
72 # Note: `scope` param is intentionally not optional in this context
73 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
74 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
75 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
76 redirect_uri = redirect_uri(conn, redirect_uri)
79 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
80 render(conn, "results.html", %{
85 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
86 url = "#{redirect_uri}#{connector}"
87 url_params = %{:code => auth.token}
90 if auth_params["state"] do
91 Map.put(url_params, :state, auth_params["state"])
96 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
98 redirect(conn, external: url)
101 {scopes_issue, _} when scopes_issue in [:unsupported_scopes, :missing_scopes] ->
102 # Per https://github.com/tootsuite/mastodon/blob/
103 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
105 |> put_flash(:error, "This action is outside the authorized scopes")
106 |> put_status(:unauthorized)
107 |> authorize(auth_params)
109 {:auth_active, false} ->
110 # Per https://github.com/tootsuite/mastodon/blob/
111 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
113 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
114 |> put_status(:forbidden)
115 |> authorize(auth_params)
118 Authenticator.handle_error(conn, error)
122 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
123 with %App{} = app <- get_app_from_request(conn, params),
124 fixed_token = fix_padding(params["code"]),
125 %Authorization{} = auth <-
126 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
127 %User{} = user <- User.get_by_id(auth.user_id),
128 {:ok, token} <- Token.exchange_token(app, auth),
129 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
131 token_type: "Bearer",
132 access_token: token.token,
133 refresh_token: token.refresh_token,
134 created_at: DateTime.to_unix(inserted_at),
136 scope: Enum.join(token.scopes, " "),
143 put_status(conn, 400)
144 |> json(%{error: "Invalid credentials"})
150 %{"grant_type" => "password"} = params
152 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn)},
153 %App{} = app <- get_app_from_request(conn, params),
154 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
155 {:user_active, true} <- {:user_active, !user.info.deactivated},
156 scopes <- oauth_scopes(params, app.scopes),
157 [] <- scopes -- app.scopes,
158 true <- Enum.any?(scopes),
159 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
160 {:ok, token} <- Token.exchange_token(app, auth) do
162 token_type: "Bearer",
163 access_token: token.token,
164 refresh_token: token.refresh_token,
166 scope: Enum.join(token.scopes, " "),
172 {:auth_active, false} ->
173 # Per https://github.com/tootsuite/mastodon/blob/
174 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
176 |> put_status(:forbidden)
177 |> json(%{error: "Your login is missing a confirmed e-mail address"})
179 {:user_active, false} ->
181 |> put_status(:forbidden)
182 |> json(%{error: "Your account is currently disabled"})
185 put_status(conn, 400)
186 |> json(%{error: "Invalid credentials"})
192 %{"grant_type" => "password", "name" => name, "password" => _password} = params
196 |> Map.delete("name")
197 |> Map.put("username", name)
199 token_exchange(conn, params)
202 def token_revoke(conn, %{"token" => token} = params) do
203 with %App{} = app <- get_app_from_request(conn, params),
204 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
205 {:ok, %Token{}} <- Repo.delete(token) do
209 # RFC 7009: invalid tokens [in the request] do not cause an error response
214 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
215 # decoding it. Investigate sometime.
216 defp fix_padding(token) do
219 |> Base.url_decode64!(padding: false)
220 |> Base.url_encode64(padding: false)
223 defp get_app_from_request(conn, params) do
224 # Per RFC 6749, HTTP Basic is preferred to body params
225 {client_id, client_secret} =
226 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
227 {:ok, decoded} <- Base.decode64(encoded),
229 String.split(decoded, ":")
230 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
233 _ -> {params["client_id"], params["client_secret"]}
236 if client_id && client_secret do
239 client_id: client_id,
240 client_secret: client_secret
247 # Special case: Local MastodonFE
248 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
250 defp redirect_uri(_conn, redirect_uri), do: redirect_uri