a2c62ae68a05d9fe44892ad6d317e03d84982dc8
[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.Repo
9 alias Pleroma.User
10 alias Pleroma.Registration
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 conn
78 |> put_flash(:error, "Permissions not specified.")
79 |> put_status(:unauthorized)
80 |> authorize(auth_params)
81
82 {:auth_active, false} ->
83 conn
84 |> put_flash(:error, "Account confirmation pending.")
85 |> put_status(:forbidden)
86 |> authorize(auth_params)
87
88 error ->
89 Authenticator.handle_error(conn, error)
90 end
91 end
92
93 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
94 with %App{} = app <- get_app_from_request(conn, params),
95 fixed_token = fix_padding(params["code"]),
96 %Authorization{} = auth <-
97 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
98 %User{} = user <- Repo.get(User, auth.user_id),
99 {:ok, token} <- Token.exchange_token(app, auth),
100 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
101 response = %{
102 token_type: "Bearer",
103 access_token: token.token,
104 refresh_token: token.refresh_token,
105 created_at: DateTime.to_unix(inserted_at),
106 expires_in: 60 * 10,
107 scope: Enum.join(token.scopes, " "),
108 me: user.ap_id
109 }
110
111 json(conn, response)
112 else
113 _error ->
114 put_status(conn, 400)
115 |> json(%{error: "Invalid credentials"})
116 end
117 end
118
119 def token_exchange(
120 conn,
121 %{"grant_type" => "password"} = params
122 ) do
123 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn, params)},
124 %App{} = app <- get_app_from_request(conn, params),
125 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
126 scopes <- oauth_scopes(params, app.scopes),
127 [] <- scopes -- app.scopes,
128 true <- Enum.any?(scopes),
129 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
130 {:ok, token} <- Token.exchange_token(app, auth) do
131 response = %{
132 token_type: "Bearer",
133 access_token: token.token,
134 refresh_token: token.refresh_token,
135 expires_in: 60 * 10,
136 scope: Enum.join(token.scopes, " "),
137 me: user.ap_id
138 }
139
140 json(conn, response)
141 else
142 {:auth_active, false} ->
143 conn
144 |> put_status(:forbidden)
145 |> json(%{error: "Account confirmation pending"})
146
147 _error ->
148 put_status(conn, 400)
149 |> json(%{error: "Invalid credentials"})
150 end
151 end
152
153 def token_exchange(
154 conn,
155 %{"grant_type" => "password", "name" => name, "password" => _password} = params
156 ) do
157 params =
158 params
159 |> Map.delete("name")
160 |> Map.put("username", name)
161
162 token_exchange(conn, params)
163 end
164
165 def token_revoke(conn, %{"token" => token} = params) do
166 with %App{} = app <- get_app_from_request(conn, params),
167 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
168 {:ok, %Token{}} <- Repo.delete(token) do
169 json(conn, %{})
170 else
171 _error ->
172 # RFC 7009: invalid tokens [in the request] do not cause an error response
173 json(conn, %{})
174 end
175 end
176
177 def request(conn, params) do
178 message =
179 if params["provider"] do
180 "Unsupported OAuth provider: #{params["provider"]}."
181 else
182 "Bad OAuth request."
183 end
184
185 conn
186 |> put_flash(:error, message)
187 |> redirect(to: "/")
188 end
189
190 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, %{"redirect_uri" => redirect_uri}) do
191 messages = for e <- Map.get(failure, :errors, []), do: e.message
192 message = Enum.join(messages, "; ")
193
194 conn
195 |> put_flash(:error, "Failed to authenticate: #{message}.")
196 |> redirect(external: redirect_uri(conn, redirect_uri))
197 end
198
199 def callback(
200 conn,
201 %{"client_id" => client_id, "redirect_uri" => redirect_uri} = params
202 ) do
203 with {:ok, registration} <- Authenticator.get_registration(conn, params) do
204 user = Repo.preload(registration, :user).user
205
206 auth_params = %{
207 "client_id" => client_id,
208 "redirect_uri" => redirect_uri,
209 "scopes" => oauth_scopes(params, nil)
210 }
211
212 if user do
213 create_authorization(
214 conn,
215 %{"authorization" => auth_params},
216 user: user
217 )
218 else
219 registration_params =
220 Map.merge(auth_params, %{
221 "nickname" => Registration.nickname(registration),
222 "email" => Registration.email(registration)
223 })
224
225 conn
226 |> put_session(:registration_id, registration.id)
227 |> redirect(to: o_auth_path(conn, :registration_details, registration_params))
228 end
229 else
230 _ ->
231 conn
232 |> put_flash(:error, "Failed to set up user account.")
233 |> redirect(external: redirect_uri(conn, redirect_uri))
234 end
235 end
236
237 def registration_details(conn, params) do
238 render(conn, "register.html", %{
239 client_id: params["client_id"],
240 redirect_uri: params["redirect_uri"],
241 scopes: oauth_scopes(params, []),
242 nickname: params["nickname"],
243 email: params["email"]
244 })
245 end
246
247 def register(conn, %{"op" => "connect"} = params) do
248 create_authorization_params = %{
249 "authorization" => Map.merge(params, %{"name" => params["auth_name"]})
250 }
251
252 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
253 %Registration{} = registration <- Repo.get(Registration, registration_id),
254 {:ok, auth} <- do_create_authorization(conn, create_authorization_params),
255 %User{} = user <- Repo.preload(auth, :user).user,
256 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
257 conn
258 |> put_session_registration_id(nil)
259 |> create_authorization(
260 create_authorization_params,
261 auth: auth
262 )
263 else
264 _ ->
265 conn
266 |> put_flash(:error, "Unknown error, please try again.")
267 |> redirect(to: o_auth_path(conn, :registration_details, params))
268 end
269 end
270
271 def register(conn, params) do
272 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
273 %Registration{} = registration <- Repo.get(Registration, registration_id),
274 {:ok, user} <- Authenticator.create_from_registration(conn, params, registration) do
275 conn
276 |> put_session_registration_id(nil)
277 |> create_authorization(
278 %{
279 "authorization" => %{
280 "client_id" => params["client_id"],
281 "redirect_uri" => params["redirect_uri"],
282 "scopes" => oauth_scopes(params, nil)
283 }
284 },
285 user: user
286 )
287 else
288 {:error, changeset} ->
289 message =
290 Enum.map(changeset.errors, fn {field, {error, _}} ->
291 "#{field} #{error}"
292 end)
293 |> Enum.join("; ")
294
295 message =
296 String.replace(
297 message,
298 "ap_id has already been taken",
299 "nickname has already been taken"
300 )
301
302 conn
303 |> put_flash(:error, "Error: #{message}.")
304 |> redirect(to: o_auth_path(conn, :registration_details, params))
305
306 _ ->
307 conn
308 |> put_flash(:error, "Unknown error, please try again.")
309 |> redirect(to: o_auth_path(conn, :registration_details, params))
310 end
311 end
312
313 defp do_create_authorization(
314 conn,
315 %{
316 "authorization" =>
317 %{
318 "client_id" => client_id,
319 "redirect_uri" => redirect_uri
320 } = auth_params
321 } = params,
322 user \\ nil
323 ) do
324 with {_, {:ok, %User{} = user}} <-
325 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn, params)},
326 %App{} = app <- Repo.get_by(App, client_id: client_id),
327 true <- redirect_uri in String.split(app.redirect_uris),
328 scopes <- oauth_scopes(auth_params, []),
329 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
330 # Note: `scope` param is intentionally not optional in this context
331 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
332 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
333 Authorization.create_authorization(app, user, scopes)
334 end
335 end
336
337 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
338 # decoding it. Investigate sometime.
339 defp fix_padding(token) do
340 token
341 |> URI.decode()
342 |> Base.url_decode64!(padding: false)
343 |> Base.url_encode64(padding: false)
344 end
345
346 defp get_app_from_request(conn, params) do
347 # Per RFC 6749, HTTP Basic is preferred to body params
348 {client_id, client_secret} =
349 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
350 {:ok, decoded} <- Base.decode64(encoded),
351 [id, secret] <-
352 String.split(decoded, ":")
353 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
354 {id, secret}
355 else
356 _ -> {params["client_id"], params["client_secret"]}
357 end
358
359 if client_id && client_secret do
360 Repo.get_by(
361 App,
362 client_id: client_id,
363 client_secret: client_secret
364 )
365 else
366 nil
367 end
368 end
369
370 # Special case: Local MastodonFE
371 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
372
373 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
374
375 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
376
377 defp put_session_registration_id(conn, registration_id),
378 do: put_session(conn, :registration_id, registration_id)
379 end