I want to generate a token and insert it to my mysql db, this is the current code, im just passing '123'. mix phoenix.gen.secret can generate random string how can i use it to my controller?
def create(conn, %{"token" => token_params}) do
token_params = Map.merge(token_params, %{"value" => "123"})
changeset = Token.changeset(%Token{}, token_params)
case Repo.insert(changeset) do
{:ok, token} ->
conn
|> put_status(:created)
|> put_resp_header("location", token_path(conn, :show, token))
|> render("show.json", token: token)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(MyApp.ChangesetView, "error.json", changeset: changeset)
end
end
You can use :crypto.strong_rand_bytes/1
, which mix phoenix.gen.secret
uses internally:
iex(1)> length = 32
32
iex(3)> :crypto.strong_rand_bytes(length) |> Base.encode64 |> binary_part(0, length)
"YiX2oINVqVWCCQZdmESBN44OxcErAFR4"
iex(4)> :crypto.strong_rand_bytes(length) |> Base.encode64 |> binary_part(0, length)
"ka2PSR9cHYSlD6fhdMpnGHgTVA7AoDwN"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With