Merge branch '114_email_confirmation' into 'develop'
[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 plug(:fetch_session)
9 plug(:fetch_flash)
10
11 action_fallback(Pleroma.Web.OAuth.FallbackController)
12
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"]
20 })
21 end
22
23 def create_authorization(conn, %{
24 "authorization" =>
25 %{
26 "name" => name,
27 "password" => password,
28 "client_id" => client_id,
29 "redirect_uri" => redirect_uri
30 } = params
31 }) do
32 with %User{} = user <- User.get_by_nickname_or_email(name),
33 true <- Pbkdf2.checkpw(password, user.password_hash),
34 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
35 %App{} = app <- Repo.get_by(App, client_id: client_id),
36 {:ok, auth} <- Authorization.create_authorization(app, user) do
37 # Special case: Local MastodonFE.
38 redirect_uri =
39 if redirect_uri == "." do
40 mastodon_api_url(conn, :login)
41 else
42 redirect_uri
43 end
44
45 cond do
46 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
47 render(conn, "results.html", %{
48 auth: auth
49 })
50
51 true ->
52 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
53 url = "#{redirect_uri}#{connector}"
54 url_params = %{:code => auth.token}
55
56 url_params =
57 if params["state"] do
58 Map.put(url_params, :state, params["state"])
59 else
60 url_params
61 end
62
63 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
64
65 redirect(conn, external: url)
66 end
67 else
68 {:auth_active, false} ->
69 conn
70 |> put_flash(:error, "Account confirmation pending")
71 |> put_status(:forbidden)
72 |> authorize(params)
73
74 error ->
75 error
76 end
77 end
78
79 # TODO
80 # - proper scope handling
81 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
82 with %App{} = app <- get_app_from_request(conn, params),
83 fixed_token = fix_padding(params["code"]),
84 %Authorization{} = auth <-
85 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
86 {:ok, token} <- Token.exchange_token(app, auth),
87 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
88 response = %{
89 token_type: "Bearer",
90 access_token: token.token,
91 refresh_token: token.refresh_token,
92 created_at: DateTime.to_unix(inserted_at),
93 expires_in: 60 * 10,
94 scope: "read write follow"
95 }
96
97 json(conn, response)
98 else
99 _error ->
100 put_status(conn, 400)
101 |> json(%{error: "Invalid credentials"})
102 end
103 end
104
105 # TODO
106 # - investigate a way to verify the user wants to grant read/write/follow once scope handling is done
107 def token_exchange(
108 conn,
109 %{"grant_type" => "password", "username" => name, "password" => password} = params
110 ) do
111 with %App{} = app <- get_app_from_request(conn, params),
112 %User{} = user <- User.get_by_nickname_or_email(name),
113 true <- Pbkdf2.checkpw(password, user.password_hash),
114 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
115 {:ok, auth} <- Authorization.create_authorization(app, user),
116 {:ok, token} <- Token.exchange_token(app, auth) do
117 response = %{
118 token_type: "Bearer",
119 access_token: token.token,
120 refresh_token: token.refresh_token,
121 expires_in: 60 * 10,
122 scope: "read write follow"
123 }
124
125 json(conn, response)
126 else
127 {:auth_active, false} ->
128 conn
129 |> put_status(:forbidden)
130 |> json(%{error: "Account confirmation pending"})
131
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", "name" => name, "password" => _password} = params
141 ) do
142 params =
143 params
144 |> Map.delete("name")
145 |> Map.put("username", name)
146
147 token_exchange(conn, params)
148 end
149
150 def token_revoke(conn, %{"token" => token} = params) do
151 with %App{} = app <- get_app_from_request(conn, params),
152 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
153 {:ok, %Token{}} <- Repo.delete(token) do
154 json(conn, %{})
155 else
156 _error ->
157 # RFC 7009: invalid tokens [in the request] do not cause an error response
158 json(conn, %{})
159 end
160 end
161
162 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
163 # decoding it. Investigate sometime.
164 defp fix_padding(token) do
165 token
166 |> URI.decode()
167 |> Base.url_decode64!(padding: false)
168 |> Base.url_encode64()
169 end
170
171 defp get_app_from_request(conn, params) do
172 # Per RFC 6749, HTTP Basic is preferred to body params
173 {client_id, client_secret} =
174 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
175 {:ok, decoded} <- Base.decode64(encoded),
176 [id, secret] <-
177 String.split(decoded, ":")
178 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
179 {id, secret}
180 else
181 _ -> {params["client_id"], params["client_secret"]}
182 end
183
184 if client_id && client_secret do
185 Repo.get_by(
186 App,
187 client_id: client_id,
188 client_secret: client_secret
189 )
190 else
191 nil
192 end
193 end
194 end