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