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
9 alias Pleroma.Web.OAuth.Token
10 alias Pleroma.Web.OAuth.App
15 import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2]
20 action_fallback(Pleroma.Web.OAuth.FallbackController)
22 def authorize(conn, params) do
23 app = Repo.get_by(App, client_id: params["client_id"])
24 available_scopes = (app && app.scopes) || []
25 scopes = oauth_scopes(params, nil) || available_scopes
27 render(conn, "show.html", %{
28 response_type: params["response_type"],
29 client_id: params["client_id"],
30 available_scopes: available_scopes,
32 redirect_uri: params["redirect_uri"],
33 state: params["state"]
37 def create_authorization(conn, %{
41 "password" => password,
42 "client_id" => client_id,
43 "redirect_uri" => redirect_uri
46 with %User{} = user <- User.get_by_nickname_or_email(name),
47 true <- Pbkdf2.checkpw(password, user.password_hash),
48 %App{} = app <- Repo.get_by(App, client_id: client_id),
49 true <- redirect_uri in String.split(app.redirect_uris),
50 scopes <- oauth_scopes(auth_params, []),
51 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
52 # Note: `scope` param is intentionally not optional in this context
53 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
54 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
55 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
56 # Special case: Local MastodonFE.
58 if redirect_uri == "." do
59 mastodon_api_url(conn, :login)
65 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
66 render(conn, "results.html", %{
71 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
72 url = "#{redirect_uri}#{connector}"
73 url_params = %{:code => auth.token}
76 if auth_params["state"] do
77 Map.put(url_params, :state, auth_params["state"])
82 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
84 redirect(conn, external: url)
87 {scopes_issue, _} when scopes_issue in [:unsupported_scopes, :missing_scopes] ->
89 |> put_flash(:error, "Permissions not specified.")
90 |> put_status(:unauthorized)
91 |> authorize(auth_params)
93 {:auth_active, false} ->
95 |> put_flash(:error, "Account confirmation pending.")
96 |> put_status(:forbidden)
97 |> authorize(auth_params)
104 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
105 with %App{} = app <- get_app_from_request(conn, params),
106 fixed_token = fix_padding(params["code"]),
107 %Authorization{} = auth <-
108 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
109 {:ok, token} <- Token.exchange_token(app, auth),
110 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
112 token_type: "Bearer",
113 access_token: token.token,
114 refresh_token: token.refresh_token,
115 created_at: DateTime.to_unix(inserted_at),
117 scope: Enum.join(token.scopes)
123 put_status(conn, 400)
124 |> json(%{error: "Invalid credentials"})
130 %{"grant_type" => "password", "username" => name, "password" => password} = params
132 with %App{} = app <- get_app_from_request(conn, params),
133 %User{} = user <- User.get_by_nickname_or_email(name),
134 true <- Pbkdf2.checkpw(password, user.password_hash),
135 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
136 scopes <- oauth_scopes(params, app.scopes),
137 [] <- scopes -- app.scopes,
138 true <- Enum.any?(scopes),
139 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
140 {:ok, token} <- Token.exchange_token(app, auth) do
142 token_type: "Bearer",
143 access_token: token.token,
144 refresh_token: token.refresh_token,
146 scope: Enum.join(token.scopes, " ")
151 {:auth_active, false} ->
153 |> put_status(:forbidden)
154 |> json(%{error: "Account confirmation pending"})
157 put_status(conn, 400)
158 |> json(%{error: "Invalid credentials"})
164 %{"grant_type" => "password", "name" => name, "password" => _password} = params
168 |> Map.delete("name")
169 |> Map.put("username", name)
171 token_exchange(conn, params)
174 def token_revoke(conn, %{"token" => token} = params) do
175 with %App{} = app <- get_app_from_request(conn, params),
176 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
177 {:ok, %Token{}} <- Repo.delete(token) do
181 # RFC 7009: invalid tokens [in the request] do not cause an error response
186 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
187 # decoding it. Investigate sometime.
188 defp fix_padding(token) do
191 |> Base.url_decode64!(padding: false)
192 |> Base.url_encode64(padding: false)
195 defp get_app_from_request(conn, params) do
196 # Per RFC 6749, HTTP Basic is preferred to body params
197 {client_id, client_secret} =
198 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
199 {:ok, decoded} <- Base.decode64(encoded),
201 String.split(decoded, ":")
202 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
205 _ -> {params["client_id"], params["client_secret"]}
208 if client_id && client_secret do
211 client_id: client_id,
212 client_secret: client_secret