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