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