示例#1
0
// Establish connection to MongoDB and write feedback to collection
func WriteFeedback(name string, email string, text string) int {
	// We like only correct e-mails
	if !govalidator.IsEmail(email) {
		fmt.Printf("'%v' is not an email!\n", email)
		return NOT_AN_EMAIL
	}
	// Length of name can't be less than four letters and more than thirty two letters
	if !govalidator.IsByteLength(name, 4, 32) {
		fmt.Printf("Name '%v' has invalid length!\n", name)
		return INVALID_NAME
	}
	// Length of text should be between 16 and 1024 letters
	if !govalidator.IsByteLength(text, 16, 1024) {
		fmt.Printf("Feedback '%v' has invalid length!\n", text)
		return INVALID_NAME
	}
	url := os.Getenv("DATABASE")
	fmt.Printf("DB_URL is %v\n", url)
	sess, err := mgo.Dial(url)
	if err != nil {
		fmt.Printf("Can't connect to mongo, go error %v\n", err)
		return DB_UNAVAILABLE
	}
	defer sess.Close()
	sess.SetMode(mgo.Monotonic, true)

	c := sess.DB("asaskevich").C("feedback")
	err = c.Insert(&Feedback{name, email, text})
	if err != nil {
		fmt.Printf("Can't write to mongo, go error %v\n", err)
		return CANT_WRITE_TO_DB
	}
	return OK
}
示例#2
0
func AddressIsValidFullFuzzy(address string, excludeExampleOrTest bool, excludeNumericTestAddress bool) bool {
	address = strings.Trim(address, " ")
	if len(address) < 6 { // [email protected]
		return false
	}
	address = strings.ToLower(address)
	valid, _, hostname := AddressIsValidFull(address)
	if !valid {
		return false
	}
	valid = govalidator.IsEmail(address)
	if !valid {
		return false
	}
	valid = HostnameIsValid(hostname)
	if !valid {
		return false
	}
	if excludeExampleOrTest {
		test := DomainIsExampleOrTest(address)
		if test {
			return false
		}
	}
	if excludeNumericTestAddress {
		rsEmailFullNumeric := rxEmailFullNumeric.FindString(address)
		if len(rsEmailFullNumeric) > 0 {
			return false
		}
	}
	return true
}
示例#3
0
func verifyFormat(val string, format string) error {
	switch format {
	case "date-time":
		_, err := time.Parse(time.RFC3339, val)
		return err
	case "email":
		if !govalidator.IsEmail(val) {
			return fmt.Errorf("%q is not a valid email", val)
		}
	case "hostname":
		if !hostnameRe.MatchString(val) || len(val) > 255 {
			return fmt.Errorf("%q is not a valid hostname", val)
		}
	case "ipv4":
		if !govalidator.IsIPv4(val) {
			return fmt.Errorf("%q is not a valid IPv4 address", val)
		}
	case "ipv6":
		if !govalidator.IsIPv6(val) {
			return fmt.Errorf("%q is not a valid IPv6 address", val)
		}
	case "uri":
		u, err := url.Parse(val)
		if err != nil {
			return err
		}
		// XXX: \noideadog{this makes all the tests pass, not sure how it really should be validated}
		if u.Host == "" {
			return fmt.Errorf("%q is not absolute", val)
		}
	}
	return nil
}
示例#4
0
//edit email
func EditEmail(c web.C, w http.ResponseWriter, r *http.Request) {

	var userId int

	if CheckToken(r.FormValue("token"), w) == false {
		return
	}
	//Get user_id by token render json error if crash ?
	if userId = GetUserIdWithToken(r.FormValue("token"), w); userId == -1 {
		return
	}

	var email = r.FormValue("email")

	//delete all space in var email
	email = strings.Replace(email, " ", "", -1)

	//check if email's syntax is correct
	if govalidator.IsEmail(email) == false {
		RenderJSON(w, RenderStructError("email", "your email haven't a good syntax"), http.StatusBadRequest)
		return
	}

	//check if email is already used
	if IsEmailExist(email) == true {
		RenderJSON(w, RenderStructError("email", "email is already used"), http.StatusBadRequest)
		return
	}

	//query update email
	_, err := gest.Db.Exec("UPDATE account SET email=$1 WHERE id=$2", email, userId)
	LogFatalError(err)
	RenderJSON(w, RenderStructOk(), http.StatusOK)
}
示例#5
0
// Validate ...
// TODO: unify somehow, to have centralized place where email (or any other field) is validated
func (prr *PasswordRecoveryRequest) Validate(builder *lib.ValidationErrorBuilder) {
	if !validator.IsByteLength(prr.Email, 6, 45) {
		builder.Add("email", "validation_error.email_min_max_wrong")
	} else if !validator.IsEmail(prr.Email) {
		builder.Add("email", "Invalid email address.")
	}
}
示例#6
0
//EmailValidator for validation of email inputs
func EmailValidator(Error string) ItemValidator {
	return NewValidator(func(field *FormItem) bool {
		if !govalidator.IsEmail(field.Value) {
			return false
		}
		return true
	}, Error)
}
func ValidateFormatOfEmail(resource Resource, attribute string) {
	value := reflect.ValueOf(resource).Elem()

	value = reflect.Indirect(value).FieldByName(attribute)

	if govalidator.IsEmail(value.String()) == false {
		resource.Errors().Add(attribute, "is not email")
	}
}
示例#8
0
func (n *NewEmail) Decode() error {
	n.Email = strings.Trim(strings.ToLower(n.Email), " ")
	if n.Email == "" || !govalidator.IsEmail(n.Email) {
		return Errors{
			"email": "Valid email is required",
		}
	}
	return nil
}
示例#9
0
文件: chartfile.go 项目: gabrtv/helm
func validateChartMaintainer(cf *chart.Metadata) (lintError support.LintError) {
	for _, maintainer := range cf.Maintainers {
		if maintainer.Name == "" {
			lintError = fmt.Errorf("Chart.yaml: maintainer requires a name")
		} else if maintainer.Email != "" && !govalidator.IsEmail(maintainer.Email) {
			lintError = fmt.Errorf("Chart.yaml: maintainer invalid email")
		}
	}
	return
}
示例#10
0
文件: chartfile.go 项目: runseb/helm
func validateChartMaintainer(cf *chart.Metadata) error {
	for _, maintainer := range cf.Maintainers {
		if maintainer.Name == "" {
			return errors.New("each maintainer requires a name")
		} else if maintainer.Email != "" && !govalidator.IsEmail(maintainer.Email) {
			return fmt.Errorf("invalid email '%s' for maintainer '%s'", maintainer.Email, maintainer.Name)
		}
	}
	return nil
}
示例#11
0
// NewUserFunc creates the default parser of login HTTP request
func NewUserFunc(idName string) UserFunc {
	return func(r *http.Request, us store.Store) (ou OAuth2User, err error) {

		var c store.Conds

		id := r.Form.Get(idName)

		if id == "" {
			serr := store.Error(http.StatusBadRequest, "empty user identifier")
			err = serr
			return
		}

		// different condition based on the user_id field format
		if govalidator.IsEmail(id) {
			c = store.NewConds().Add("email", id)
		} else {
			c = store.NewConds().Add("username", id)
		}

		// get user from database
		u := us.AllocEntity()
		err = us.One(c, u)

		if err != nil {
			serr := store.ExpandError(err)
			if serr.Status != http.StatusNotFound {
				serr.TellServer("Error searching user %#v: %s", id, serr.ServerMsg)
				return
			}
			err = serr
			return
		}

		// if user does not exists
		if u == nil {
			serr := store.Error(http.StatusBadRequest, "Username or Password incorrect")
			serr.TellServer("Unknown user %#v attempt to login", id)
			err = serr
			return
		}

		// cast the user as OAuth2User
		// and do password check
		ou, ok := u.(OAuth2User)
		if !ok {
			serr := store.Error(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
			serr.TellServer("User cannot be cast as OAuth2User")
			err = serr
			return
		}

		return
	}
}
示例#12
0
// Valid validates email. If the email is temporary it returns false and an error explaining
// why it is not valid. For valid email it returns true, and the error is nil.
func Valid(email string) (bool, error) {
	if !govalidator.IsEmail(email) {
		return false, errors.New("Bad email address")
	}
	sep := strings.Split(email, "@")
	_, err := checkDisposable(sep[1])
	if err != nil {
		return true, nil
	}
	return false, errors.New("This is a temporary email")
}
示例#13
0
func (m *Order) validateContact() error {
	if m.Contact == "" {
		return nil
	}

	if govalidator.IsEmail(m.Contact) != true {
		return errors.InvalidType("contact", "body", "email", m.Contact)
	}

	return nil
}
示例#14
0
func (m *User) validateEmail() error {
	if m.Email == "" {
		return nil
	}

	if govalidator.IsEmail(m.Email) != true {
		return errors.InvalidType("email", "body", "email", m.Email)
	}

	return nil
}
示例#15
0
文件: config.go 项目: Rompei/vuls
func checkEmails(emails []string) (errs []error) {
	for _, addr := range emails {
		if len(addr) == 0 {
			return
		}
		if ok := valid.IsEmail(addr); !ok {
			errs = append(errs, fmt.Errorf("Invalid email address. email: %s", addr))
		}
	}
	return
}
示例#16
0
func (Lst_users *All_users) Add_new_user(new_user *User, Db *sql.DB, Pass []byte) (bool, error) {
	if len(new_user.Mail) > 0 {
		if valid.IsEmail(new_user.Mail) != true {
			return false, nil
		}
	}
	err := Db.QueryRow("SELECT  setsuserdata2($1, $2, $3, $4, $5, $6, $7, $8);", 1, "user_particulier", new_user.Coord.Lat, new_user.Coord.Lon, new_user.Stats.CreationDate, new_user.Log, new_user.Mail, Pass).Scan(&new_user.Id)
	if err != nil {
		Lst_users.Logger.Println("Add_new_user: ", err)
		return false, err
	}
	return true, nil
}
示例#17
0
文件: user.go 项目: quorumsco/users
func (u *User) Validate() map[string]string {
	var errs = make(map[string]string)

	switch {
	case u.Mail == nil:
		errs["mail"] = "is required"
	case u.Mail != nil && !govalidator.IsEmail(*u.Mail):
		errs["mail"] = "is not valid"
	case u.Password == nil:
		errs["password"] = "******"
	}

	return errs
}
示例#18
0
//for now just return submited params
func registerHandler(c *gin.Context) {
	username := c.PostForm("username")
	email := c.PostForm("email")

	//we are using external library to validate email and other things if needed
	if govalidator.IsEmail(email) {
		//c.String(200, "Username is: %s and e-mail %s", username, email)
		//or we can return JSON as well
		c.JSON(200, gin.H{"username": username, "email": email})
	} else {
		//email is not valid we can't register this user
		c.String(400, "We are sorry but email: %s is not valid e-mail adress", email)
	}
}
示例#19
0
func (user *User) Validate(repo UserRepository) error {
	if user.Email == "" {
		return errors.New("Cannot create User without email.")
	}

	if !govalidator.IsEmail(user.Email) {
		return UserInvalidEmail
	}

	u, _ := repo.FindByEmail(user.Email)
	if u != nil {
		return UserDuplicateEmail
	}

	return nil
}
示例#20
0
文件: user.go 项目: warreq/gohstd
// Validate returns an error if a User struct does not satisfy the following
// conditions:
//  * Username is 3 or more characters
//  * Username is composed solely of alphanumeric characters
//  * Email is a valid email address
//  * Password is 8 or more characters
func (u User) Validate() (err error) {
	if !valid.IsEmail(u.Email) {
		err = errors.New(fmt.Sprintf("'%s' is not a valid email address", u.Email))
	}
	if len(u.Username) < 3 {
		err = errors.New(fmt.Sprintf("'%s' is less than 3 characters", u.Username))
	}
	if len(u.Password) < 8 {
		err = errors.New("Password must be at least 8 characters long")
	}
	if !valid.IsAlphanumeric(u.Username) {
		err = errors.New(fmt.Sprintf("'%s' is less than 3 characters", u.Username))
	}

	return err
}
示例#21
0
func (this *LoginValidator) validateRequest(loginRequest *LoginRequest) (isValid bool, errorMessages []string) {
	if loginRequest.UserId == "" {
		errorMessages = append(errorMessages, this.ResourceProvider.GetString(configuration.R_LOGIN_USER_ID_REQUIRED))
	} else if !valid.IsEmail(loginRequest.UserId) {
		errorMessages = append(errorMessages, this.ResourceProvider.GetString(configuration.R_LOGIN_USER_ID_INVALID_EMAIL))
	}

	if loginRequest.Password == "" {
		errorMessages = append(errorMessages, this.ResourceProvider.GetString(configuration.R_LOGIN_PASSWORD_REQUIRED))
	} else if !valid.IsPrintableASCII(loginRequest.Password) {
		errorMessages = append(errorMessages, this.ResourceProvider.GetString(configuration.R_LOGIN_PASSWORD_INVALID))
	}

	isValid = len(errorMessages) == 0
	return isValid, errorMessages
}
示例#22
0
func RegisterHandler(context *RegistrationContext, w http.ResponseWriter, r *http.Request) error {
	if r.Method != "POST" {
		w.Header().Set("Allow", "POST")
		w.WriteHeader(http.StatusMethodNotAllowed)
		json.NewEncoder(w).Encode(RegistrationError{"Method not allowed! Use POST"})
		return nil
	}

	email, err := getEmailFromRequest(w, r)
	if err != nil {
		return err
	}

	if email != "" {

		// validate email first
		if !govalidator.IsEmail(email) {
			w.WriteHeader(http.StatusBadRequest)
			json.NewEncoder(w).Encode(RegistrationError{"Email not valid!"})
			return nil
		}

		registerTime := time.Now()
		err := context.RegisteredUserRepository.AddRegisteredUser(RegisteredUser{email, registerTime})
		if err != nil {
			if mgo.IsDup(err) {
				w.WriteHeader(http.StatusConflict)
				json.NewEncoder(w).Encode(RegistrationError{"Email exists!"})
				return nil
			}

			return err
		}

		w.WriteHeader(http.StatusCreated)
		json.NewEncoder(w).Encode(RegisteredUser{email, registerTime})
		context.Mailer.SendWelcomeMessage(email)
		return nil
	}

	w.WriteHeader(http.StatusBadRequest)
	json.NewEncoder(w).Encode(RegistrationError{"Email missing!"})
	return nil
}
示例#23
0
// Validate ...
func (rr *RegistrationRequest) Validate(builder *lib.ValidationErrorBuilder) {
	if !validator.IsByteLength(rr.Email, 6, 45) {
		builder.Add("email", "validation_error.email_min_max_wrong")
	} else if !validator.IsEmail(rr.Email) {
		builder.Add("email", "Invalid email address.")
	}

	if !validator.IsByteLength(rr.Password, 6, 45) {
		builder.Add("password", "validation_error.password_min_max_wrong")
	}

	if !validator.IsByteLength(rr.FirstName, 1, 45) {
		builder.Add("firstName", "validation_error.firstname_max_len_wrong")
	}

	if !validator.IsByteLength(rr.LastName, 1, 45) {
		builder.Add("lastName", "validation_error.lastname_max_len_wrong")
	}
}
示例#24
0
func ConfigureLdapClient(conf LdapConfig) (*mozldap.Client, error) {
	// check if ldap email was entered
	if govalidator.IsEmail(conf.Username) {
		conf.Username = "******" + conf.Username + ",o=com,dc=" + conf.Dc
	}

	// instantiate an ldap client
	ldapClient, err := mozldap.NewTLSClient(
		conf.Uri,
		conf.Username,
		conf.Password,
		conf.ClientCertFile,
		conf.ClientKeyFile,
		conf.CaCertFile,
		&tls.Config{
			InsecureSkipVerify: conf.Insecure,
		},
	)

	return &ldapClient, err
}
示例#25
0
// CreateUser create a new user. Checks for duplicate users and password-length requirement
func CreateUser(handle tools.Handle, db *mgo.DbQueue) (interface{}, error) {
	var user models.User

	user.Enable = true
	user.Domains = nil
	user.Variables = nil
	err := rest.Parse(handle.R, &user)
	if err != nil {
		return nil, tools.NewError(err, 400, "bad request: couldn't parse body")
	}

	if user.Username == "" {
		return nil, tools.NewError(nil, 400, "bad request: username is missing")
	}
	if user.Password == "" {
		return nil, tools.NewError(nil, 400, "bad request: password is missing")
	}
	if len(user.Password) < handle.C.PasswordMinLength {
		return nil, tools.NewError(nil, 400, "bad request: password is too short")
	}
	if user.Domains == nil || len(user.Domains) == 0 {
		return nil, tools.NewError(nil, 400, "bad request: domains is missing")
	}
	if user.Variables == nil {
		user.Variables = make(map[string]interface{})
	}
	if govalidator.IsEmail(user.Username) == false {
		return nil, tools.NewError(nil, 400, "bad request: username must be a valid email")
	}

	user.Username, err = govalidator.NormalizeEmail(user.Username)
	if err != nil {
		return nil, tools.NewError(nil, 400, "bad request: username must be a valid email")
	}
	uid, err := user.Create(db)
	return CreateResponse{
		Status: "ok",
		UserID: uid.Hex(),
	}, err
}
示例#26
0
func (s *Signup) Decode() error {

	s.Name = strings.Trim(s.Name, " ")
	s.Email = strings.ToLower(strings.Trim(s.Email, " "))

	errors := make(Errors)

	if len(s.Name) < minNameLength {
		errors["name"] = fmt.Sprintf("Your name must be at least %d characters long", minNameLength)
	}
	if !govalidator.IsEmail(s.Email) {
		errors["email"] = "Email address is required"
	}
	if len(s.Password) < minPasswordLength {
		errors["password"] = fmt.Sprintf("Password must be at least %d characters long", minPasswordLength)
	}
	if len(errors) > 0 {
		return errors
	}

	return nil
}
示例#27
0
文件: user.go 项目: nhocconan/lobster
func UserCreate(db *Database, username string, password string, email string) (int, error) {
	if email != "" && !govalidator.IsEmail(email) {
		return 0, L.Error("invalid_email")
	}

	if len(username) < MIN_USERNAME_LENGTH || len(username) > MAX_USERNAME_LENGTH {
		return 0, L.Errorf("username_length", MIN_USERNAME_LENGTH, MAX_USERNAME_LENGTH)
	}

	if !isPrintable(username) {
		return 0, L.Error("invalid_username_format")
	}

	if len(password) < MIN_PASSWORD_LENGTH || len(password) > MAX_PASSWORD_LENGTH {
		return 0, L.Errorf("password_length", MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH)
	}

	// ensure username not taken already
	var userCount int
	db.QueryRow("SELECT COUNT(*) FROM users WHERE username = ?", username).Scan(&userCount)
	if userCount > 0 {
		return 0, L.Error("username_in_use")
	}

	// ensure email not taken already
	if email != "" {
		db.QueryRow("SELECT COUNT(*) FROM users WHERE email = ?", email).Scan(&userCount)
		if userCount > 0 {
			return 0, L.Error("email_in_use")
		}
	}

	// generate salt and hash password
	result := db.Exec("INSERT INTO users (username, password, email) VALUES (?, ?, ?)", username, authMakePassword(password), email)
	userId, _ := result.LastInsertId()
	return int(userId), nil
}
示例#28
0
func (email Email) Validate() error {
	if !govalidator.IsEmail(email.String()) {
		return ErrInvalidMail
	}
	return nil
}
示例#29
0
func (i IsEmailChecker) IsFormat(data string) bool {
	return govalidator.IsEmail(data)
}
示例#30
0
func (s *service) extendedIsEmail(str string) bool {
	return gov.IsEmail(str) && len(strings.TrimSpace(str)) >= 3
}