[#468] Prototype of OAuth2 scopes support. TwitterAPI scope restrictions.
[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.OAuth.{Authorization, Token, App}
9 alias Pleroma.{Repo, User}
10 alias Comeonin.Pbkdf2
11
12 plug(:fetch_session)
13 plug(:fetch_flash)
14
15 action_fallback(Pleroma.Web.OAuth.FallbackController)
16
17 def authorize(conn, params) do
18 render(conn, "show.html", %{
19 response_type: params["response_type"],
20 client_id: params["client_id"],
21 scope: params["scope"],
22 redirect_uri: params["redirect_uri"],
23 state: params["state"]
24 })
25 end
26
27 def create_authorization(conn, %{
28 "authorization" =>
29 %{
30 "name" => name,
31 "password" => password,
32 "client_id" => client_id,
33 "redirect_uri" => redirect_uri
34 } = params
35 }) do
36 with %User{} = user <- User.get_by_nickname_or_email(name),
37 true <- Pbkdf2.checkpw(password, user.password_hash),
38 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
39 %App{} = app <- Repo.get_by(App, client_id: client_id),
40 true <- redirect_uri in String.split(app.redirect_uris),
41 {:ok, auth} <- Authorization.create_authorization(app, user, params["scope"]) do
42 # Special case: Local MastodonFE.
43 redirect_uri =
44 if redirect_uri == "." do
45 mastodon_api_url(conn, :login)
46 else
47 redirect_uri
48 end
49
50 cond do
51 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
52 render(conn, "results.html", %{
53 auth: auth
54 })
55
56 true ->
57 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
58 url = "#{redirect_uri}#{connector}"
59 url_params = %{:code => auth.token}
60
61 url_params =
62 if params["state"] do
63 Map.put(url_params, :state, params["state"])
64 else
65 url_params
66 end
67
68 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
69
70 redirect(conn, external: url)
71 end
72 else
73 {:auth_active, false} ->
74 conn
75 |> put_flash(:error, "Account confirmation pending")
76 |> put_status(:forbidden)
77 |> authorize(params)
78
79 error ->
80 error
81 end
82 end
83
84 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
85 with %App{} = app <- get_app_from_request(conn, params),
86 fixed_token = fix_padding(params["code"]),
87 %Authorization{} = auth <-
88 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
89 {:ok, token} <- Token.exchange_token(app, auth),
90 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
91 response = %{
92 token_type: "Bearer",
93 access_token: token.token,
94 refresh_token: token.refresh_token,
95 created_at: DateTime.to_unix(inserted_at),
96 expires_in: 60 * 10,
97 scope: token.scope
98 }
99
100 json(conn, response)
101 else
102 _error ->
103 put_status(conn, 400)
104 |> json(%{error: "Invalid credentials"})
105 end
106 end
107
108 def token_exchange(
109 conn,
110 %{"grant_type" => "password", "username" => name, "password" => password} = params
111 ) do
112 with %App{} = app <- get_app_from_request(conn, params),
113 %User{} = user <- User.get_by_nickname_or_email(name),
114 true <- Pbkdf2.checkpw(password, user.password_hash),
115 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
116 {:ok, auth} <- Authorization.create_authorization(app, user, params["scope"]),
117 {:ok, token} <- Token.exchange_token(app, auth) do
118 response = %{
119 token_type: "Bearer",
120 access_token: token.token,
121 refresh_token: token.refresh_token,
122 expires_in: 60 * 10,
123 scope: token.scope
124 }
125
126 json(conn, response)
127 else
128 {:auth_active, false} ->
129 conn
130 |> put_status(:forbidden)
131 |> json(%{error: "Account confirmation pending"})
132
133 _error ->
134 put_status(conn, 400)
135 |> json(%{error: "Invalid credentials"})
136 end
137 end
138
139 def token_exchange(
140 conn,
141 %{"grant_type" => "password", "name" => name, "password" => _password} = params
142 ) do
143 params =
144 params
145 |> Map.delete("name")
146 |> Map.put("username", name)
147
148 token_exchange(conn, params)
149 end
150
151 def token_revoke(conn, %{"token" => token} = params) do
152 with %App{} = app <- get_app_from_request(conn, params),
153 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
154 {:ok, %Token{}} <- Repo.delete(token) do
155 json(conn, %{})
156 else
157 _error ->
158 # RFC 7009: invalid tokens [in the request] do not cause an error response
159 json(conn, %{})
160 end
161 end
162
163 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
164 # decoding it. Investigate sometime.
165 defp fix_padding(token) do
166 token
167 |> URI.decode()
168 |> Base.url_decode64!(padding: false)
169 |> Base.url_encode64()
170 end
171
172 defp get_app_from_request(conn, params) do
173 # Per RFC 6749, HTTP Basic is preferred to body params
174 {client_id, client_secret} =
175 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
176 {:ok, decoded} <- Base.decode64(encoded),
177 [id, secret] <-
178 String.split(decoded, ":")
179 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
180 {id, secret}
181 else
182 _ -> {params["client_id"], params["client_secret"]}
183 end
184
185 if client_id && client_secret do
186 Repo.get_by(
187 App,
188 client_id: client_id,
189 client_secret: client_secret
190 )
191 else
192 nil
193 end
194 end
195 end