Merge branch 'feature/770-add-emoji-tags' 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 {:user_active, true} <- {:user_active, !user.info.deactivated},
156 scopes <- oauth_scopes(params, app.scopes),
157 [] <- scopes -- app.scopes,
158 true <- Enum.any?(scopes),
159 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
160 {:ok, token} <- Token.exchange_token(app, auth) do
161 response = %{
162 token_type: "Bearer",
163 access_token: token.token,
164 refresh_token: token.refresh_token,
165 expires_in: 60 * 10,
166 scope: Enum.join(token.scopes, " "),
167 me: user.ap_id
168 }
169
170 json(conn, response)
171 else
172 {:auth_active, false} ->
173 # Per https://github.com/tootsuite/mastodon/blob/
174 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
175 conn
176 |> put_status(:forbidden)
177 |> json(%{error: "Your login is missing a confirmed e-mail address"})
178
179 {:user_active, false} ->
180 conn
181 |> put_status(:forbidden)
182 |> json(%{error: "Your account is currently disabled"})
183
184 _error ->
185 put_status(conn, 400)
186 |> json(%{error: "Invalid credentials"})
187 end
188 end
189
190 def token_exchange(
191 conn,
192 %{"grant_type" => "password", "name" => name, "password" => _password} = params
193 ) do
194 params =
195 params
196 |> Map.delete("name")
197 |> Map.put("username", name)
198
199 token_exchange(conn, params)
200 end
201
202 def token_revoke(conn, %{"token" => token} = params) do
203 with %App{} = app <- get_app_from_request(conn, params),
204 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
205 {:ok, %Token{}} <- Repo.delete(token) do
206 json(conn, %{})
207 else
208 _error ->
209 # RFC 7009: invalid tokens [in the request] do not cause an error response
210 json(conn, %{})
211 end
212 end
213
214 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
215 # decoding it. Investigate sometime.
216 defp fix_padding(token) do
217 token
218 |> URI.decode()
219 |> Base.url_decode64!(padding: false)
220 |> Base.url_encode64(padding: false)
221 end
222
223 defp get_app_from_request(conn, params) do
224 # Per RFC 6749, HTTP Basic is preferred to body params
225 {client_id, client_secret} =
226 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
227 {:ok, decoded} <- Base.decode64(encoded),
228 [id, secret] <-
229 String.split(decoded, ":")
230 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
231 {id, secret}
232 else
233 _ -> {params["client_id"], params["client_secret"]}
234 end
235
236 if client_id && client_secret do
237 Repo.get_by(
238 App,
239 client_id: client_id,
240 client_secret: client_secret
241 )
242 else
243 nil
244 end
245 end
246
247 # Special case: Local MastodonFE
248 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
249
250 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
251 end