1 defmodule Pleroma.Web.OAuth.OAuthController do
2 use Pleroma.Web, :controller
4 alias Pleroma.Web.OAuth.{Authorization, Token, App}
5 alias Pleroma.{Repo, User}
11 action_fallback(Pleroma.Web.OAuth.FallbackController)
13 def authorize(conn, params) do
14 render(conn, "show.html", %{
15 response_type: params["response_type"],
16 client_id: params["client_id"],
17 scope: params["scope"],
18 redirect_uri: params["redirect_uri"],
19 state: params["state"]
23 def create_authorization(conn, %{
27 "password" => password,
28 "client_id" => client_id,
29 "redirect_uri" => redirect_uri
32 with %User{} = user <- User.get_by_nickname_or_email(name),
33 true <- Pbkdf2.checkpw(password, user.password_hash),
34 %App{} = app <- Repo.get_by(App, client_id: client_id),
35 {:ok, auth} <- Authorization.create_authorization(app, user) do
36 if redirect_uri == "urn:ietf:wg:oauth:2.0:oob" do
37 render(conn, "results.html", %{
41 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
42 url = "#{redirect_uri}#{connector}code=#{auth.token}"
46 url <> "&state=#{params["state"]}"
51 redirect(conn, external: url)
57 # - proper scope handling
58 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
62 client_id: params["client_id"],
63 client_secret: params["client_secret"]
65 fixed_token = fix_padding(params["code"]),
66 %Authorization{} = auth <-
67 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
68 {:ok, token} <- Token.exchange_token(app, auth) do
71 access_token: token.token,
72 refresh_token: token.refresh_token,
74 scope: "read write follow"
79 _error -> json(conn, %{error: "Invalid credentials"})
84 # - investigate a way to verify the user wants to grant read/write/follow once scope handling is done
87 %{"grant_type" => "password", "name" => name, "password" => password} = params
92 client_id: params["client_id"],
93 client_secret: params["client_secret"]
95 %User{} = user <- User.get_cached_by_nickname(name),
96 true <- Pbkdf2.checkpw(password, user.password_hash),
97 {:ok, auth} <- Authorization.create_authorization(app, user),
98 {:ok, token} <- Token.exchange_token(app, auth) do
100 token_type: "Bearer",
101 access_token: token.token,
102 refresh_token: token.refresh_token,
104 scope: "read write follow"
109 _error -> json(conn, %{error: "Invalid credentials"})
113 defp fix_padding(token) do
115 |> Base.url_decode64!(padding: false)
116 |> Base.url_encode64()