change `Repo.get(User, id)` => `User.get_by_id(id)`
[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 # Per https://github.com/tootsuite/mastodon/blob/
87 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
88 conn
89 |> put_flash(:error, "This action is outside the authorized scopes")
90 |> put_status(:unauthorized)
91 |> authorize(auth_params)
92
93 {:auth_active, false} ->
94 # Per https://github.com/tootsuite/mastodon/blob/
95 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
96 conn
97 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
98 |> put_status(:forbidden)
99 |> authorize(auth_params)
100
101 error ->
102 Authenticator.handle_error(conn, error)
103 end
104 end
105
106 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
107 with %App{} = app <- get_app_from_request(conn, params),
108 fixed_token = fix_padding(params["code"]),
109 %Authorization{} = auth <-
110 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
111 %User{} = user <- User.get_by_id(auth.user_id),
112 {:ok, token} <- Token.exchange_token(app, auth),
113 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
114 response = %{
115 token_type: "Bearer",
116 access_token: token.token,
117 refresh_token: token.refresh_token,
118 created_at: DateTime.to_unix(inserted_at),
119 expires_in: 60 * 10,
120 scope: Enum.join(token.scopes, " "),
121 me: user.ap_id
122 }
123
124 json(conn, response)
125 else
126 _error ->
127 put_status(conn, 400)
128 |> json(%{error: "Invalid credentials"})
129 end
130 end
131
132 def token_exchange(
133 conn,
134 %{"grant_type" => "password"} = params
135 ) do
136 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn)},
137 %App{} = app <- get_app_from_request(conn, params),
138 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
139 scopes <- oauth_scopes(params, app.scopes),
140 [] <- scopes -- app.scopes,
141 true <- Enum.any?(scopes),
142 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
143 {:ok, token} <- Token.exchange_token(app, auth) do
144 response = %{
145 token_type: "Bearer",
146 access_token: token.token,
147 refresh_token: token.refresh_token,
148 expires_in: 60 * 10,
149 scope: Enum.join(token.scopes, " "),
150 me: user.ap_id
151 }
152
153 json(conn, response)
154 else
155 {:auth_active, false} ->
156 # Per https://github.com/tootsuite/mastodon/blob/
157 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
158 conn
159 |> put_status(:forbidden)
160 |> json(%{error: "Your login is missing a confirmed e-mail address"})
161
162 _error ->
163 put_status(conn, 400)
164 |> json(%{error: "Invalid credentials"})
165 end
166 end
167
168 def token_exchange(
169 conn,
170 %{"grant_type" => "password", "name" => name, "password" => _password} = params
171 ) do
172 params =
173 params
174 |> Map.delete("name")
175 |> Map.put("username", name)
176
177 token_exchange(conn, params)
178 end
179
180 def token_revoke(conn, %{"token" => token} = params) do
181 with %App{} = app <- get_app_from_request(conn, params),
182 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
183 {:ok, %Token{}} <- Repo.delete(token) do
184 json(conn, %{})
185 else
186 _error ->
187 # RFC 7009: invalid tokens [in the request] do not cause an error response
188 json(conn, %{})
189 end
190 end
191
192 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
193 # decoding it. Investigate sometime.
194 defp fix_padding(token) do
195 token
196 |> URI.decode()
197 |> Base.url_decode64!(padding: false)
198 |> Base.url_encode64(padding: false)
199 end
200
201 defp get_app_from_request(conn, params) do
202 # Per RFC 6749, HTTP Basic is preferred to body params
203 {client_id, client_secret} =
204 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
205 {:ok, decoded} <- Base.decode64(encoded),
206 [id, secret] <-
207 String.split(decoded, ":")
208 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
209 {id, secret}
210 else
211 _ -> {params["client_id"], params["client_secret"]}
212 end
213
214 if client_id && client_secret do
215 Repo.get_by(
216 App,
217 client_id: client_id,
218 client_secret: client_secret
219 )
220 else
221 nil
222 end
223 end
224 end