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