/// What a user registers with, checked once, where the form is read. /// /// Both types are opaque (ADR 0033): other modules can name them but not /// build them, so the only way to get a `Username` or a `Password` is /// through `username` and `password` here. A function that takes one knows /// the rules below hold, without checking again; `credentials.Username("x")` /// or `credentials.Password(..p, ...)` elsewhere does not compile (E0117). import std/option import std/string import std/test.{assert, assert_equal} /// A user name: at least 2 characters. @derive Eq pub opaque type Username { Username(String) } /// Shown as the name itself: `"registered {name}"`. impl Show { fn show :: u { name u } } /// A password: at least 8 characters. It has no `Show`, so it cannot be /// logged by mistake (`"{password}"` does not compile); `secret` reads /// it, to hash it. pub opaque type Password { Password(String) } /// `text` as a user name, if it has at least 2 characters. pub fn username :: text: String -> Option { if string.length text < 2 { None } else { Some(Username(text)) } } pub fn name :: u: Username -> String { match u { Username(text) -> text } } /// `text` as a password, if it has at least 8 characters. pub fn password :: text: String -> Option { if string.length text < 8 { None } else { Some(Password(text)) } } /// The password's text, for hashing and checking only. pub fn secret :: p: Password -> String { match p { Password(text) -> text } } @test fn names_need_two_characters :: { assert_equal (username "a") None assert_equal (option.map (username "ab") name) Some("ab") } @test fn a_name_shows_as_itself :: { assert_equal (option.map (username "ada") fn u { "user {u}" }) Some("user ada") } @test fn passwords_need_eight_characters :: { assert (option.is_none (password "1234567")) "7 characters" assert_equal (option.map (password "12345678") secret) Some("12345678") } @test fn lengths_count_characters_not_bytes :: { // "é" is 2 bytes in UTF-8, but 1 character. assert_equal (username "é") None assert (option.is_none (password "ééééééé")) "7 characters, 14 bytes" }