Merge branch 'admin-api-account-view-namespace' into 'develop'
[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 Comeonin.Pbkdf2
9 alias Pleroma.Repo
10 alias Pleroma.User
11 alias Pleroma.Web.Auth.Authenticator
12 alias Pleroma.Web.OAuth.App
13 alias Pleroma.Web.OAuth.Authorization
14 alias Pleroma.Web.OAuth.Token
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 <- User.get_by_nickname_or_email(name),
133 true <- Pbkdf2.checkpw(password, user.password_hash),
134 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
135 scopes <- oauth_scopes(params, app.scopes),
136 [] <- scopes -- app.scopes,
137 true <- Enum.any?(scopes),
138 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
139 {:ok, token} <- Token.exchange_token(app, auth) do
140 response = %{
141 token_type: "Bearer",
142 access_token: token.token,
143 refresh_token: token.refresh_token,
144 expires_in: 60 * 10,
145 scope: Enum.join(token.scopes, " ")
146 }
147
148 json(conn, response)
149 else
150 {:auth_active, false} ->
151 conn
152 |> put_status(:forbidden)
153 |> json(%{error: "Account confirmation pending"})
154
155 _error ->
156 put_status(conn, 400)
157 |> json(%{error: "Invalid credentials"})
158 end
159 end
160
161 def token_exchange(
162 conn,
163 %{"grant_type" => "password", "name" => name, "password" => _password} = params
164 ) do
165 params =
166 params
167 |> Map.delete("name")
168 |> Map.put("username", name)
169
170 token_exchange(conn, params)
171 end
172
173 def token_revoke(conn, %{"token" => token} = params) do
174 with %App{} = app <- get_app_from_request(conn, params),
175 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
176 {:ok, %Token{}} <- Repo.delete(token) do
177 json(conn, %{})
178 else
179 _error ->
180 # RFC 7009: invalid tokens [in the request] do not cause an error response
181 json(conn, %{})
182 end
183 end
184
185 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
186 # decoding it. Investigate sometime.
187 defp fix_padding(token) do
188 token
189 |> URI.decode()
190 |> Base.url_decode64!(padding: false)
191 |> Base.url_encode64(padding: false)
192 end
193
194 defp get_app_from_request(conn, params) do
195 # Per RFC 6749, HTTP Basic is preferred to body params
196 {client_id, client_secret} =
197 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
198 {:ok, decoded} <- Base.decode64(encoded),
199 [id, secret] <-
200 String.split(decoded, ":")
201 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
202 {id, secret}
203 else
204 _ -> {params["client_id"], params["client_secret"]}
205 end
206
207 if client_id && client_secret do
208 Repo.get_by(
209 App,
210 client_id: client_id,
211 client_secret: client_secret
212 )
213 else
214 nil
215 end
216 end
217 end