[#923] Removed <br> elements from auth forms, adjusted docs, minor auth settings...
[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 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 %{"authorization" => auth_params} = params,
66 opts \\ []
67 ) do
68 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
69 after_create_authorization(conn, auth, auth_params)
70 else
71 error ->
72 handle_create_authorization_error(conn, error, auth_params)
73 end
74 end
75
76 def after_create_authorization(conn, auth, %{"redirect_uri" => redirect_uri} = auth_params) do
77 redirect_uri = redirect_uri(conn, redirect_uri)
78
79 if redirect_uri == "urn:ietf:wg:oauth:2.0:oob" do
80 render(conn, "results.html", %{
81 auth: auth
82 })
83 else
84 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
85 url = "#{redirect_uri}#{connector}"
86 url_params = %{:code => auth.token}
87
88 url_params =
89 if auth_params["state"] do
90 Map.put(url_params, :state, auth_params["state"])
91 else
92 url_params
93 end
94
95 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
96
97 redirect(conn, external: url)
98 end
99 end
100
101 defp handle_create_authorization_error(conn, {scopes_issue, _}, auth_params)
102 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
103 # Per https://github.com/tootsuite/mastodon/blob/
104 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
105 conn
106 |> put_flash(:error, "This action is outside the authorized scopes")
107 |> put_status(:unauthorized)
108 |> authorize(auth_params)
109 end
110
111 defp handle_create_authorization_error(conn, {:auth_active, false}, auth_params) do
112 # Per https://github.com/tootsuite/mastodon/blob/
113 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
114 conn
115 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
116 |> put_status(:forbidden)
117 |> authorize(auth_params)
118 end
119
120 defp handle_create_authorization_error(conn, error, _auth_params) do
121 Authenticator.handle_error(conn, error)
122 end
123
124 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
125 with %App{} = app <- get_app_from_request(conn, params),
126 fixed_token = fix_padding(params["code"]),
127 %Authorization{} = auth <-
128 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
129 %User{} = user <- User.get_by_id(auth.user_id),
130 {:ok, token} <- Token.exchange_token(app, auth),
131 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
132 response = %{
133 token_type: "Bearer",
134 access_token: token.token,
135 refresh_token: token.refresh_token,
136 created_at: DateTime.to_unix(inserted_at),
137 expires_in: 60 * 10,
138 scope: Enum.join(token.scopes, " "),
139 me: user.ap_id
140 }
141
142 json(conn, response)
143 else
144 _error ->
145 put_status(conn, 400)
146 |> json(%{error: "Invalid credentials"})
147 end
148 end
149
150 def token_exchange(
151 conn,
152 %{"grant_type" => "password"} = params
153 ) do
154 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn, params)},
155 %App{} = app <- get_app_from_request(conn, params),
156 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
157 scopes <- oauth_scopes(params, app.scopes),
158 [] <- scopes -- app.scopes,
159 true <- Enum.any?(scopes),
160 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
161 {:ok, token} <- Token.exchange_token(app, auth) do
162 response = %{
163 token_type: "Bearer",
164 access_token: token.token,
165 refresh_token: token.refresh_token,
166 expires_in: 60 * 10,
167 scope: Enum.join(token.scopes, " "),
168 me: user.ap_id
169 }
170
171 json(conn, response)
172 else
173 {:auth_active, false} ->
174 # Per https://github.com/tootsuite/mastodon/blob/
175 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
176 conn
177 |> put_status(:forbidden)
178 |> json(%{error: "Your login is missing a confirmed e-mail address"})
179
180 _error ->
181 put_status(conn, 400)
182 |> json(%{error: "Invalid credentials"})
183 end
184 end
185
186 def token_exchange(
187 conn,
188 %{"grant_type" => "password", "name" => name, "password" => _password} = params
189 ) do
190 params =
191 params
192 |> Map.delete("name")
193 |> Map.put("username", name)
194
195 token_exchange(conn, params)
196 end
197
198 def token_revoke(conn, %{"token" => token} = params) do
199 with %App{} = app <- get_app_from_request(conn, params),
200 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
201 {:ok, %Token{}} <- Repo.delete(token) do
202 json(conn, %{})
203 else
204 _error ->
205 # RFC 7009: invalid tokens [in the request] do not cause an error response
206 json(conn, %{})
207 end
208 end
209
210 @doc "Prepares OAuth request to provider for Ueberauth"
211 def prepare_request(conn, %{"provider" => provider} = params) do
212 scope =
213 oauth_scopes(params, [])
214 |> Enum.join(" ")
215
216 state =
217 params
218 |> Map.delete("scopes")
219 |> Map.put("scope", scope)
220 |> Poison.encode!()
221
222 params =
223 params
224 |> Map.drop(~w(scope scopes client_id redirect_uri))
225 |> Map.put("state", state)
226
227 # Handing the request to Ueberauth
228 redirect(conn, to: o_auth_path(conn, :request, provider, params))
229 end
230
231 def request(conn, params) do
232 message =
233 if params["provider"] do
234 "Unsupported OAuth provider: #{params["provider"]}."
235 else
236 "Bad OAuth request."
237 end
238
239 conn
240 |> put_flash(:error, message)
241 |> redirect(to: "/")
242 end
243
244 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
245 params = callback_params(params)
246 messages = for e <- Map.get(failure, :errors, []), do: e.message
247 message = Enum.join(messages, "; ")
248
249 conn
250 |> put_flash(:error, "Failed to authenticate: #{message}.")
251 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
252 end
253
254 def callback(conn, params) do
255 params = callback_params(params)
256
257 with {:ok, registration} <- Authenticator.get_registration(conn, params) do
258 user = Repo.preload(registration, :user).user
259 auth_params = Map.take(params, ~w(client_id redirect_uri scope scopes state))
260
261 if user do
262 create_authorization(
263 conn,
264 %{"authorization" => auth_params},
265 user: user
266 )
267 else
268 registration_params =
269 Map.merge(auth_params, %{
270 "nickname" => Registration.nickname(registration),
271 "email" => Registration.email(registration)
272 })
273
274 conn
275 |> put_session(:registration_id, registration.id)
276 |> registration_details(registration_params)
277 end
278 else
279 _ ->
280 conn
281 |> put_flash(:error, "Failed to set up user account.")
282 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
283 end
284 end
285
286 defp callback_params(%{"state" => state} = params) do
287 Map.merge(params, Poison.decode!(state))
288 end
289
290 def registration_details(conn, params) do
291 render(conn, "register.html", %{
292 client_id: params["client_id"],
293 redirect_uri: params["redirect_uri"],
294 state: params["state"],
295 scopes: oauth_scopes(params, []),
296 nickname: params["nickname"],
297 email: params["email"]
298 })
299 end
300
301 def register(conn, %{"op" => "connect"} = params) do
302 authorization_params = Map.put(params, "name", params["auth_name"])
303 create_authorization_params = %{"authorization" => authorization_params}
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}} <-
308 {:create_authorization, do_create_authorization(conn, create_authorization_params)},
309 %User{} = user <- Repo.preload(auth, :user).user,
310 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
311 conn
312 |> put_session_registration_id(nil)
313 |> after_create_authorization(auth, authorization_params)
314 else
315 {:create_authorization, error} ->
316 {:register, handle_create_authorization_error(conn, error, create_authorization_params)}
317
318 _ ->
319 {:register, :generic_error}
320 end
321 end
322
323 def register(conn, %{"op" => "register"} = params) do
324 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
325 %Registration{} = registration <- Repo.get(Registration, registration_id),
326 {:ok, user} <- Authenticator.create_from_registration(conn, params, registration) do
327 conn
328 |> put_session_registration_id(nil)
329 |> create_authorization(
330 %{
331 "authorization" => %{
332 "client_id" => params["client_id"],
333 "redirect_uri" => params["redirect_uri"],
334 "scopes" => oauth_scopes(params, nil)
335 }
336 },
337 user: user
338 )
339 else
340 {:error, changeset} ->
341 message =
342 Enum.map(changeset.errors, fn {field, {error, _}} ->
343 "#{field} #{error}"
344 end)
345 |> Enum.join("; ")
346
347 message =
348 String.replace(
349 message,
350 "ap_id has already been taken",
351 "nickname has already been taken"
352 )
353
354 conn
355 |> put_status(:forbidden)
356 |> put_flash(:error, "Error: #{message}.")
357 |> registration_details(params)
358
359 _ ->
360 {:register, :generic_error}
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