Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

phoenix framework - How to generate a random url safe string with Elixir

I need to be able to generate random url safe strings so I could use those in links (like in an activation link sent to a user's email), so how can I generate it? Is there a way to do that only with Elixir or I'd have to use some library?

question from:https://stackoverflow.com/questions/32001606/how-to-generate-a-random-url-safe-string-with-elixir

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you can do instead is to generate a Base64-encoded string to be used as a confirmation token. This confirmation token will then be saved to your DB and passed as params to the activation link. Your activation url would look something like:

activation_url(MyApp.Endpoint, :confirm, confirm_id: confirm_id)

The above url helper assumes you have a MyApp.ActivationController and a confirm/2 action in that controller. To generate the confirm_id, you could do:

def random_string(length) do
  :crypto.strong_rand_bytes(length) |> Base.url_encode64 |> binary_part(0, length)
end

# random_string(64)

In your MyApp.ActivationController.confirm/2, you could have code lik:

def confirm(conn, %{"confirm_id" => confirm_id}) do
  user = Repo.get_by(User, confirm_id: confirm_id)
  User.confirm(user)
  conn
  |> put_flash(:info, "Account confirmed!")
  |> redirect(to: "/")
end

Hope that helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...