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