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.Auth.DatabaseAuthenticator
9 alias Pleroma.Web.OAuth.Authorization
10 alias Pleroma.Web.OAuth.Token
11 alias Pleroma.Web.OAuth.App
16 import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2]
21 action_fallback(Pleroma.Web.OAuth.FallbackController)
23 def authorize(conn, params) do
24 app = Repo.get_by(App, client_id: params["client_id"])
25 available_scopes = (app && app.scopes) || []
26 scopes = oauth_scopes(params, nil) || available_scopes
28 template = Application.get_env(:pleroma, :auth_template, "show.html")
30 render(conn, template, %{
31 response_type: params["response_type"],
32 client_id: params["client_id"],
33 available_scopes: available_scopes,
35 redirect_uri: params["redirect_uri"],
36 state: params["state"],
41 def create_authorization(conn, %{
44 "client_id" => client_id,
45 "redirect_uri" => redirect_uri
48 with {_, {:ok, %User{} = user}} <- {:get_user, DatabaseAuthenticator.get_user(conn)},
49 %App{} = app <- Repo.get_by(App, client_id: client_id),
50 true <- redirect_uri in String.split(app.redirect_uris),
51 scopes <- oauth_scopes(auth_params, []),
52 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
53 # Note: `scope` param is intentionally not optional in this context
54 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
55 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
56 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
58 if redirect_uri == "." do
59 # Special case: Local MastodonFE
60 mastodon_api_url(conn, :login)
66 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
67 render(conn, "results.html", %{
72 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
73 url = "#{redirect_uri}#{connector}"
74 url_params = %{:code => auth.token}
77 if auth_params["state"] do
78 Map.put(url_params, :state, auth_params["state"])
83 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
85 redirect(conn, external: url)
88 {scopes_issue, _} when scopes_issue in [:unsupported_scopes, :missing_scopes] ->
90 |> put_flash(:error, "Permissions not specified.")
91 |> put_status(:unauthorized)
92 |> authorize(auth_params)
94 {:auth_active, false} ->
96 |> put_flash(:error, "Account confirmation pending.")
97 |> put_status(:forbidden)
98 |> authorize(auth_params)
101 DatabaseAuthenticator.handle_error(conn, error)
105 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
106 with %App{} = app <- get_app_from_request(conn, params),
107 fixed_token = fix_padding(params["code"]),
108 %Authorization{} = auth <-
109 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
110 {:ok, token} <- Token.exchange_token(app, auth),
111 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
113 token_type: "Bearer",
114 access_token: token.token,
115 refresh_token: token.refresh_token,
116 created_at: DateTime.to_unix(inserted_at),
118 scope: Enum.join(token.scopes)
124 put_status(conn, 400)
125 |> json(%{error: "Invalid credentials"})
131 %{"grant_type" => "password", "username" => name, "password" => password} = params
133 with %App{} = app <- get_app_from_request(conn, params),
134 %User{} = user <- User.get_by_nickname_or_email(name),
135 true <- Pbkdf2.checkpw(password, user.password_hash),
136 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
137 scopes <- oauth_scopes(params, app.scopes),
138 [] <- scopes -- app.scopes,
139 true <- Enum.any?(scopes),
140 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
141 {:ok, token} <- Token.exchange_token(app, auth) do
143 token_type: "Bearer",
144 access_token: token.token,
145 refresh_token: token.refresh_token,
147 scope: Enum.join(token.scopes, " ")
152 {:auth_active, false} ->
154 |> put_status(:forbidden)
155 |> json(%{error: "Account confirmation pending"})
158 put_status(conn, 400)
159 |> json(%{error: "Invalid credentials"})
165 %{"grant_type" => "password", "name" => name, "password" => _password} = params
169 |> Map.delete("name")
170 |> Map.put("username", name)
172 token_exchange(conn, params)
175 def token_revoke(conn, %{"token" => token} = params) do
176 with %App{} = app <- get_app_from_request(conn, params),
177 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
178 {:ok, %Token{}} <- Repo.delete(token) do
182 # RFC 7009: invalid tokens [in the request] do not cause an error response
187 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
188 # decoding it. Investigate sometime.
189 defp fix_padding(token) do
192 |> Base.url_decode64!(padding: false)
193 |> Base.url_encode64(padding: false)
196 defp get_app_from_request(conn, params) do
197 # Per RFC 6749, HTTP Basic is preferred to body params
198 {client_id, client_secret} =
199 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
200 {:ok, decoded} <- Base.decode64(encoded),
202 String.split(decoded, ":")
203 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
206 _ -> {params["client_id"], params["client_secret"]}
209 if client_id && client_secret do
212 client_id: client_id,
213 client_secret: client_secret