841df8c32d24d1a5f4b96bf2706f568fd4e61441
[akkoma] / oauth_controller.ex
1 defmodule Pleroma.Web.OAuth.OAuthController do
2 use Pleroma.Web, :controller
3
4 alias Pleroma.Web.OAuth.{Authorization, Token, App}
5 alias Pleroma.{Repo, User}
6 alias Comeonin.Pbkdf2
7
8 def authorize(conn, params) do
9 render conn, "show.html", %{
10 response_type: params["response_type"],
11 client_id: params["client_id"],
12 scope: params["scope"],
13 redirect_uri: params["redirect_uri"],
14 state: params["state"]
15 }
16 end
17
18 def create_authorization(conn, %{"authorization" => %{"name" => name, "password" => password, "client_id" => client_id, "redirect_uri" => redirect_uri} = params}) do
19 with %User{} = user <- User.get_cached_by_nickname(name),
20 true <- Pbkdf2.checkpw(password, user.password_hash),
21 %App{} = app <- Repo.get_by(App, client_id: client_id),
22 {:ok, auth} <- Authorization.create_authorization(app, user) do
23 if redirect_uri == "urn:ietf:wg:oauth:2.0:oob" do
24 render conn, "results.html", %{
25 auth: auth
26 }
27 else
28 url = "#{redirect_uri}?code=#{auth.token}"
29 url = if params["state"] do
30 url <> "&state=#{params["state"]}"
31 else
32 url
33 end
34 redirect(conn, external: url)
35 end
36 end
37 end
38
39 # TODO
40 # - proper scope handling
41 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
42 with %App{} = app <- Repo.get_by(App, client_id: params["client_id"], client_secret: params["client_secret"]),
43 fixed_token = fix_padding(params["code"]),
44 %Authorization{} = auth <- Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
45 {:ok, token} <- Token.exchange_token(app, auth) do
46 response = %{
47 token_type: "Bearer",
48 access_token: token.token,
49 refresh_token: token.refresh_token,
50 expires_in: 60 * 10,
51 scope: "read write follow"
52 }
53 json(conn, response)
54 else
55 _error -> json(conn, %{error: "Invalid credentials"})
56 end
57 end
58
59 defp fix_padding(token) do
60 token
61 |> Base.url_decode64!(padding: false)
62 |> Base.url_encode64
63 end
64 end