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