diff options
author | Roger Braun <roger@rogerbraun.net> | 2017-09-09 12:02:59 +0200 |
---|---|---|
committer | Roger Braun <roger@rogerbraun.net> | 2017-09-09 12:02:59 +0200 |
commit | 95cedd60004893fd646735d17f7196297c38e22c (patch) | |
tree | 9915027eb19f458aa8627f8ac886518a27e41d79 /lib | |
parent | 890503ca1ea4308664d31622eb19208757a4c881 (diff) | |
download | pleroma-95cedd60004893fd646735d17f7196297c38e22c.tar.gz |
Make auth tokens usable once and expire them.
Diffstat (limited to 'lib')
-rw-r--r-- | lib/pleroma/web/oauth/authorization.ex | 17 | ||||
-rw-r--r-- | lib/pleroma/web/oauth/token.ex | 9 |
2 files changed, 25 insertions, 1 deletions
diff --git a/lib/pleroma/web/oauth/authorization.ex b/lib/pleroma/web/oauth/authorization.ex index c47289455..1ba5be602 100644 --- a/lib/pleroma/web/oauth/authorization.ex +++ b/lib/pleroma/web/oauth/authorization.ex @@ -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 diff --git a/lib/pleroma/web/oauth/token.ex b/lib/pleroma/web/oauth/token.ex index da723d6d6..828a966fb 100644 --- a/lib/pleroma/web/oauth/token.ex +++ b/lib/pleroma/web/oauth/token.ex @@ -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 |