8c864cb1d473b85b599ae4a535f5b53945cdcdf0
[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.Web.Auth.Authenticator
11 alias Pleroma.Web.OAuth.App
12 alias Pleroma.Web.OAuth.Authorization
13 alias Pleroma.Web.OAuth.Token
14
15 import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2]
16
17 if Pleroma.Config.get([:auth, :oauth_consumer_enabled]), do: plug(Ueberauth)
18
19 plug(:fetch_session)
20 plug(:fetch_flash)
21
22 action_fallback(Pleroma.Web.OAuth.FallbackController)
23
24 def request(conn, params) do
25 message =
26 if params["provider"] do
27 "Unsupported OAuth provider: #{params["provider"]}."
28 else
29 "Bad OAuth request."
30 end
31
32 conn
33 |> put_flash(:error, message)
34 |> redirect(to: "/")
35 end
36
37 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, %{"redirect_uri" => redirect_uri}) do
38 messages = for e <- Map.get(failure, :errors, []), do: e.message
39 message = Enum.join(messages, "; ")
40
41 conn
42 |> put_flash(:error, "Failed to authenticate: #{message}.")
43 |> redirect(external: redirect_uri(conn, redirect_uri))
44 end
45
46 def callback(
47 conn,
48 %{"client_id" => client_id, "redirect_uri" => redirect_uri} = params
49 ) do
50 with {:ok, user} <- Authenticator.get_by_external_registration(conn, params) do
51 do_create_authorization(
52 conn,
53 %{
54 "authorization" => %{
55 "client_id" => client_id,
56 "redirect_uri" => redirect_uri,
57 "scope" => oauth_scopes(params, nil)
58 }
59 },
60 user
61 )
62 else
63 _ ->
64 conn
65 |> put_flash(:error, "Failed to set up user account.")
66 |> redirect(external: redirect_uri(conn, redirect_uri))
67 end
68 end
69
70 def authorize(conn, params) do
71 app = Repo.get_by(App, client_id: params["client_id"])
72 available_scopes = (app && app.scopes) || []
73 scopes = oauth_scopes(params, nil) || available_scopes
74
75 render(conn, Authenticator.auth_template(), %{
76 response_type: params["response_type"],
77 client_id: params["client_id"],
78 available_scopes: available_scopes,
79 scopes: scopes,
80 redirect_uri: params["redirect_uri"],
81 state: params["state"],
82 params: params
83 })
84 end
85
86 def create_authorization(conn, params), do: do_create_authorization(conn, params, nil)
87
88 defp do_create_authorization(
89 conn,
90 %{
91 "authorization" =>
92 %{
93 "client_id" => client_id,
94 "redirect_uri" => redirect_uri
95 } = auth_params
96 } = params,
97 user
98 ) do
99 with {_, {:ok, %User{} = user}} <-
100 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn, params)},
101 %App{} = app <- Repo.get_by(App, client_id: client_id),
102 true <- redirect_uri in String.split(app.redirect_uris),
103 scopes <- oauth_scopes(auth_params, []),
104 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
105 # Note: `scope` param is intentionally not optional in this context
106 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
107 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
108 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
109 redirect_uri = redirect_uri(conn, redirect_uri)
110
111 cond do
112 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
113 render(conn, "results.html", %{
114 auth: auth
115 })
116
117 true ->
118 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
119 url = "#{redirect_uri}#{connector}"
120 url_params = %{:code => auth.token}
121
122 url_params =
123 if auth_params["state"] do
124 Map.put(url_params, :state, auth_params["state"])
125 else
126 url_params
127 end
128
129 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
130
131 redirect(conn, external: url)
132 end
133 else
134 {scopes_issue, _} when scopes_issue in [:unsupported_scopes, :missing_scopes] ->
135 conn
136 |> put_flash(:error, "Permissions not specified.")
137 |> put_status(:unauthorized)
138 |> authorize(auth_params)
139
140 {:auth_active, false} ->
141 conn
142 |> put_flash(:error, "Account confirmation pending.")
143 |> put_status(:forbidden)
144 |> authorize(auth_params)
145
146 error ->
147 Authenticator.handle_error(conn, error)
148 end
149 end
150
151 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
152 with %App{} = app <- get_app_from_request(conn, params),
153 fixed_token = fix_padding(params["code"]),
154 %Authorization{} = auth <-
155 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
156 %User{} = user <- Repo.get(User, auth.user_id),
157 {:ok, token} <- Token.exchange_token(app, auth),
158 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
159 response = %{
160 token_type: "Bearer",
161 access_token: token.token,
162 refresh_token: token.refresh_token,
163 created_at: DateTime.to_unix(inserted_at),
164 expires_in: 60 * 10,
165 scope: Enum.join(token.scopes, " "),
166 me: user.ap_id
167 }
168
169 json(conn, response)
170 else
171 _error ->
172 put_status(conn, 400)
173 |> json(%{error: "Invalid credentials"})
174 end
175 end
176
177 def token_exchange(
178 conn,
179 %{"grant_type" => "password"} = params
180 ) do
181 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn, params)},
182 %App{} = app <- get_app_from_request(conn, params),
183 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
184 scopes <- oauth_scopes(params, app.scopes),
185 [] <- scopes -- app.scopes,
186 true <- Enum.any?(scopes),
187 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
188 {:ok, token} <- Token.exchange_token(app, auth) do
189 response = %{
190 token_type: "Bearer",
191 access_token: token.token,
192 refresh_token: token.refresh_token,
193 expires_in: 60 * 10,
194 scope: Enum.join(token.scopes, " "),
195 me: user.ap_id
196 }
197
198 json(conn, response)
199 else
200 {:auth_active, false} ->
201 conn
202 |> put_status(:forbidden)
203 |> json(%{error: "Account confirmation pending"})
204
205 _error ->
206 put_status(conn, 400)
207 |> json(%{error: "Invalid credentials"})
208 end
209 end
210
211 def token_exchange(
212 conn,
213 %{"grant_type" => "password", "name" => name, "password" => _password} = params
214 ) do
215 params =
216 params
217 |> Map.delete("name")
218 |> Map.put("username", name)
219
220 token_exchange(conn, params)
221 end
222
223 def token_revoke(conn, %{"token" => token} = params) do
224 with %App{} = app <- get_app_from_request(conn, params),
225 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
226 {:ok, %Token{}} <- Repo.delete(token) do
227 json(conn, %{})
228 else
229 _error ->
230 # RFC 7009: invalid tokens [in the request] do not cause an error response
231 json(conn, %{})
232 end
233 end
234
235 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
236 # decoding it. Investigate sometime.
237 defp fix_padding(token) do
238 token
239 |> URI.decode()
240 |> Base.url_decode64!(padding: false)
241 |> Base.url_encode64(padding: false)
242 end
243
244 defp get_app_from_request(conn, params) do
245 # Per RFC 6749, HTTP Basic is preferred to body params
246 {client_id, client_secret} =
247 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
248 {:ok, decoded} <- Base.decode64(encoded),
249 [id, secret] <-
250 String.split(decoded, ":")
251 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
252 {id, secret}
253 else
254 _ -> {params["client_id"], params["client_secret"]}
255 end
256
257 if client_id && client_secret do
258 Repo.get_by(
259 App,
260 client_id: client_id,
261 client_secret: client_secret
262 )
263 else
264 nil
265 end
266 end
267
268 # Special case: Local MastodonFE
269 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
270
271 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
272 end