oauth_controller.ex 2.26 KB
Newer Older
1
2
3
defmodule Pleroma.Web.OAuth.OAuthController do
  use Pleroma.Web, :controller

lain's avatar
lain committed
4
5
  alias Pleroma.Web.OAuth.{Authorization, Token, App}
  alias Pleroma.{Repo, User}
6
7
  alias Comeonin.Pbkdf2

8
9
10
11
12
  plug :fetch_session
  plug :fetch_flash

  action_fallback Pleroma.Web.OAuth.FallbackController

13
14
15
16
17
  def authorize(conn, params) do
    render conn, "show.html", %{
      response_type: params["response_type"],
      client_id: params["client_id"],
      scope: params["scope"],
lain's avatar
lain committed
18
19
      redirect_uri: params["redirect_uri"],
      state: params["state"]
20
21
22
    }
  end

lain's avatar
lain committed
23
  def create_authorization(conn, %{"authorization" => %{"name" => name, "password" => password, "client_id" => client_id, "redirect_uri" => redirect_uri} = params}) do
24
25
    with %User{} = user <- User.get_cached_by_nickname(name),
         true <- Pbkdf2.checkpw(password, user.password_hash),
lain's avatar
lain committed
26
         %App{} = app <- Repo.get_by(App, client_id: client_id),
27
         {:ok, auth} <- Authorization.create_authorization(app, user) do
lain's avatar
lain committed
28
29
30
31
32
      if redirect_uri == "urn:ietf:wg:oauth:2.0:oob" do
        render conn, "results.html", %{
          auth: auth
        }
      else
lain's avatar
lain committed
33
34
        connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
        url = "#{redirect_uri}#{connector}code=#{auth.token}"
lain's avatar
lain committed
35
36
37
38
39
        url = if params["state"] do
          url <> "&state=#{params["state"]}"
        else
          url
        end
lain's avatar
lain committed
40
41
        redirect(conn, external: url)
      end
42
43
44
    end
  end

lain's avatar
lain committed
45
46
  # TODO
  # - proper scope handling
47
48
  def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
    with %App{} = app <- Repo.get_by(App, client_id: params["client_id"], client_secret: params["client_secret"]),
eal's avatar
eal committed
49
50
         fixed_token = fix_padding(params["code"]),
         %Authorization{} = auth <- Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
lain's avatar
lain committed
51
         {:ok, token} <- Token.exchange_token(app, auth) do
52
53
54
55
56
57
58
59
      response = %{
        token_type: "Bearer",
        access_token: token.token,
        refresh_token: token.refresh_token,
        expires_in: 60 * 10,
        scope: "read write follow"
      }
      json(conn, response)
eal's avatar
eal committed
60
61
    else
      _error -> json(conn, %{error: "Invalid credentials"})
62
63
    end
  end
eal's avatar
eal committed
64
65
66
67
68
69

  defp fix_padding(token) do
    token
    |> Base.url_decode64!(padding: false)
    |> Base.url_encode64
  end
70
end