# Copyright 2021 Nicolas Jouanin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule Polyjuice.Util.Randomizer do @moduledoc """ Random string generator module. """ @doc """ Generate random string based on the given length. It is also possible to generate certain type of randomise string using the options below: * :all - generate alphanumeric random string * :alpha - generate nom-numeric random string * :numeric - generate numeric random string * :upcase - generate upper case non-numeric random string * :downcase - generate lower case non-numeric random string * :upcase_numeric - generate uppercase alphanumeric random string * :downcase_numeric - generate downcase alphanumeric random string ## Example iex> Randomizer.randomizer(20) //"Je5QaLj982f0Meb0ZBSK" """ def randomize(length, type \\ :all) do alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" numbers = "0123456789" lists = cond do type == :alpha -> alphabets <> String.downcase(alphabets) type == :numeric -> numbers type == :upcase -> alphabets type == :downcase -> String.downcase(alphabets) type == :upcase_numeric -> alphabets <> numbers type == :downcase_numeric -> String.downcase(alphabets) <> numbers true -> alphabets <> String.downcase(alphabets) <> numbers end |> String.split("", trim: true) do_randomizer(length, lists) end @doc false defp get_range(length) when length > 1, do: 1..length defp get_range(_length), do: [1] @doc false defp do_randomizer(length, lists) do get_range(length) |> Enum.reduce([], fn _, acc -> [Enum.random(lists) | acc] end) |> Enum.join("") end @spec crypto_random_string(non_neg_integer()) :: binary() def crypto_random_string(length \\ 30) do length |> :crypto.strong_rand_bytes() |> Base.url_encode64(padding: false) end def unique_id() do UUID.uuid4(:hex) |> Base.url_encode64(padding: false) end end