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