2017-08-02 15:56:33 +00:00
|
|
|
defmodule Asciinema.Accounts.ApiToken do
|
2017-07-29 19:01:40 +00:00
|
|
|
use Ecto.Schema
|
|
|
|
import Ecto.Changeset
|
2017-08-02 15:56:33 +00:00
|
|
|
alias Asciinema.Accounts.{ApiToken, User}
|
2017-06-12 09:52:50 +00:00
|
|
|
|
|
|
|
schema "api_tokens" do
|
|
|
|
field :token, :string
|
|
|
|
field :revoked_at, Timex.Ecto.DateTime
|
|
|
|
|
|
|
|
timestamps(inserted_at: :created_at)
|
|
|
|
|
2017-07-29 19:01:40 +00:00
|
|
|
belongs_to :user, User
|
2017-06-12 09:52:50 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
@uuid4 ~r/\A[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\z/
|
|
|
|
|
|
|
|
def create_changeset(%User{id: user_id}, token) do
|
|
|
|
%ApiToken{user_id: user_id}
|
|
|
|
|> change(%{token: token})
|
|
|
|
|> validate_format(:token, @uuid4)
|
|
|
|
end
|
|
|
|
|
|
|
|
def revoke_changeset(%ApiToken{revoked_at: nil} = api_token) do
|
|
|
|
change(api_token, %{revoked_at: Timex.now()})
|
|
|
|
end
|
|
|
|
def revoke_changeset(%ApiToken{} = api_token) do
|
|
|
|
change(api_token)
|
|
|
|
end
|
|
|
|
end
|