update
This commit is contained in:
parent
e2967f68b2
commit
ef2a6c41b4
39 changed files with 2349 additions and 30 deletions
36
lib/zoeyscomputer/api_keys/api_key.ex
Normal file
36
lib/zoeyscomputer/api_keys/api_key.ex
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
defmodule Zoeyscomputer.ApiKeys.ApiKey do
|
||||
use Ecto.Schema
|
||||
import Ecto.Changeset
|
||||
alias Zoeyscomputer.Users.User
|
||||
|
||||
schema "api_keys" do
|
||||
field :name, :string
|
||||
field :token, :string
|
||||
belongs_to :user, User
|
||||
|
||||
timestamps(type: :utc_datetime)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def changeset(api_key, attrs) do
|
||||
api_key
|
||||
# Make sure both fields are in cast
|
||||
|> cast(attrs, [:name, :user_id])
|
||||
|> validate_required([:name, :user_id])
|
||||
# This needs to happen before validation
|
||||
|> put_token()
|
||||
# Add token to required fields
|
||||
|> validate_required([:token])
|
||||
end
|
||||
|
||||
defp put_token(changeset) do
|
||||
case changeset do
|
||||
%Ecto.Changeset{valid?: true} ->
|
||||
token = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
|
||||
put_change(changeset, :token, token)
|
||||
|
||||
_ ->
|
||||
changeset
|
||||
end
|
||||
end
|
||||
end
|
||||
Loading…
Add table
Add a link
Reference in a new issue