github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/kbun/username.go (about) 1 // Copyright 2018 Keybase, Inc. All rights reserved. Use of 2 // this source code is governed by the included BSD license. 3 4 package kbun 5 6 import ( 7 "regexp" 8 "strings" 9 ) 10 11 // UsernameRE is the regex for matching usernames. Underscores are allowed, 12 // just not first or doubled. 13 const UsernameRE = `(?:[a-zA-Z0-9]+_?)+` 14 15 var usernameRE = regexp.MustCompile("^" + UsernameRE + "$") 16 17 // CheckUsername returns true if the given string can be a Keybase 18 // username. 19 func CheckUsername(s string) bool { 20 return len(s) >= 2 && len(s) <= 16 && usernameRE.MatchString(s) 21 } 22 23 // NormalizedUsername is a Keybase username that has been normalized 24 // (toLowered) and therefore will compare correctly against other 25 // normalized usernames. 26 type NormalizedUsername string 27 28 // NewNormalizedUsername makes a normalized username out of a non-normalized 29 // plain string username 30 func NewNormalizedUsername(s string) NormalizedUsername { 31 return NormalizedUsername(strings.ToLower(s)) 32 } 33 34 // Eq returns true if the given normalized usernames are equal 35 func (n NormalizedUsername) Eq(n2 NormalizedUsername) bool { 36 return string(n) == string(n2) 37 } 38 39 // String returns the normalized username as a string (in lower case) 40 func (n NormalizedUsername) String() string { return string(n) } 41 42 // IsNil returns true if the username is the empty string 43 func (n NormalizedUsername) IsNil() bool { return len(string(n)) == 0 } 44 45 // IsValid returns CheckUsername(n.String()). 46 func (n NormalizedUsername) IsValid() bool { return CheckUsername(string(n)) }