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