github.com/greenpau/go-identity@v1.1.6/email.go (about)

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