1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.OAuth.OAuthController do
6 use Pleroma.Web, :controller
8 alias Pleroma.Web.OAuth.{Authorization, Token, App}
9 alias Pleroma.{Repo, User}
12 import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2]
17 action_fallback(Pleroma.Web.OAuth.FallbackController)
19 def authorize(conn, params) do
20 app = Repo.get_by(App, client_id: params["client_id"])
21 available_scopes = (app && app.scopes) || []
22 scopes = oauth_scopes(params, nil) || available_scopes
24 render(conn, "show.html", %{
25 response_type: params["response_type"],
26 client_id: params["client_id"],
27 available_scopes: available_scopes,
29 redirect_uri: params["redirect_uri"],
30 state: params["state"]
34 def create_authorization(conn, %{
38 "password" => password,
39 "client_id" => client_id,
40 "redirect_uri" => redirect_uri
43 with %User{} = user <- User.get_by_nickname_or_email(name),
44 true <- Pbkdf2.checkpw(password, user.password_hash),
45 %App{} = app <- Repo.get_by(App, client_id: client_id),
46 true <- redirect_uri in String.split(app.redirect_uris),
47 scopes <- oauth_scopes(auth_params, []),
48 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
49 # Note: `scope` param is intentionally not optional in this context
50 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
51 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
52 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
53 # Special case: Local MastodonFE.
55 if redirect_uri == "." do
56 mastodon_api_url(conn, :login)
62 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
63 render(conn, "results.html", %{
68 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
69 url = "#{redirect_uri}#{connector}"
70 url_params = %{:code => auth.token}
73 if auth_params["state"] do
74 Map.put(url_params, :state, auth_params["state"])
79 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
81 redirect(conn, external: url)
84 {scopes_issue, _} when scopes_issue in [:unsupported_scopes, :missing_scopes] ->
86 |> put_flash(:error, "Permissions not specified.")
87 |> put_status(:unauthorized)
88 |> authorize(auth_params)
90 {:auth_active, false} ->
92 |> put_flash(:error, "Account confirmation pending.")
93 |> put_status(:forbidden)
94 |> authorize(auth_params)
101 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
102 with %App{} = app <- get_app_from_request(conn, params),
103 fixed_token = fix_padding(params["code"]),
104 %Authorization{} = auth <-
105 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
106 {:ok, token} <- Token.exchange_token(app, auth),
107 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
109 token_type: "Bearer",
110 access_token: token.token,
111 refresh_token: token.refresh_token,
112 created_at: DateTime.to_unix(inserted_at),
114 scope: Enum.join(token.scopes)
120 put_status(conn, 400)
121 |> json(%{error: "Invalid credentials"})
127 %{"grant_type" => "password", "username" => name, "password" => password} = params
129 with %App{} = app <- get_app_from_request(conn, params),
130 %User{} = user <- User.get_by_nickname_or_email(name),
131 true <- Pbkdf2.checkpw(password, user.password_hash),
132 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
133 scopes <- oauth_scopes(params, app.scopes),
134 [] <- scopes -- app.scopes,
135 true <- Enum.any?(scopes),
136 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
137 {:ok, token} <- Token.exchange_token(app, auth) do
139 token_type: "Bearer",
140 access_token: token.token,
141 refresh_token: token.refresh_token,
143 scope: Enum.join(token.scopes, " ")
148 {:auth_active, false} ->
150 |> put_status(:forbidden)
151 |> json(%{error: "Account confirmation pending"})
154 put_status(conn, 400)
155 |> json(%{error: "Invalid credentials"})
161 %{"grant_type" => "password", "name" => name, "password" => _password} = params
165 |> Map.delete("name")
166 |> Map.put("username", name)
168 token_exchange(conn, params)
171 def token_revoke(conn, %{"token" => token} = params) do
172 with %App{} = app <- get_app_from_request(conn, params),
173 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
174 {:ok, %Token{}} <- Repo.delete(token) do
178 # RFC 7009: invalid tokens [in the request] do not cause an error response
183 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
184 # decoding it. Investigate sometime.
185 defp fix_padding(token) do
188 |> Base.url_decode64!(padding: false)
189 |> Base.url_encode64()
192 defp get_app_from_request(conn, params) do
193 # Per RFC 6749, HTTP Basic is preferred to body params
194 {client_id, client_secret} =
195 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
196 {:ok, decoded} <- Base.decode64(encoded),
198 String.split(decoded, ":")
199 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
202 _ -> {params["client_id"], params["client_secret"]}
205 if client_id && client_secret do
208 client_id: client_id,
209 client_secret: client_secret