tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

96 lignes · 2234 octetsBrut · Historique
1/// What a user registers with, checked once, where the form is read.
2///
3/// Both types are opaque (ADR 0033): other modules can name them but not
4/// build them, so the only way to get a `Username` or a `Password` is
5/// through `username` and `password` here. A function that takes one knows
6/// the rules below hold, without checking again; `credentials.Username("x")`
7/// or `credentials.Password(..p, ...)` elsewhere does not compile (E0117).
8
9import std/option
10import std/string
11import std/test.{assert, assert_equal}
12
13/// A user name: at least 2 characters.
14@derive Eq
15pub opaque type Username { Username(String) }
16
17/// Shown as the name itself: `"registered {name}"`.
18impl Show<Username>
19{
20 fn show :: u
21 {
22 name u
23 }
24}
25
26/// A password: at least 8 characters. It has no `Show`, so it cannot be
27/// logged by mistake (`"{password}"` does not compile); `secret` reads
28/// it, to hash it.
29pub opaque type Password { Password(String) }
30
31/// `text` as a user name, if it has at least 2 characters.
32pub fn username :: text: String -> Option<Username>
33{
34 if string.length text < 2
35 {
36 None
37 }
38 else
39 {
40 Some(Username(text))
41 }
42}
43
44pub fn name :: u: Username -> String
45{
46 match u { Username(text) -> text }
47}
48
49/// `text` as a password, if it has at least 8 characters.
50pub fn password :: text: String -> Option<Password>
51{
52 if string.length text < 8
53 {
54 None
55 }
56 else
57 {
58 Some(Password(text))
59 }
60}
61
62/// The password's text, for hashing and checking only.
63pub fn secret :: p: Password -> String
64{
65 match p { Password(text) -> text }
66}
67
68@test
69fn names_need_two_characters ::
70{
71 assert_equal (username "a") None
72 assert_equal (option.map (username "ab") name) Some("ab")
73}
74
75@test
76fn a_name_shows_as_itself ::
77{
78 assert_equal
79 (option.map (username "ada") fn u { "user {u}" })
80 Some("user ada")
81}
82
83@test
84fn passwords_need_eight_characters ::
85{
86 assert (option.is_none (password "1234567")) "7 characters"
87 assert_equal (option.map (password "12345678") secret) Some("12345678")
88}
89
90@test
91fn lengths_count_characters_not_bytes ::
92{
93 // "é" is 2 bytes in UTF-8, but 1 character.
94 assert_equal (username "é") None
95 assert (option.is_none (password "ééééééé")) "7 characters, 14 bytes"
96}