gpt4 book ai didi

elixir - 如何使用 Elixir 生成随机 url 安全字符串

转载 作者:行者123 更新时间:2023-12-03 07:56:25 27 4
gpt4 key购买 nike

我需要能够生成随机的 url 安全字符串,以便我可以在链接中使用它们(例如在发送到用户电子邮件的激活链接中),那么我该如何生成呢?有没有办法只使用 Elixir 或者我必须使用一些库?

最佳答案

您可以做的是生成一个 Base64 编码的字符串以用作确认 token 。然后,此确认 token 将保存到您的数据库中,并作为参数传递给激活链接。您的激活网址如下所示:

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

上面的 url helper 假设你有一个 MyApp.ActivationController和一个 confirm/2该 Controller 中的操作。生成 confirm_id ,你可以这样做:
def random_string(length) do
:crypto.strong_rand_bytes(length) |> Base.url_encode64 |> binary_part(0, length)
end

# random_string(64)

在您的 MyApp.ActivationController.confirm/2 ,你可以有这样的代码:
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

希望有帮助!

关于elixir - 如何使用 Elixir 生成随机 url 安全字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32001606/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com