Merge branch 'features/pleroma-tan' into 'develop'
[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.ControllerHelper
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 plug(:fetch_session)
19 plug(:fetch_flash)
20
21 action_fallback(Pleroma.Web.OAuth.FallbackController)
22
23 def authorize(%{assigns: %{token: %Token{} = token}} = conn, params) do
24 if ControllerHelper.truthy_param?(params["force_login"]) do
25 do_authorize(conn, params)
26 else
27 redirect_uri =
28 if is_binary(params["redirect_uri"]) do
29 params["redirect_uri"]
30 else
31 app = Repo.preload(token, :app).app
32
33 app.redirect_uris
34 |> String.split()
35 |> Enum.at(0)
36 end
37
38 redirect(conn, external: redirect_uri(conn, redirect_uri))
39 end
40 end
41
42 def authorize(conn, params), do: do_authorize(conn, params)
43
44 defp do_authorize(conn, params) do
45 app = Repo.get_by(App, client_id: params["client_id"])
46 available_scopes = (app && app.scopes) || []
47 scopes = oauth_scopes(params, nil) || available_scopes
48
49 render(conn, Authenticator.auth_template(), %{
50 response_type: params["response_type"],
51 client_id: params["client_id"],
52 available_scopes: available_scopes,
53 scopes: scopes,
54 redirect_uri: params["redirect_uri"],
55 state: params["state"],
56 params: params
57 })
58 end
59
60 def create_authorization(conn, %{
61 "authorization" =>
62 %{
63 "client_id" => client_id,
64 "redirect_uri" => redirect_uri
65 } = auth_params
66 }) do
67 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn)},
68 %App{} = app <- Repo.get_by(App, client_id: client_id),
69 true <- redirect_uri in String.split(app.redirect_uris),
70 scopes <- oauth_scopes(auth_params, []),
71 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
72 # Note: `scope` param is intentionally not optional in this context
73 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
74 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
75 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
76 redirect_uri = redirect_uri(conn, redirect_uri)
77
78 cond do
79 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
80 render(conn, "results.html", %{
81 auth: auth
82 })
83
84 true ->
85 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
86 url = "#{redirect_uri}#{connector}"
87 url_params = %{:code => auth.token}
88
89 url_params =
90 if auth_params["state"] do
91 Map.put(url_params, :state, auth_params["state"])
92 else
93 url_params
94 end
95
96 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
97
98 redirect(conn, external: url)
99 end
100 else
101 {scopes_issue, _} when scopes_issue in [:unsupported_scopes, :missing_scopes] ->
102 # Per https://github.com/tootsuite/mastodon/blob/
103 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
104 conn
105 |> put_flash(:error, "This action is outside the authorized scopes")
106 |> put_status(:unauthorized)
107 |> authorize(auth_params)
108
109 {:auth_active, false} ->
110 # Per https://github.com/tootsuite/mastodon/blob/
111 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
112 conn
113 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
114 |> put_status(:forbidden)
115 |> authorize(auth_params)
116
117 error ->
118 Authenticator.handle_error(conn, error)
119 end
120 end
121
122 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
123 with %App{} = app <- get_app_from_request(conn, params),
124 fixed_token = fix_padding(params["code"]),
125 %Authorization{} = auth <-
126 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
127 %User{} = user <- User.get_by_id(auth.user_id),
128 {:ok, token} <- Token.exchange_token(app, auth),
129 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
130 response = %{
131 token_type: "Bearer",
132 access_token: token.token,
133 refresh_token: token.refresh_token,
134 created_at: DateTime.to_unix(inserted_at),
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 _error ->
143 put_status(conn, 400)
144 |> json(%{error: "Invalid credentials"})
145 end
146 end
147
148 def token_exchange(
149 conn,
150 %{"grant_type" => "password"} = params
151 ) do
152 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn)},
153 %App{} = app <- get_app_from_request(conn, params),
154 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
155 scopes <- oauth_scopes(params, app.scopes),
156 [] <- scopes -- app.scopes,
157 true <- Enum.any?(scopes),
158 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
159 {:ok, token} <- Token.exchange_token(app, auth) do
160 response = %{
161 token_type: "Bearer",
162 access_token: token.token,
163 refresh_token: token.refresh_token,
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 {:auth_active, false} ->
172 # Per https://github.com/tootsuite/mastodon/blob/
173 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
174 conn
175 |> put_status(:forbidden)
176 |> json(%{error: "Your login is missing a confirmed e-mail address"})
177
178 _error ->
179 put_status(conn, 400)
180 |> json(%{error: "Invalid credentials"})
181 end
182 end
183
184 def token_exchange(
185 conn,
186 %{"grant_type" => "password", "name" => name, "password" => _password} = params
187 ) do
188 params =
189 params
190 |> Map.delete("name")
191 |> Map.put("username", name)
192
193 token_exchange(conn, params)
194 end
195
196 def token_revoke(conn, %{"token" => token} = params) do
197 with %App{} = app <- get_app_from_request(conn, params),
198 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
199 {:ok, %Token{}} <- Repo.delete(token) do
200 json(conn, %{})
201 else
202 _error ->
203 # RFC 7009: invalid tokens [in the request] do not cause an error response
204 json(conn, %{})
205 end
206 end
207
208 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
209 # decoding it. Investigate sometime.
210 defp fix_padding(token) do
211 token
212 |> URI.decode()
213 |> Base.url_decode64!(padding: false)
214 |> Base.url_encode64(padding: false)
215 end
216
217 defp get_app_from_request(conn, params) do
218 # Per RFC 6749, HTTP Basic is preferred to body params
219 {client_id, client_secret} =
220 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
221 {:ok, decoded} <- Base.decode64(encoded),
222 [id, secret] <-
223 String.split(decoded, ":")
224 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
225 {id, secret}
226 else
227 _ -> {params["client_id"], params["client_secret"]}
228 end
229
230 if client_id && client_secret do
231 Repo.get_by(
232 App,
233 client_id: client_id,
234 client_secret: client_secret
235 )
236 else
237 nil
238 end
239 end
240
241 # Special case: Local MastodonFE
242 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
243
244 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
245 end