MastoAPI: Add max_toot_chars.
[akkoma] / lib / pleroma / web / oauth / 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 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
29 url = "#{redirect_uri}#{connector}code=#{auth.token}"
30 url = if params["state"] do
31 url <> "&state=#{params["state"]}"
32 else
33 url
34 end
35 redirect(conn, external: url)
36 end
37 end
38 end
39
40 # TODO
41 # - proper scope handling
42 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
43 with %App{} = app <- Repo.get_by(App, client_id: params["client_id"], client_secret: params["client_secret"]),
44 fixed_token = fix_padding(params["code"]),
45 %Authorization{} = auth <- Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
46 {:ok, token} <- Token.exchange_token(app, auth) do
47 response = %{
48 token_type: "Bearer",
49 access_token: token.token,
50 refresh_token: token.refresh_token,
51 expires_in: 60 * 10,
52 scope: "read write follow"
53 }
54 json(conn, response)
55 else
56 _error -> json(conn, %{error: "Invalid credentials"})
57 end
58 end
59
60 defp fix_padding(token) do
61 token
62 |> Base.url_decode64!(padding: false)
63 |> Base.url_encode64
64 end
65 end