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