github.com/greenpau/go-authcrunch@v1.1.4/pkg/identity/name.go (about) 1 // Copyright 2022 Paul Greenberg greenpau@outlook.com 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package identity 16 17 import ( 18 "github.com/greenpau/go-authcrunch/pkg/errors" 19 "strings" 20 ) 21 22 // Name represents human name 23 type Name struct { 24 First string `json:"first,omitempty" xml:"first,omitempty" yaml:"first,omitempty"` 25 Last string `json:"last,omitempty" xml:"last,omitempty" yaml:"last,omitempty"` 26 Middle string `json:"middle,omitempty" xml:"middle,omitempty" yaml:"middle,omitempty"` 27 Preferred string `json:"preferred,omitempty" xml:"preferred,omitempty" yaml:"preferred,omitempty"` 28 Nickname bool `json:"nickname,omitempty" xml:"nickname,omitempty" yaml:"nickname,omitempty"` 29 Confirmed bool `json:"confirmed,omitempty" xml:"confirmed,omitempty" yaml:"confirmed,omitempty"` 30 Primary bool `json:"primary,omitempty" xml:"primary,omitempty" yaml:"primary,omitempty"` 31 Legal bool `json:"legal,omitempty" xml:"legal,omitempty" yaml:"legal,omitempty"` 32 Alias bool `json:"alias,omitempty" xml:"alias,omitempty" yaml:"alias,omitempty"` 33 } 34 35 // NewName returns an instance of Name. 36 func NewName() *Name { 37 return &Name{} 38 } 39 40 // GetNameClaim returns name field of a claim. 41 func (n *Name) GetNameClaim() string { 42 return n.GetFullName() 43 } 44 45 // ToString returns string represenation of name. 46 func (n *Name) ToString() string { 47 return n.GetFullName() 48 } 49 50 // GetFullName returns the primary full name for User. 51 func (n *Name) GetFullName() string { 52 if n.Alias { 53 return n.Last 54 } 55 var b strings.Builder 56 if n.Last != "" { 57 b.WriteString(n.Last) 58 } 59 if n.First != "" { 60 b.WriteString(", " + n.First) 61 } 62 return b.String() 63 } 64 65 // ParseName parses name from input. 66 func ParseName(s string) (*Name, error) { 67 s = strings.TrimSpace(s) 68 n := &Name{} 69 var x, y int 70 for i, sp := range []string{",", " "} { 71 x = 0 72 y = 1 73 if i == 1 { 74 x = 1 75 y = 0 76 } 77 if !strings.Contains(s, sp) { 78 continue 79 } 80 arr := strings.Split(s, sp) 81 if len(arr) == 2 { 82 n.Last = strings.TrimSpace(arr[x]) 83 n.First = strings.TrimSpace(arr[y]) 84 return n, nil 85 } 86 } 87 88 if s == "" { 89 return nil, errors.ErrParseNameFailed.WithArgs(s) 90 } 91 92 n.Last = s 93 n.Alias = true 94 return n, nil 95 }