[#923] OAuth: prototype of sign in / sign up with Twitter.
[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.Web.Auth.Authenticator
9 alias Pleroma.Web.OAuth.Authorization
10 alias Pleroma.Web.OAuth.Token
11 alias Pleroma.Web.OAuth.App
12 alias Pleroma.Repo
13 alias Pleroma.User
14 alias Comeonin.Pbkdf2
15
16 import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2]
17
18 if Pleroma.Config.get([:auth, :oauth_consumer_enabled]), do: plug(Ueberauth)
19
20 plug(:fetch_session)
21 plug(:fetch_flash)
22
23 action_fallback(Pleroma.Web.OAuth.FallbackController)
24
25 def request(conn, params) do
26 message =
27 if params["provider"] do
28 "Unsupported OAuth provider: #{params["provider"]}."
29 else
30 "Bad OAuth request."
31 end
32
33 conn
34 |> put_flash(:error, message)
35 |> redirect(to: "/")
36 end
37
38 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, %{"redirect_uri" => redirect_uri}) do
39 messages = for e <- Map.get(failure, :errors, []), do: e.message
40 message = Enum.join(messages, "; ")
41
42 conn
43 |> put_flash(:error, "Failed to authenticate: #{message}.")
44 |> redirect(external: redirect_uri(conn, redirect_uri))
45 end
46
47 def callback(
48 conn,
49 %{"client_id" => client_id, "redirect_uri" => redirect_uri} = params
50 ) do
51 with {:ok, user} <- Authenticator.get_or_create_user_by_oauth(conn, params) do
52 do_create_authorization(
53 conn,
54 %{
55 "authorization" => %{
56 "client_id" => client_id,
57 "redirect_uri" => redirect_uri,
58 "scope" => oauth_scopes(params, nil)
59 }
60 },
61 user
62 )
63 else
64 _ ->
65 conn
66 |> put_flash(:error, "Failed to set up user account.")
67 |> redirect(external: redirect_uri(conn, redirect_uri))
68 end
69 end
70
71 def authorize(conn, params) do
72 app = Repo.get_by(App, client_id: params["client_id"])
73 available_scopes = (app && app.scopes) || []
74 scopes = oauth_scopes(params, nil) || available_scopes
75
76 render(conn, Authenticator.auth_template(), %{
77 response_type: params["response_type"],
78 client_id: params["client_id"],
79 available_scopes: available_scopes,
80 scopes: scopes,
81 redirect_uri: params["redirect_uri"],
82 state: params["state"],
83 params: params
84 })
85 end
86
87 def create_authorization(conn, params), do: do_create_authorization(conn, params, nil)
88
89 defp do_create_authorization(
90 conn,
91 %{
92 "authorization" =>
93 %{
94 "client_id" => client_id,
95 "redirect_uri" => redirect_uri
96 } = auth_params
97 } = params,
98 user
99 ) do
100 with {_, {:ok, %User{} = user}} <-
101 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn, params)},
102 %App{} = app <- Repo.get_by(App, client_id: client_id),
103 true <- redirect_uri in String.split(app.redirect_uris),
104 scopes <- oauth_scopes(auth_params, []),
105 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
106 # Note: `scope` param is intentionally not optional in this context
107 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
108 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
109 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
110 redirect_uri = redirect_uri(conn, redirect_uri)
111
112 cond do
113 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
114 render(conn, "results.html", %{
115 auth: auth
116 })
117
118 true ->
119 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
120 url = "#{redirect_uri}#{connector}"
121 url_params = %{:code => auth.token}
122
123 url_params =
124 if auth_params["state"] do
125 Map.put(url_params, :state, auth_params["state"])
126 else
127 url_params
128 end
129
130 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
131
132 redirect(conn, external: url)
133 end
134 else
135 {scopes_issue, _} when scopes_issue in [:unsupported_scopes, :missing_scopes] ->
136 conn
137 |> put_flash(:error, "Permissions not specified.")
138 |> put_status(:unauthorized)
139 |> authorize(auth_params)
140
141 {:auth_active, false} ->
142 conn
143 |> put_flash(:error, "Account confirmation pending.")
144 |> put_status(:forbidden)
145 |> authorize(auth_params)
146
147 error ->
148 Authenticator.handle_error(conn, error)
149 end
150 end
151
152 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
153 with %App{} = app <- get_app_from_request(conn, params),
154 fixed_token = fix_padding(params["code"]),
155 %Authorization{} = auth <-
156 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
157 {:ok, token} <- Token.exchange_token(app, auth),
158 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
159 response = %{
160 token_type: "Bearer",
161 access_token: token.token,
162 refresh_token: token.refresh_token,
163 created_at: DateTime.to_unix(inserted_at),
164 expires_in: 60 * 10,
165 scope: Enum.join(token.scopes, " ")
166 }
167
168 json(conn, response)
169 else
170 _error ->
171 put_status(conn, 400)
172 |> json(%{error: "Invalid credentials"})
173 end
174 end
175
176 def token_exchange(
177 conn,
178 %{"grant_type" => "password", "username" => name, "password" => password} = params
179 ) do
180 with %App{} = app <- get_app_from_request(conn, params),
181 %User{} = user <- User.get_by_nickname_or_email(name),
182 true <- Pbkdf2.checkpw(password, user.password_hash),
183 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
184 scopes <- oauth_scopes(params, app.scopes),
185 [] <- scopes -- app.scopes,
186 true <- Enum.any?(scopes),
187 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
188 {:ok, token} <- Token.exchange_token(app, auth) do
189 response = %{
190 token_type: "Bearer",
191 access_token: token.token,
192 refresh_token: token.refresh_token,
193 expires_in: 60 * 10,
194 scope: Enum.join(token.scopes, " ")
195 }
196
197 json(conn, response)
198 else
199 {:auth_active, false} ->
200 conn
201 |> put_status(:forbidden)
202 |> json(%{error: "Account confirmation pending"})
203
204 _error ->
205 put_status(conn, 400)
206 |> json(%{error: "Invalid credentials"})
207 end
208 end
209
210 def token_exchange(
211 conn,
212 %{"grant_type" => "password", "name" => name, "password" => _password} = params
213 ) do
214 params =
215 params
216 |> Map.delete("name")
217 |> Map.put("username", name)
218
219 token_exchange(conn, params)
220 end
221
222 def token_revoke(conn, %{"token" => token} = params) do
223 with %App{} = app <- get_app_from_request(conn, params),
224 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
225 {:ok, %Token{}} <- Repo.delete(token) do
226 json(conn, %{})
227 else
228 _error ->
229 # RFC 7009: invalid tokens [in the request] do not cause an error response
230 json(conn, %{})
231 end
232 end
233
234 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
235 # decoding it. Investigate sometime.
236 defp fix_padding(token) do
237 token
238 |> URI.decode()
239 |> Base.url_decode64!(padding: false)
240 |> Base.url_encode64(padding: false)
241 end
242
243 defp get_app_from_request(conn, params) do
244 # Per RFC 6749, HTTP Basic is preferred to body params
245 {client_id, client_secret} =
246 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
247 {:ok, decoded} <- Base.decode64(encoded),
248 [id, secret] <-
249 String.split(decoded, ":")
250 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
251 {id, secret}
252 else
253 _ -> {params["client_id"], params["client_secret"]}
254 end
255
256 if client_id && client_secret do
257 Repo.get_by(
258 App,
259 client_id: client_id,
260 client_secret: client_secret
261 )
262 else
263 nil
264 end
265 end
266
267 # Special case: Local MastodonFE
268 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
269
270 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
271 end