diff options
author | Lunny Xiao <xiaolunwen@gmail.com> | 2022-03-15 01:39:54 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-03-14 18:39:54 +0100 |
commit | 18033f49ba8f00695dd9f885360664a383610df1 (patch) | |
tree | df3c1f1738353a7fffc4ac7b9e6c48e3af231b9c /models/user/email_address.go | |
parent | 49db87a035a28cd8eaa4abdd5832f952ca6449d9 (diff) | |
download | gitea-18033f49ba8f00695dd9f885360664a383610df1.tar.gz gitea-18033f49ba8f00695dd9f885360664a383610df1.zip |
Restrict email address validation (#17688)
This didn't follow the RFC but it's a subset of that. I think we should narrow the allowed chars at first and discuss more possibility in future PRs.
Diffstat (limited to 'models/user/email_address.go')
-rw-r--r-- | models/user/email_address.go | 30 |
1 files changed, 29 insertions, 1 deletions
diff --git a/models/user/email_address.go b/models/user/email_address.go index 726af7b3b4..564d018dac 100644 --- a/models/user/email_address.go +++ b/models/user/email_address.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "net/mail" + "regexp" "strings" "code.gitea.io/gitea/models/db" @@ -22,7 +23,22 @@ import ( ) // ErrEmailNotActivated e-mail address has not been activated error -var ErrEmailNotActivated = errors.New("E-mail address has not been activated") +var ErrEmailNotActivated = errors.New("e-mail address has not been activated") + +// ErrEmailCharIsNotSupported e-mail address contains unsupported character +type ErrEmailCharIsNotSupported struct { + Email string +} + +// IsErrEmailCharIsNotSupported checks if an error is an ErrEmailCharIsNotSupported +func IsErrEmailCharIsNotSupported(err error) bool { + _, ok := err.(ErrEmailCharIsNotSupported) + return ok +} + +func (err ErrEmailCharIsNotSupported) Error() string { + return fmt.Sprintf("e-mail address contains unsupported character [email: %s]", err.Email) +} // ErrEmailInvalid represents an error where the email address does not comply with RFC 5322 type ErrEmailInvalid struct { @@ -106,12 +122,24 @@ func (email *EmailAddress) BeforeInsert() { } } +var emailRegexp = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") + // ValidateEmail check if email is a allowed address func ValidateEmail(email string) error { if len(email) == 0 { return nil } + if !emailRegexp.MatchString(email) { + return ErrEmailCharIsNotSupported{email} + } + + if !(email[0] >= 'a' && email[0] <= 'z') && + !(email[0] >= 'A' && email[0] <= 'Z') && + !(email[0] >= '0' && email[0] <= '9') { + return ErrEmailInvalid{email} + } + if _, err := mail.ParseAddress(email); err != nil { return ErrEmailInvalid{email} } |