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