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