github.com/greenpau/go-authcrunch@v1.1.4/pkg/identity/email.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  	"regexp"
    19  	"strings"
    20  
    21  	"github.com/greenpau/go-authcrunch/pkg/errors"
    22  )
    23  
    24  var emailRegex *regexp.Regexp
    25  
    26  func init() {
    27  	emailRegex = regexp.MustCompile(
    28  		"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9]" +
    29  			"(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9]" +
    30  			"(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$",
    31  	)
    32  }
    33  
    34  // EmailAddress is an instance of email address
    35  type EmailAddress struct {
    36  	Address   string `json:"address,omitempty" xml:"address,omitempty" yaml:"address,omitempty"`
    37  	Confirmed bool   `json:"confirmed,omitempty" xml:"confirmed,omitempty" yaml:"confirmed,omitempty"`
    38  	Domain    string `json:"domain,omitempty" xml:"domain,omitempty" yaml:"domain,omitempty"`
    39  	isPrimary bool
    40  }
    41  
    42  // NewEmailAddress returns an instance of EmailAddress.
    43  func NewEmailAddress(s string) (*EmailAddress, error) {
    44  	if !emailRegex.MatchString(s) {
    45  		return nil, errors.ErrEmailAddressInvalid
    46  	}
    47  	parts := strings.Split(s, "@")
    48  	addr := &EmailAddress{
    49  		Address: s,
    50  		Domain:  parts[1],
    51  	}
    52  	return addr, nil
    53  }
    54  
    55  // Primary returns true is the email is a primary email.
    56  func (m *EmailAddress) Primary() bool {
    57  	if m.isPrimary {
    58  		return true
    59  	}
    60  	return false
    61  }
    62  
    63  // ToString returns string representation of an email address.
    64  func (m *EmailAddress) ToString() string {
    65  	return m.Address
    66  }