Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phoenix framework Generate random string using the controller

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

like image 609
Joseph Avatar asked Dec 01 '22 15:12

Joseph


1 Answers

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"
like image 60
Dogbert Avatar answered Jun 05 '23 20:06

Dogbert