4047288995d1b4122f236a5c4ea278eee31a729e
[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 auth_params = Map.take(params, ~w(client_id redirect_uri scope scopes state))
253
254 if user do
255 create_authorization(
256 conn,
257 %{"authorization" => auth_params},
258 user: user
259 )
260 else
261 registration_params =
262 Map.merge(auth_params, %{
263 "nickname" => Registration.nickname(registration),
264 "email" => Registration.email(registration)
265 })
266
267 conn
268 |> put_session(:registration_id, registration.id)
269 |> redirect(to: o_auth_path(conn, :registration_details, registration_params))
270 end
271 else
272 _ ->
273 conn
274 |> put_flash(:error, "Failed to set up user account.")
275 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
276 end
277 end
278
279 defp callback_params(%{"state" => state} = params) do
280 Map.merge(params, Poison.decode!(state))
281 end
282
283 def registration_details(conn, params) do
284 render(conn, "register.html", %{
285 client_id: params["client_id"],
286 redirect_uri: params["redirect_uri"],
287 state: params["state"],
288 scopes: oauth_scopes(params, []),
289 nickname: params["nickname"],
290 email: params["email"]
291 })
292 end
293
294 def register(conn, %{"op" => "connect"} = params) do
295 create_authorization_params = %{
296 "authorization" => Map.merge(params, %{"name" => params["auth_name"]})
297 }
298
299 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
300 %Registration{} = registration <- Repo.get(Registration, registration_id),
301 {:ok, auth} <- do_create_authorization(conn, create_authorization_params),
302 %User{} = user <- Repo.preload(auth, :user).user,
303 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
304 conn
305 |> put_session_registration_id(nil)
306 |> create_authorization(
307 create_authorization_params,
308 auth: auth
309 )
310 else
311 _ ->
312 params = Map.delete(params, "password")
313
314 conn
315 |> put_flash(:error, "Unknown error, please try again.")
316 |> redirect(to: o_auth_path(conn, :registration_details, params))
317 end
318 end
319
320 def register(conn, params) do
321 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
322 %Registration{} = registration <- Repo.get(Registration, registration_id),
323 {:ok, user} <- Authenticator.create_from_registration(conn, params, registration) do
324 conn
325 |> put_session_registration_id(nil)
326 |> create_authorization(
327 %{
328 "authorization" => %{
329 "client_id" => params["client_id"],
330 "redirect_uri" => params["redirect_uri"],
331 "scopes" => oauth_scopes(params, nil)
332 }
333 },
334 user: user
335 )
336 else
337 {:error, changeset} ->
338 message =
339 Enum.map(changeset.errors, fn {field, {error, _}} ->
340 "#{field} #{error}"
341 end)
342 |> Enum.join("; ")
343
344 message =
345 String.replace(
346 message,
347 "ap_id has already been taken",
348 "nickname has already been taken"
349 )
350
351 conn
352 |> put_flash(:error, "Error: #{message}.")
353 |> redirect(to: o_auth_path(conn, :registration_details, params))
354
355 _ ->
356 conn
357 |> put_flash(:error, "Unknown error, please try again.")
358 |> redirect(to: o_auth_path(conn, :registration_details, params))
359 end
360 end
361
362 defp do_create_authorization(
363 conn,
364 %{
365 "authorization" =>
366 %{
367 "client_id" => client_id,
368 "redirect_uri" => redirect_uri
369 } = auth_params
370 } = params,
371 user \\ nil
372 ) do
373 with {_, {:ok, %User{} = user}} <-
374 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn, params)},
375 %App{} = app <- Repo.get_by(App, client_id: client_id),
376 true <- redirect_uri in String.split(app.redirect_uris),
377 scopes <- oauth_scopes(auth_params, []),
378 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
379 # Note: `scope` param is intentionally not optional in this context
380 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
381 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
382 Authorization.create_authorization(app, user, scopes)
383 end
384 end
385
386 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
387 # decoding it. Investigate sometime.
388 defp fix_padding(token) do
389 token
390 |> URI.decode()
391 |> Base.url_decode64!(padding: false)
392 |> Base.url_encode64(padding: false)
393 end
394
395 defp get_app_from_request(conn, params) do
396 # Per RFC 6749, HTTP Basic is preferred to body params
397 {client_id, client_secret} =
398 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
399 {:ok, decoded} <- Base.decode64(encoded),
400 [id, secret] <-
401 String.split(decoded, ":")
402 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
403 {id, secret}
404 else
405 _ -> {params["client_id"], params["client_secret"]}
406 end
407
408 if client_id && client_secret do
409 Repo.get_by(
410 App,
411 client_id: client_id,
412 client_secret: client_secret
413 )
414 else
415 nil
416 end
417 end
418
419 # Special case: Local MastodonFE
420 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
421
422 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
423
424 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
425
426 defp put_session_registration_id(conn, registration_id),
427 do: put_session(conn, :registration_id, registration_id)
428 end