1
0
mirror of https://github.com/mainflux/mainflux.git synced 2025-04-29 13:49:28 +08:00

75 lines
1.5 KiB
Go
Raw Normal View History

//
2019-07-18 15:01:09 +02:00
// Copyright (c) 2019
// Mainflux
//
// SPDX-License-Identifier: Apache-2.0
//
2018-05-10 23:53:25 +02:00
package users
2019-07-18 15:01:09 +02:00
import (
"context"
"regexp"
"strings"
)
2019-07-18 15:01:09 +02:00
var (
userRegexp = regexp.MustCompile("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+$")
hostRegexp = regexp.MustCompile("^[^\\s]+\\.[^\\s]+$")
userDotRegexp = regexp.MustCompile("(^[.]{1})|([.]{1}$)|([.]{2,})")
2019-07-18 15:01:09 +02:00
)
2018-05-10 23:53:25 +02:00
2018-05-11 01:00:10 +02:00
// User represents a Mainflux user account. Each user is identified given its
// email and password.
type User struct {
Email string
Password string
2018-05-10 23:53:25 +02:00
}
2018-05-11 01:00:10 +02:00
// Validate returns an error if user representation is invalid.
func (u User) Validate() error {
if u.Email == "" || u.Password == "" {
2018-05-10 23:53:25 +02:00
return ErrMalformedEntity
}
if !isEmail(u.Email) {
2018-05-11 01:00:10 +02:00
return ErrMalformedEntity
2018-05-10 23:53:25 +02:00
}
2018-05-11 01:00:10 +02:00
return nil
2018-05-10 23:53:25 +02:00
}
2018-05-11 01:00:10 +02:00
// UserRepository specifies an account persistence API.
type UserRepository interface {
// Save persists the user account. A non-nil error is returned to indicate
// operation failure.
2019-07-18 15:01:09 +02:00
Save(context.Context, User) error
2018-05-11 01:00:10 +02:00
// RetrieveByID retrieves user by its unique identifier (i.e. email).
2019-07-18 15:01:09 +02:00
RetrieveByID(context.Context, string) (User, error)
2018-05-10 23:53:25 +02:00
}
func isEmail(email string) bool {
if len(email) < 6 || len(email) > 254 {
return false
}
at := strings.LastIndex(email, "@")
if at <= 0 || at > len(email)-3 {
return false
}
user := email[:at]
host := email[at+1:]
if len(user) > 64 {
return false
}
if userDotRegexp.MatchString(user) || !userRegexp.MatchString(user) || !hostRegexp.MatchString(host) {
return false
}
return true
}