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