2017-01-19 7 views
1

私はトークンを生成してそれを私のmysql dbに挿入したいと思います。これは現在のコードです。 mix phoenix.gen.secretはランダムな文字列を生成することができます。どうすればそれをコントローラに使用できますか?フェニックスのフレームワークコントローラを使用してランダムな文字列を生成

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 

エンド

答えて

7

あなたはmix phoenix.gen.secretuses internally:crypto.strong_rand_bytes/1を、使用することができます。

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" 
+0

iが追加 'defpのrandom_string(長さ)'私のコントローラでは、私は私のMap.Mergeにrandom_string呼び出すことができますか? – Joseph

+0

それは 'token_params = Map.merge(token_params、%{value:Token.random_string(32)})' 'を返し、関数MyApp.Token.random_string/1が未定義またはプライベートであることを返します ' – Joseph

+0

@JAlcantara 'Map.merge (token_params、%{"value" => random_string(32)}) '? 'Map.put(token_params、" value "、random_string(32))'のように、ここで 'Map.put'を使う方が適切です。 – Dogbert

1

フェニックスは、あなたがの信憑性を検証することを可能にするトークンを生成するためのビルトインPhoenix.Tokenモジュールを、持っていますトークンはデータベースにもぶつかることもありません。

# Generate a token for a given user_id 
user_id = # get id of current user 
token = Phoenix.Token.sign(MyApp.Endpoint, "user", user_id) 

# Later, verify and decode the token, 
# and assert that it matches the expected user_id 
user_id = # get id of current user 
{:ok, ^user_id} = Phoenix.Token.verify(MyApp.Endpoint, "user", token) 
+0

ありがとうございます。そのアプローチを試してみましょう。そのアプローチでは、生成されたトークンを自分のデータベースに挿入したいのですか? – Joseph

+0

はい、追加のトークンをデータベースに追加することはできますが、正確なユースケースに応じて、必要でない可能性があります。たとえばトークンを取り消すには、DBにトークンを格納する必要があります。 –

1

どうEctoの使用について:たとえば、特定のユーザーのためのトークンを生成したい場合は?

Ecto.UUID.generate |> binary_partは(16,16)

関連する問題