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