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