💾 Archived View for gemini.rmf-dev.com › repo › Vaati › gmiChat › files › 54779a4e59f838b1a101ad6a69… captured on 2023-09-08 at 16:19:31. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2023-03-20)
-=-=-=-=-=-=-
0 defmodule Gmichat.User do
1 use Ecto.Schema
2
3 schema "users" do
4 field :name, :string
5 field :password, :string
6 field :timezone, :integer
7 field :leftmargin, :integer
8 field :linelength, :integer
9 field :timestamp, :integer
10 end
11
12 def validate_password(changeset) do
13 password = Ecto.Changeset.get_field(changeset, :password)
14 len = if is_bitstring(password) do String.length(password) else 0 end
15 cond do
16 password == :ignore ->
17 changeset
18 len < 6 or len > 24 ->
19 Ecto.Changeset.add_error(changeset, :password, "must be between 6 and 24")
20 true ->
21 Ecto.Changeset.put_change(changeset, :password, Argon2.hash_pwd_salt(password))
22 end
23 end
24
25 def is_name_valid(name) do
26 if name == [] do
27 true
28 else
29 c = hd(name)
30 if (c >= ?a and c <= ?z) or (c >= ?A and c <= ?Z) or (c >= ?0 and c <= ?9) do
31 is_name_valid(tl(name))
32 else
33 false
34 end
35 end
36 end
37
38 def validate_name(changeset) do
39 name = Ecto.Changeset.get_field(changeset, :name)
40 len = String.length(name)
41 cond do
42 !is_name_valid(to_charlist(name)) ->
43 Ecto.Changeset.add_error(changeset, :name, "must contains only letters and numbers")
44 len < 3 or len > 12 ->
45 Ecto.Changeset.add_error(changeset, :name, "must be between 3 and 12 characters")
46 true ->
47 changeset
48 end
49 end
50
51 def validate_timezone(changeset) do
52 zone = Ecto.Changeset.get_field(changeset, :timezone)
53 if zone < -14 or zone > 14 do
54 Ecto.Changeset.add_error(changeset, :timezone, "must be between -14 and 14")
55 else
56 changeset
57 end
58 end
59
60 def validate_linelength(changeset) do
61 ll = Ecto.Changeset.get_field(changeset, :linelength)
62 if ll < 0 or ll > 1024 do
63 Ecto.Changeset.add_error(changeset, :linelength, "must be between 0 and 1024")
64 else
65 changeset
66 end
67 end
68
69 def validate_leftmargin(changeset) do
70 ll = Ecto.Changeset.get_field(changeset, :leftmargin)
71 if ll < 0 or ll > 4096 do
72 Ecto.Changeset.add_error(changeset, :leftmargin, "must be between 0 and 4096")
73 else
74 changeset
75 end
76 end
77
78
79 def changeset(user, params \\ %{}) do
80 user
81 |> Ecto.Changeset.cast(params, [:name, :password, :timezone,
82 :linelength, :leftmargin, :timestamp])
83 |> validate_name
84 |> validate_password
85 |> validate_timezone
86 |> validate_linelength
87 |> validate_leftmargin
88 |> Ecto.Changeset.unique_constraint(:name)
89 end
90
91 end
92