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