Make auth tokens usable once and expire them.
This commit is contained in:
parent
890503ca1e
commit
95cedd6000
4 changed files with 91 additions and 1 deletions
|
|
@ -4,6 +4,8 @@ defmodule Pleroma.Web.OAuth.Authorization do
|
|||
alias Pleroma.{User, Repo}
|
||||
alias Pleroma.Web.OAuth.{Authorization, App}
|
||||
|
||||
import Ecto.{Changeset}
|
||||
|
||||
schema "oauth_authorizations" do
|
||||
field :token, :string
|
||||
field :valid_until, :naive_datetime
|
||||
|
|
@ -27,4 +29,19 @@ defmodule Pleroma.Web.OAuth.Authorization do
|
|||
|
||||
Repo.insert(authorization)
|
||||
end
|
||||
|
||||
def use_changeset(%Authorization{} = auth, params) do
|
||||
auth
|
||||
|> cast(params, [:used])
|
||||
|> validate_required([:used])
|
||||
end
|
||||
|
||||
def use_token(%Authorization{used: false, valid_until: valid_until} = auth) do
|
||||
if NaiveDateTime.diff(NaiveDateTime.utc_now, valid_until) < 0 do
|
||||
Repo.update(use_changeset(auth, %{used: true}))
|
||||
else
|
||||
{:error, "token expired"}
|
||||
end
|
||||
end
|
||||
def use_token(%Authorization{used: true}), do: {:error, "already used"}
|
||||
end
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ defmodule Pleroma.Web.OAuth.Token do
|
|||
use Ecto.Schema
|
||||
|
||||
alias Pleroma.{User, Repo}
|
||||
alias Pleroma.Web.OAuth.{Token, App}
|
||||
alias Pleroma.Web.OAuth.{Token, App, Authorization}
|
||||
|
||||
schema "oauth_tokens" do
|
||||
field :token, :string
|
||||
|
|
@ -14,6 +14,13 @@ defmodule Pleroma.Web.OAuth.Token do
|
|||
timestamps()
|
||||
end
|
||||
|
||||
def exchange_token(app, auth) do
|
||||
with {:ok, auth} <- Authorization.use_token(auth),
|
||||
true <- auth.app_id == app.id do
|
||||
create_token(app, Repo.get(User, auth.user_id))
|
||||
end
|
||||
end
|
||||
|
||||
def create_token(%App{} = app, %User{} = user) do
|
||||
token = :crypto.strong_rand_bytes(32) |> Base.url_encode64
|
||||
refresh_token = :crypto.strong_rand_bytes(32) |> Base.url_encode64
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue