Merge branch 'fix-stuck-follows' into 'develop'
[akkoma] / lib / pleroma / web / oauth / oauth_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.OAuth.OAuthController do
6 use Pleroma.Web, :controller
7
8 alias Pleroma.Registration
9 alias Pleroma.Repo
10 alias Pleroma.User
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
16 alias Pleroma.Web.OAuth.Token.Strategy.RefreshToken
17 alias Pleroma.Web.OAuth.Token.Strategy.Revoke, as: RevokeToken
18 alias Pleroma.Web.OAuth.Scopes
19
20 require Logger
21
22 if Pleroma.Config.oauth_consumer_enabled?(), do: plug(Ueberauth)
23
24 plug(:fetch_session)
25 plug(:fetch_flash)
26
27 action_fallback(Pleroma.Web.OAuth.FallbackController)
28
29 # Note: this definition is only called from error-handling methods with `conn.params` as 2nd arg
30 def authorize(conn, %{"authorization" => _} = params) do
31 {auth_attrs, params} = Map.pop(params, "authorization")
32 authorize(conn, Map.merge(params, auth_attrs))
33 end
34
35 def authorize(%{assigns: %{token: %Token{} = token}} = conn, params) do
36 if ControllerHelper.truthy_param?(params["force_login"]) do
37 do_authorize(conn, params)
38 else
39 redirect_uri =
40 if is_binary(params["redirect_uri"]) do
41 params["redirect_uri"]
42 else
43 app = Repo.preload(token, :app).app
44
45 app.redirect_uris
46 |> String.split()
47 |> Enum.at(0)
48 end
49
50 redirect(conn, external: redirect_uri(conn, redirect_uri))
51 end
52 end
53
54 def authorize(conn, params), do: do_authorize(conn, params)
55
56 defp do_authorize(conn, params) do
57 app = Repo.get_by(App, client_id: params["client_id"])
58 available_scopes = (app && app.scopes) || []
59 scopes = Scopes.fetch_scopes(params, available_scopes)
60
61 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
62 render(conn, Authenticator.auth_template(), %{
63 response_type: params["response_type"],
64 client_id: params["client_id"],
65 available_scopes: available_scopes,
66 scopes: scopes,
67 redirect_uri: params["redirect_uri"],
68 state: params["state"],
69 params: params
70 })
71 end
72
73 def create_authorization(
74 conn,
75 %{"authorization" => _} = params,
76 opts \\ []
77 ) do
78 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
79 after_create_authorization(conn, auth, params)
80 else
81 error ->
82 handle_create_authorization_error(conn, error, params)
83 end
84 end
85
86 def after_create_authorization(conn, auth, %{
87 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
88 }) do
89 redirect_uri = redirect_uri(conn, redirect_uri)
90
91 if redirect_uri == "urn:ietf:wg:oauth:2.0:oob" do
92 render(conn, "results.html", %{
93 auth: auth
94 })
95 else
96 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
97 url = "#{redirect_uri}#{connector}"
98 url_params = %{:code => auth.token}
99
100 url_params =
101 if auth_attrs["state"] do
102 Map.put(url_params, :state, auth_attrs["state"])
103 else
104 url_params
105 end
106
107 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
108
109 redirect(conn, external: url)
110 end
111 end
112
113 defp handle_create_authorization_error(
114 conn,
115 {:error, scopes_issue},
116 %{"authorization" => _} = params
117 )
118 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
119 # Per https://github.com/tootsuite/mastodon/blob/
120 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
121 conn
122 |> put_flash(:error, "This action is outside the authorized scopes")
123 |> put_status(:unauthorized)
124 |> authorize(params)
125 end
126
127 defp handle_create_authorization_error(
128 conn,
129 {:auth_active, false},
130 %{"authorization" => _} = params
131 ) do
132 # Per https://github.com/tootsuite/mastodon/blob/
133 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
134 conn
135 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
136 |> put_status(:forbidden)
137 |> authorize(params)
138 end
139
140 defp handle_create_authorization_error(conn, error, %{"authorization" => _}) do
141 Authenticator.handle_error(conn, error)
142 end
143
144 @doc "Renew access_token with refresh_token"
145 def token_exchange(
146 conn,
147 %{"grant_type" => "refresh_token", "refresh_token" => token} = _params
148 ) do
149 with {:ok, app} <- Token.Utils.fetch_app(conn),
150 {:ok, %{user: user} = token} <- Token.get_by_refresh_token(app, token),
151 {:ok, token} <- RefreshToken.grant(token) do
152 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
153
154 json(conn, Token.Response.build(user, token, response_attrs))
155 else
156 _error ->
157 put_status(conn, 400)
158 |> json(%{error: "Invalid credentials"})
159 end
160 end
161
162 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
163 with {:ok, app} <- Token.Utils.fetch_app(conn),
164 fixed_token = Token.Utils.fix_padding(params["code"]),
165 {:ok, auth} <- Authorization.get_by_token(app, fixed_token),
166 %User{} = user <- User.get_cached_by_id(auth.user_id),
167 {:ok, token} <- Token.exchange_token(app, auth) do
168 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
169
170 json(conn, Token.Response.build(user, token, response_attrs))
171 else
172 _error ->
173 put_status(conn, 400)
174 |> json(%{error: "Invalid credentials"})
175 end
176 end
177
178 def token_exchange(
179 conn,
180 %{"grant_type" => "password"} = params
181 ) do
182 with {:ok, %User{} = user} <- Authenticator.get_user(conn),
183 {:ok, app} <- Token.Utils.fetch_app(conn),
184 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
185 {:user_active, true} <- {:user_active, !user.info.deactivated},
186 {:ok, scopes} <- validate_scopes(app, params),
187 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
188 {:ok, token} <- Token.exchange_token(app, auth) do
189 json(conn, Token.Response.build(user, token))
190 else
191 {:auth_active, false} ->
192 # Per https://github.com/tootsuite/mastodon/blob/
193 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
194 conn
195 |> put_status(:forbidden)
196 |> json(%{error: "Your login is missing a confirmed e-mail address"})
197
198 {:user_active, false} ->
199 conn
200 |> put_status(:forbidden)
201 |> json(%{error: "Your account is currently disabled"})
202
203 _error ->
204 put_status(conn, 400)
205 |> json(%{error: "Invalid credentials"})
206 end
207 end
208
209 def token_exchange(
210 conn,
211 %{"grant_type" => "password", "name" => name, "password" => _password} = params
212 ) do
213 params =
214 params
215 |> Map.delete("name")
216 |> Map.put("username", name)
217
218 token_exchange(conn, params)
219 end
220
221 def token_exchange(conn, %{"grant_type" => "client_credentials"} = _params) do
222 with {:ok, app} <- Token.Utils.fetch_app(conn),
223 {:ok, auth} <- Authorization.create_authorization(app, %User{}),
224 {:ok, token} <- Token.exchange_token(app, auth) do
225 json(conn, Token.Response.build_for_client_credentials(token))
226 else
227 _error ->
228 put_status(conn, 400)
229 |> json(%{error: "Invalid credentials"})
230 end
231 end
232
233 # Bad request
234 def token_exchange(conn, params), do: bad_request(conn, params)
235
236 def token_revoke(conn, %{"token" => _token} = params) do
237 with {:ok, app} <- Token.Utils.fetch_app(conn),
238 {:ok, _token} <- RevokeToken.revoke(app, params) do
239 json(conn, %{})
240 else
241 _error ->
242 # RFC 7009: invalid tokens [in the request] do not cause an error response
243 json(conn, %{})
244 end
245 end
246
247 def token_revoke(conn, params), do: bad_request(conn, params)
248
249 # Response for bad request
250 defp bad_request(conn, _) do
251 conn
252 |> put_status(500)
253 |> json(%{error: "Bad request"})
254 end
255
256 @doc "Prepares OAuth request to provider for Ueberauth"
257 def prepare_request(conn, %{"provider" => provider, "authorization" => auth_attrs}) do
258 scope =
259 auth_attrs
260 |> Scopes.fetch_scopes([])
261 |> Scopes.to_string()
262
263 state =
264 auth_attrs
265 |> Map.delete("scopes")
266 |> Map.put("scope", scope)
267 |> Jason.encode!()
268
269 params =
270 auth_attrs
271 |> Map.drop(~w(scope scopes client_id redirect_uri))
272 |> Map.put("state", state)
273
274 # Handing the request to Ueberauth
275 redirect(conn, to: o_auth_path(conn, :request, provider, params))
276 end
277
278 def request(conn, params) do
279 message =
280 if params["provider"] do
281 "Unsupported OAuth provider: #{params["provider"]}."
282 else
283 "Bad OAuth request."
284 end
285
286 conn
287 |> put_flash(:error, message)
288 |> redirect(to: "/")
289 end
290
291 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
292 params = callback_params(params)
293 messages = for e <- Map.get(failure, :errors, []), do: e.message
294 message = Enum.join(messages, "; ")
295
296 conn
297 |> put_flash(:error, "Failed to authenticate: #{message}.")
298 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
299 end
300
301 def callback(conn, params) do
302 params = callback_params(params)
303
304 with {:ok, registration} <- Authenticator.get_registration(conn) do
305 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
306
307 case Repo.get_assoc(registration, :user) do
308 {:ok, user} ->
309 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
310
311 _ ->
312 registration_params =
313 Map.merge(auth_attrs, %{
314 "nickname" => Registration.nickname(registration),
315 "email" => Registration.email(registration)
316 })
317
318 conn
319 |> put_session(:registration_id, registration.id)
320 |> registration_details(%{"authorization" => registration_params})
321 end
322 else
323 error ->
324 Logger.debug(inspect(["OAUTH_ERROR", error, conn.assigns]))
325
326 conn
327 |> put_flash(:error, "Failed to set up user account.")
328 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
329 end
330 end
331
332 defp callback_params(%{"state" => state} = params) do
333 Map.merge(params, Jason.decode!(state))
334 end
335
336 def registration_details(conn, %{"authorization" => auth_attrs}) do
337 render(conn, "register.html", %{
338 client_id: auth_attrs["client_id"],
339 redirect_uri: auth_attrs["redirect_uri"],
340 state: auth_attrs["state"],
341 scopes: Scopes.fetch_scopes(auth_attrs, []),
342 nickname: auth_attrs["nickname"],
343 email: auth_attrs["email"]
344 })
345 end
346
347 def register(conn, %{"authorization" => _, "op" => "connect"} = params) do
348 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
349 %Registration{} = registration <- Repo.get(Registration, registration_id),
350 {_, {:ok, auth}} <-
351 {:create_authorization, do_create_authorization(conn, params)},
352 %User{} = user <- Repo.preload(auth, :user).user,
353 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
354 conn
355 |> put_session_registration_id(nil)
356 |> after_create_authorization(auth, params)
357 else
358 {:create_authorization, error} ->
359 {:register, handle_create_authorization_error(conn, error, params)}
360
361 _ ->
362 {:register, :generic_error}
363 end
364 end
365
366 def register(conn, %{"authorization" => _, "op" => "register"} = params) do
367 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
368 %Registration{} = registration <- Repo.get(Registration, registration_id),
369 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
370 conn
371 |> put_session_registration_id(nil)
372 |> create_authorization(
373 params,
374 user: user
375 )
376 else
377 {:error, changeset} ->
378 message =
379 Enum.map(changeset.errors, fn {field, {error, _}} ->
380 "#{field} #{error}"
381 end)
382 |> Enum.join("; ")
383
384 message =
385 String.replace(
386 message,
387 "ap_id has already been taken",
388 "nickname has already been taken"
389 )
390
391 conn
392 |> put_status(:forbidden)
393 |> put_flash(:error, "Error: #{message}.")
394 |> registration_details(params)
395
396 _ ->
397 {:register, :generic_error}
398 end
399 end
400
401 defp do_create_authorization(
402 conn,
403 %{
404 "authorization" =>
405 %{
406 "client_id" => client_id,
407 "redirect_uri" => redirect_uri
408 } = auth_attrs
409 },
410 user \\ nil
411 ) do
412 with {_, {:ok, %User{} = user}} <-
413 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
414 %App{} = app <- Repo.get_by(App, client_id: client_id),
415 true <- redirect_uri in String.split(app.redirect_uris),
416 {:ok, scopes} <- validate_scopes(app, auth_attrs),
417 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
418 Authorization.create_authorization(app, user, scopes)
419 end
420 end
421
422 # Special case: Local MastodonFE
423 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
424
425 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
426
427 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
428
429 defp put_session_registration_id(conn, registration_id),
430 do: put_session(conn, :registration_id, registration_id)
431
432 @spec validate_scopes(App.t(), map()) ::
433 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
434 defp validate_scopes(app, params) do
435 params
436 |> Scopes.fetch_scopes(app.scopes)
437 |> Scopes.validates(app.scopes)
438 end
439 end