Beispiel #1
0
// Send an email using the given host and SMTP auth (optional), returns any error thrown by smtp.SendMail
// This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message
func (e *Email) Send(addr string, a smtp.Auth) error {
	// Merge the To, Cc, and Bcc fields
	to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
	to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
	for i := 0; i < len(to); i++ {
		addr, err := mail.ParseAddress(to[i])
		if err != nil {
			return err
		}
		to[i] = addr.Address
	}
	// Check to make sure there is at least one recipient and one "From" address
	if e.From == "" || len(to) == 0 {
		return errors.New("Must specify at least one From address and one To address")
	}
	from, err := mail.ParseAddress(e.From)
	if err != nil {
		return err
	}
	raw, err := e.Bytes()
	if err != nil {
		return err
	}
	return smtp.SendMail(addr, a, from.Address, to, raw)
}
Beispiel #2
0
func sendMail(from, to, subject, htmlContent string, mailer *mail.Mailer,
	debug bool, success chan *email.Email, fail chan error) {

	parsedSender, err := stdMail.ParseAddress(from)
	if err != nil {
		fail <- err
		return
	}

	parsedTo, err := stdMail.ParseAddress(to)
	if err != nil {
		fail <- err
		return
	}

	message, err := mail.NewMessage(
		parsedSender,
		parsedTo,
		subject,
		htmlContent,
	)
	if err != nil {
		fail <- err
		return
	}

	if err := mailer.Send(message); err != nil {
		fail <- err
		return
	}

	success <- message
}
Beispiel #3
0
func testValidate(t *testing.T, s *Service) {
	// Valid
	userEmail, pwd, err := getUserCreds(t)
	if e(t, err) {
		return
	}
	eml, err := mail.ParseAddress(userEmail)
	if e(t, err) {
		return
	}
	valid, err := s.Validate(*eml, pwd)
	if e(t, err) {
		return
	}
	if !valid {
		t.Errorf("expected Validate to return true but returned %t", valid)
	}
	// Invalid
	eml, err = mail.ParseAddress("*****@*****.**")
	if e(t, err) {
		return
	}
	valid, err = s.Validate(*eml, "invalidpassword")
	if e(t, err) {
		return
	}
	if valid {
		t.Errorf("expected Validate to return false but returned %t", valid)
	}
}
Beispiel #4
0
func (s *EmailServer) dispatchMessage(m *Message) error {
	var e email.Email
	//err := ds.LoadStruct(&e, []byte(m.Data))
	err := ds.Load(&e, []byte(m.Data))
	if err != nil {
		return err
	}

	// Merge the To, Cc, and Bcc fields
	to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
	to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
	for i := 0; i < len(to); i++ {
		addr, err := mail.ParseAddress(to[i])
		if err != nil {
			return err
		}
		to[i] = addr.Address
	}

	// Check to make sure there is at least one recipient and one "From" address
	if e.From == "" || len(to) == 0 {
		return errors.New("Must specify at least one From address and one To address")
	}
	from, err := mail.ParseAddress(e.From)
	if err != nil {
		return err
	}
	raw, err := e.Bytes()
	if err != nil {
		return err
	}

	return smtp.SendMail(s.address, s.auth, from.Address, to, raw)
}
Beispiel #5
0
func testAccountAvailabilityCheck(t *testing.T, s *Service) {
	// Available
	eml, err := mail.ParseAddress("*****@*****.**")
	if e(t, err) {
		return
	}
	avail, err := s.AccountAvailabilityCheck(*eml)
	if e(t, err) {
		return
	}
	if !avail {
		t.Errorf("expected AccountAvailabilityCheck to return true but returned %t", avail)
	}
	// UnAvailable
	userEmail, _, err := getUserCreds(t)
	if e(t, err) {
		return
	}
	eml, err = mail.ParseAddress(userEmail)
	if e(t, err) {
		return
	}
	avail, err = s.AccountAvailabilityCheck(*eml)
	if e(t, err) {
		return
	}
	if avail {
		t.Errorf("expected AccountAvailabilityCheck to return false but returned %t", avail)
		return
	}
}
Beispiel #6
0
// NewMailAuthHook creates a hook to be added to an instance of logger.
func NewMailAuthHook(appname string, host string, port int, from string, to string, username string, password string) (*MailAuthHook, error) {
	// Check if server listens on that port.
	conn, err := net.DialTimeout("tcp", host+":"+strconv.Itoa(port), 3*time.Second)
	if err != nil {
		return nil, err
	} else {
		defer conn.Close()
	}

	// Validate sender and recipient
	sender, err := mail.ParseAddress(from)
	if err != nil {
		return nil, err
	}
	receiver, err := mail.ParseAddress(to)
	if err != nil {
		return nil, err
	}

	return &MailAuthHook{
		AppName:  appname,
		Host:     host,
		Port:     port,
		From:     sender,
		To:       receiver,
		Username: username,
		Password: password}, nil
}
Beispiel #7
0
func sendMail(recipient Recipient, emailField string, mailer *mail.Mailer,
	success chan Recipient, fail chan error) {

	parsedSender, err := stdMail.ParseAddress(sender)
	if err != nil {
		fail <- err
		return
	}

	parsedTo, err := stdMail.ParseAddress(recipient[emailField])
	if err != nil {
		fail <- err
		return
	}

	message, err := mail.NewMessage(
		parsedSender,
		parsedTo,
		subject,
		textTemplatePath,
		htmlTemplatePath,
		recipient,
	)
	if err != nil {
		fail <- err
		return
	}

	if err := mailer.Send(message); err != nil {
		fail <- err
		return
	}

	success <- recipient
}
Beispiel #8
0
// NewMailHook creates a hook to be added to an instance of logger.
func NewMailHook(appname string, host string, port int, from string, to string) (*MailHook, error) {
	// Connect to the remote SMTP server.
	c, err := smtp.Dial(host + ":" + strconv.Itoa(port))
	if err != nil {
		return nil, err
	}

	// Validate sender and recipient
	sender, err := mail.ParseAddress(from)
	if err != nil {
		return nil, err
	}
	recipient, err := mail.ParseAddress(to)
	if err != nil {
		return nil, err
	}

	// Set the sender and recipient.
	if err := c.Mail(sender.Address); err != nil {
		return nil, err
	}
	if err := c.Rcpt(recipient.Address); err != nil {
		return nil, err
	}

	return &MailHook{
		AppName: appname,
		c:       c,
	}, nil

}
func sendEmail(headers map[string]string, body string, address string, gConfig map[string]string) {

	host := gConfig["REMOTE_SMTP_HOST"]
	port := gConfig["REMOTE_SMTP_PORT"]
	user := gConfig["REMOTE_SMTP_USER"]
	password := gConfig["REMOTE_SMTP_PASS"]

	m := email.NewMessage(headers["Subject"], body)

	fromAddress := "Unknown"
	fromHeader, ok := headers["From"]
	if ok {
		from, _ := mail.ParseAddress(fromHeader)
		fromAddress = from.Address
	}

	to, _ := mail.ParseAddress(address)
	toAddress := to.Address

	m.From = fromAddress
	m.To = []string{toAddress}

	if gConfig["PGP_ATTACH_BODY"] == "Y" {
		m.AttachData("message.asc", []byte(body))
	}

	err := email.Send(host+":"+port, smtp.PlainAuth("", user, password, host), m)
	logging.CheckFatal(err)
}
Beispiel #10
0
func (p *Post) Validate() error {
	if p.Replyto != "" {
		t := ""
		if !strings.Contains(p.Replyto, "<") || !strings.Contains(p.Replyto, ">") {
			t = p.Replyto + " <" + p.Replyto + ">"
		}
		a, err := mail.ParseAddress(t)
		if err != nil {
			return err
		}
		p.Replyto = a.Address
	}
	if len(p.CC) > 0 {
		for k, v := range p.CC {
			t := ""
			if !strings.Contains(v, "<") || !strings.Contains(v, ">") {
				t = v + " <" + v + ">"
			}
			a, err := mail.ParseAddress(t)
			if err != nil {
				return err
			}
			p.CC[k] = a.Address
		}
	}

	return nil
}
Beispiel #11
0
// NewSESHook creates a hook to be added to an instance of logger.
func NewSESHook(appName string, level log.Level) (*SESHook, error) {
	// Validate sender and recipient
	sender, err := mail.ParseAddress(getFrom())
	if err != nil {
		return nil, err
	}
	receiver, err := mail.ParseAddress(getTo())
	if err != nil {
		return nil, err
	}

	// Get SES specific username and password
	username := getUsername()
	if len(username) == 0 {
		return nil, errors.New("SES_ACCESS_KEY_ID not set.")
	}
	password := getPassword()
	if len(password) == 0 {
		return nil, errors.New("SES_SECRET_ACCESS_KEY not set.")
	}

	return &SESHook{
		AppName: appName,
		From:    sender,
		To:      receiver,
		Auth:    smtp.PlainAuth("", username, password, SESServer),
		Level:   level,
	}, nil
}
Beispiel #12
0
func (s *SMTPDeliverer) Deliver(ctx scope.Context, ref *EmailRef) error {
	// Connect and authenticate to SMTP server.
	c, err := smtp.Dial(s.addr)
	if err != nil {
		return fmt.Errorf("%s: dial error: %s", s, err)
	}
	defer c.Quit()

	if err := c.Hello(s.localName); err != nil {
		return fmt.Errorf("%s: ehlo error: %s", s, err)
	}

	if s.tlsConfig != nil {
		if err := c.StartTLS(s.tlsConfig); err != nil {
			return fmt.Errorf("%s: starttls error: %s", s, err)
		}
	}

	if s.auth != nil {
		if err := c.Auth(s.auth); err != nil {
			return fmt.Errorf("%s: auth error: %s", s, err)
		}
	}

	// Send email.
	if ref.SendFrom == "" {
		ref.SendFrom = "noreply@" + s.localName
	}
	sendFrom, err := mail.ParseAddress(ref.SendFrom)
	if err != nil {
		return fmt.Errorf("%s: from address error: %s", s, err)
	}
	if err := c.Mail(sendFrom.Address); err != nil {
		return fmt.Errorf("%s: mail error: %s", s, err)
	}

	sendTo, err := mail.ParseAddress(ref.SendTo)
	if err != nil {
		return fmt.Errorf("%s: to address error: %s", s, err)
	}
	if err := c.Rcpt(sendTo.Address); err != nil {
		return fmt.Errorf("%s: rcpt error: %s", s, err)
	}

	wc, err := c.Data()
	if err != nil {
		return fmt.Errorf("%s: data error: %s", s, err)
	}

	if _, err := wc.Write(ref.Message); err != nil {
		return fmt.Errorf("%s: write error: %s", s, err)
	}
	if err := wc.Close(); err != nil {
		return fmt.Errorf("%s: close error: %s", s, err)
	}

	ref.Delivered = time.Now()
	return nil
}
Beispiel #13
0
// Dequeue returns jobs from the queue. It maps hosts to the packages
// that need to be delivered to them. If anything goes wrong, Dequeue
// returns an error. Dequeue will never return more hosts than the
// current MaxHostsPerDequeue value.
func (mb mailBox) Dequeue() (map[string]Package, error) {
	rows, err := mb.dequeueStmt.Query(MaxHostsPerDequeue)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	jobs := make(map[string]Package)
	cache := make(map[uint64]*Message)
	for rows.Next() {
		var row struct {
			User, Host  string
			Date        pq.NullTime
			Attempts    int
			MID         uint64
			MRaw, MFrom string
		}
		err := rows.Scan(&row.Host, &row.MID, &row.User, &row.Date,
			&row.Attempts, &row.MRaw, &row.MFrom)
		if err != nil {
			return jobs, err
		}
		if jobs[row.Host] == nil {
			jobs[row.Host] = make(Package)
		}
		msg, ok := cache[row.MID]
		if !ok {
			msg = &Message{
				ID:  row.MID,
				Raw: row.MRaw,
			}
			addr, err := mail.ParseAddress(row.MFrom)
			if err != nil {
				return nil, err
			}
			msg.SetFrom(addr)
			cache[row.MID] = msg
		}
		if jobs[row.Host][msg] == nil {
			jobs[row.Host][msg] = make([]*mail.Address, 0, 1)
		}
		dest, err := mail.ParseAddress(row.User + "@" + row.Host)
		if err != nil {
			return nil, err
		}
		jobs[row.Host][msg] = append(jobs[row.Host][msg], dest)
	}
	return jobs, nil
}
Beispiel #14
0
func insertTargetIntoGroup(t Target, gid int64) error {
	if _, err = mail.ParseAddress(t.Email); err != nil {
		Logger.Printf("Invalid email %s\n", t.Email)
		return err
	}
	trans := db.Begin()
	trans.Where(t).FirstOrCreate(&t)
	if err != nil {
		Logger.Printf("Error adding target: %s\n", t.Email)
		return err
	}
	err = trans.Where("group_id=? and target_id=?", gid, t.Id).Find(&GroupTarget{}).Error
	if err == gorm.RecordNotFound {
		err = trans.Save(&GroupTarget{GroupId: gid, TargetId: t.Id}).Error
		if err != nil {
			Logger.Println(err)
			return err
		}
	}
	if err != nil {
		Logger.Printf("Error adding many-many mapping for %s\n", t.Email)
		return err
	}
	err = trans.Commit().Error
	if err != nil {
		Logger.Printf("Error committing db changes\n")
		return err
	}
	return nil
}
Beispiel #15
0
// LoadConfig will try to search around for the corresponding config file.
// It will search /tmp/fileName then attempt ./config/fileName,
// then ../config/fileName and last it will look at fileName
func LoadConfig(fileName string) {

	fileName = findConfigFile(fileName)
	l4g.Info("Loading config file at " + fileName)

	file, err := os.Open(fileName)
	if err != nil {
		panic("Error opening config file=" + fileName + ", err=" + err.Error())
	}

	decoder := json.NewDecoder(file)
	config := Config{}
	err = decoder.Decode(&config)
	if err != nil {
		panic("Error decoding configuration " + err.Error())
	}

	// Check for a valid email for feedback, if not then do feedback@domain
	if _, err := mail.ParseAddress(config.EmailSettings.FeedbackEmail); err != nil {
		config.EmailSettings.FeedbackEmail = "feedback@localhost"
		l4g.Error("Misconfigured feedback email setting: %s", config.EmailSettings.FeedbackEmail)
	}

	configureLog(config.LogSettings)

	Cfg = &config
	SanitizeOptions = getSanitizeOptions()

	// Validates our mail settings
	if err := CheckMailSettings(); err != nil {
		l4g.Error("Email settings are not valid err=%v", err)
	}
}
Beispiel #16
0
func (e *Email) From() (*EmailAddr, error) {
	mailAddr, err := mail.ParseAddress(e.msg.Header.Get("From"))
	if err != nil {
		return nil, err
	}
	return NewEmailAddr(mailAddr.Address), nil
}
Beispiel #17
0
// SetMandrill sets the Mandrill API for sending emails. This function is not
// recursive and returns nil. @todo
func SetMandrill(opts ...MandrillOptions) DaemonOption {
	return func(da *Daemon) DaemonOption {
		// this whole func is just a quick write down. no idea if it's working
		// and refactor ... 8-)
		apiKey := da.Config.GetString(config.ScopeStore(da.ScopeID), config.Path(PathSmtpMandrillAPIKey))

		if apiKey == "" {
			da.lastErrs = append(da.lastErrs, errors.New("Mandrill API Key is empty."))
			return nil
		}

		md, err := gochimp.NewMandrill(apiKey)
		if err != nil {
			da.lastErrs = append(da.lastErrs, err)
			return nil
		}
		for _, o := range opts {
			o(md)
		}

		da.sendFunc = func(from string, to []string, msg io.WriterTo) error {

			// @todo figure out if "to" contains To, CC and BCC addresses.

			addr, err := mail.ParseAddress(from)
			if err != nil {
				return log.Error("mail.daemon.Mandrill.ParseAddress", "err", err, "from", from, "to", to)
			}

			r := gochimp.Recipient{
				Name:  addr.Name,
				Email: addr.Address,
			}

			var buf bytes.Buffer
			if _, err := msg.WriteTo(&buf); err != nil {
				return log.Error("mail.daemon.Mandrill.MessageWriteTo", "err", err, "from", from, "to", to, "msg", buf.String())
			}

			resp, err := md.MessageSendRaw(buf.String(), to, r, false)
			if err != nil {
				return log.Error("mail.daemon.Mandrill.MessageSendRaw", "err", err, "from", from, "to", to, "msg", buf.String())
			}
			if log.IsDebug() {
				log.Debug("mail.daemon.Mandrill.MessageSendRaw", "resp", resp, "from", from, "to", to, "msg", buf.String())
			}
			// The last arg in MessageSendRaw means async in the Mandrill API:
			// Async: enable a background sending mode that is optimized for bulk sending.
			// In async mode, messages/send will immediately return a status of "queued"
			// for every recipient. To handle rejections when sending in async mode, set
			// up a webhook for the 'reject' event. Defaults to false for messages with
			// no more than 10 recipients; messages with more than 10 recipients are
			// always sent asynchronously, regardless of the value of async.
			return nil
		}
		da.dialer = nil

		return nil
	}
}
Beispiel #18
0
// RFC 2821 4.1.1.3 RECIPIENT (RCPT)
func cmdRCPT(ctx *transaction, param string) error {
	switch {
	case ctx.Mode == stateHELO:
		return ctx.notify(reply{503, "5.5.1 Say HELO/EHLO first."})
	case ctx.Mode == stateMAIL:
		return ctx.notify(reply{503, "5.5.1 Error: need MAIL command"})
	case !strings.HasPrefix(strings.ToUpper(param), "TO:"):
		return ctx.notify(reply{501, "5.5.4 Syntax: RCPT TO:<address>"})
	}
	addr, err := mail.ParseAddress(param[len("TO:"):])
	if err != nil {
		return ctx.notify(reply{501, "5.1.7 Bad recipient address syntax"})
	}

	switch ctx.host.query(addr) {
	case mailbox.QueryNotFound:
		return ctx.notify(reply{550, "5.1.1 No such user here."})
	case mailbox.QueryNotLocal:
		if flags := ctx.host.settings(); !flags.Has("relay") {
			return ctx.notify(reply{550, "5.1.1 No such user here."})
		}
		ctx.Message.AddOutbound(addr)
		ctx.Mode = stateDATA

		return ctx.notify(reply{251, "User not local; will forward to <forward-path>"})
	case mailbox.QuerySuccess:
		ctx.Message.AddInbound(addr)
		ctx.Mode = stateDATA
		return ctx.notify(reply{250, "2.1.5 Ok"})
	}
	return ctx.notify(replyErrorProcessing)
}
Beispiel #19
0
func SMSHandler(w http.ResponseWriter, r *http.Request) {
	sms := r.URL.Query().Get("Body")
	sms = strings.Trim(sms, "8575-2838")
	if sms == "" {
		log.Println("Blank body.")
		SendSMS(w, r, "Please send a text with: \"Name\" \"email@address\"")
		return
	}
	info := strings.Fields(sms)
	name := strings.Join(info[:len(info)-1], " ")
	email := info[len(info)-1]
	name = strings.Trim(name, "\"")
	if name == "" {
		log.Println("Blank name.")
		SendSMS(w, r, "Please send a text with: \"Name\" \"email@address\"")
		return
	}
	email = strings.Trim(email, "\"")
	address := fmt.Sprintf("%s <%s>", name, email)
	_, err := mail.ParseAddress(address)
	if err != nil {
		SendSMS(w, r, "Please try again with a valid email address.")
		return
	}
	signup := Signup{Name: name, Email: email, Raw: sms, Timestamp: time.Now()}
	log.Println(signup)
	c := mgoSession.DB("sms_signup").C("signups")
	err = c.Insert(signup)
	if err != nil {
		log.Println(err.Error())
	}
	SendSMS(w, r, fmt.Sprintf("Thanks for signing up, %s!", info[0]))
}
Beispiel #20
0
// parseAddress parses a single RFC 5322 address and returns the
// e-mail address portion.
// e.g. "Barry Gibbs <*****@*****.**>" would return "*****@*****.**".
func parseAddress(address string) (string, error) {
	a, err := mail.ParseAddress(address)
	if err != nil {
		return "", err
	}
	return a.Address, err
}
Beispiel #21
0
func getEmail(interactor interaction.Interactor) (string, error) {
	for {
		res, err := interactor.Prompt(&interaction.Challenge{
			Title:        "E. Mail Address Required",
			ResponseType: interaction.RTLineString,
			Prompt:       "E. mail address: ",
			Body:         `Please enter an e. mail address where you can be reached. Although entering an e. mail address is optional, it is highly recommended.`,
			UniqueID:     "acme-enter-email",
		})
		if err != nil {
			return "", err
		}

		if res.Value == "" {
			return "", nil
		}

		if res.Cancelled {
			return "-", nil
		}

		addr, err := mail.ParseAddress(res.Value)
		if err != nil {
			continue
		}

		return addr.Address, nil
	}
}
func validateEmail(address string, resolver bdns.DNSResolver) (prob *probs.ProblemDetails) {
	_, err := mail.ParseAddress(address)
	if err != nil {
		return &probs.ProblemDetails{
			Type:   probs.InvalidEmailProblem,
			Detail: unparseableEmailDetail,
		}
	}
	splitEmail := strings.SplitN(address, "@", -1)
	domain := strings.ToLower(splitEmail[len(splitEmail)-1])
	var resultMX []string
	var resultA []net.IP
	resultMX, err = resolver.LookupMX(domain)

	if err == nil && len(resultMX) == 0 {
		resultA, err = resolver.LookupHost(domain)
		if err == nil && len(resultA) == 0 {
			return &probs.ProblemDetails{
				Type:   probs.InvalidEmailProblem,
				Detail: emptyDNSResponseDetail,
			}
		}
	}
	if err != nil {
		dnsProblem := bdns.ProblemDetailsFromDNSError(err)
		return &probs.ProblemDetails{
			Type:   probs.InvalidEmailProblem,
			Detail: dnsProblem.Detail,
		}
	}

	return nil
}
Beispiel #23
0
// Send will send out the mail
func (e *Email) Send() error {
	if e.Auth == nil {
		e.Auth = smtp.PlainAuth(e.Identity, e.Username, e.Password, e.Host)
	}
	// Merge the To, Cc, and Bcc fields
	to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
	to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
	// Check to make sure there is at least one recipient and one "From" address
	if len(to) == 0 {
		return errors.New("Must specify at least one To address")
	}

	from, err := mail.ParseAddress(e.Username)
	if err != nil {
		return err
	}

	if len(e.From) == 0 {
		e.From = e.Username
	}
	// use mail's RFC 2047 to encode any string
	e.Subject = qEncode("utf-8", e.Subject)

	raw, err := e.Bytes()
	if err != nil {
		return err
	}
	return smtp.SendMail(e.Host+":"+strconv.Itoa(e.Port), e.Auth, from.Address, to, raw)
}
Beispiel #24
0
func (validator *Validator) Validate(user *User) (models.ValidationErrors, error) {

	errs := make(models.ValidationErrors)

	if user.Username == "" {
		errs.Add("Username", "Username must be provided.")
	}

	if user.HashedPassword == "" {
		errs.Add("Password", "Password must be provided.")
	}

	if user.Email == "" {
		errs.Add("Email", "Email must be provided.")
	} else if _, err := mail.ParseAddress(user.Email); err != nil {
		errs.Add("Email", "Invalid email address.")
	}

	savedUser, err := validator.Dao.GetByUsername(user.Username)
	if err != nil {
		return nil, err
	}

	if savedUser != nil && savedUser.ID != user.ID {
		errs.Add("Username", "A user with this username already exists.")
	}

	return errs, nil

}
Beispiel #25
0
func (r registrant) Validate() bool {
	if r.Name == "" {
		return false
	}
	names := strings.Split(r.Name, " ")
	if len(names) != 2 {
		return false
	}

	if r.Email == "" {
		return false
	}
	_, err := mail.ParseAddress(r.Email)
	if err != nil {
		return false
	}

	if r.Password == "" {
		return false
	}

	if r.Template != "M" && r.Template != "F" {
		return false
	}
	return true
}
Beispiel #26
0
// Function to mock a domain object
func newDomain() model.Domain {
	var domain model.Domain
	domain.FQDN = "rafael.net.br"

	domain.Nameservers = []model.Nameserver{
		{
			Host: "ns1.rafael.net.br",
			IPv4: net.ParseIP("127.0.0.1"),
			IPv6: net.ParseIP("::1"),
		},
		{
			Host: "ns2.rafael.net.br",
			IPv4: net.ParseIP("127.0.0.2"),
		},
	}

	domain.DSSet = []model.DS{
		{
			Keytag:    1234,
			Algorithm: model.DSAlgorithmRSASHA1,
			Digest:    "A790A11EA430A85DA77245F091891F73AA740483",
		},
	}

	owner, _ := mail.ParseAddress("*****@*****.**")
	domain.Owners = []model.Owner{
		{
			Email:    owner,
			Language: "pt-BR",
		},
	}

	return domain
}
Beispiel #27
0
// ContactInfo returns a *ContactInfo struct
func (user *User) ContactInfo() *ContactInfo {
	// Errors should never occurs, since values are stored in db after have been controlled
	yahoo, _ := mail.ParseAddress(user.Profile.Yahoo)
	website, _ := url.Parse(user.Profile.Website)
	github, _ := url.Parse(user.Profile.Github)
	facebook, _ := url.Parse(user.Profile.Facebook)
	twitter, _ := url.Parse(user.Profile.Twitter)

	// Set Address.Name field
	emailName := user.Surname + " " + user.Name
	// yahoo address can be nil
	if yahoo != nil {
		yahoo.Name = emailName
	}

	return &ContactInfo{
		Website:  website,
		GitHub:   github,
		Skype:    user.Profile.Skype,
		Jabber:   user.Profile.Jabber,
		Yahoo:    yahoo,
		Facebook: facebook,
		Twitter:  twitter,
		Steam:    user.Profile.Steam}
}
Beispiel #28
0
// Login initializes a User struct if login (id | email | username) and password are correct
func Login(login, password string) (*User, error) {
	var email *mail.Address
	var username string
	var id uint64
	var e error

	if email, e = mail.ParseAddress(login); e == nil { // is a mail
		if e = Db().Model(User{}).Select("username").Where(&User{Email: email.Address}).Scan(&username); e != nil {
			return nil, e
		}
	} else if id, e = strconv.ParseUint(login, 10, 64); e == nil { // if login the user ID
		if e = Db().Model(User{}).Select("username").Where(&User{Counter: id}).Scan(&username); e != nil {
			return nil, e
		}
	} else { // otherwise is the username
		username = login
	}

	var logged bool
	var counter uint64

	if e = Db().Model(User{}).Select("login(?, ?) AS logged, counter", username, password).Where("LOWER(username) = ?", username).Scan(&logged, &counter); e != nil {
		return nil, e
	}

	if !logged {
		return nil, errors.New("wrong username or password")
	}

	return NewUser(counter)
}
Beispiel #29
0
func TestRegisteredTypeParser(t *testing.T) {
	var d time.Duration
	RegisterTypeParser(reflect.TypeOf(d), func(blank bool, val string) (interface{}, error) {
		if blank {
			return nil, nil
		}
		return time.ParseDuration(val)
	})
	RegisterTypeParser(reflect.TypeOf(mail.Address{}), func(blank bool, val string) (interface{}, error) {
		if blank {
			return nil, nil
		}
		return mail.ParseAddress(val)
	})
	for _, tt := range []stTestCase{
		{"[reg-types-1]\nduration1=5m", &cRegTypes{Reg_Types_1: cRegTypes1{Duration1: 5 * time.Minute}}, true},
		{"[reg-types-1]\nduration1=1m30s", &cRegTypes{Reg_Types_1: cRegTypes1{Duration1: 90 * time.Second}}, true},
		{"[reg-types-1]\nduration1=1m1m", &cRegTypes{Reg_Types_1: cRegTypes1{Duration1: time.Duration(2 * time.Minute)}}, true},
		{"[reg-types-1]\nduration1=30", &cRegTypes{Reg_Types_1: cRegTypes1{Duration1: time.Duration(0)}}, false},
		{"[reg-types-1]\nduration1=m", &cRegTypes{Reg_Types_1: cRegTypes1{Duration1: time.Duration(0)}}, false},
		{"[reg-types-1]\nduration2=5m", &cRegTypes{Reg_Types_1: cRegTypes1{Duration2: []time.Duration{5 * time.Minute}}}, true},
		{"[reg-types-1]\[email protected]", &cRegTypes{Reg_Types_1: cRegTypes1{Email1: &mail.Address{"", "*****@*****.**"}}}, true},
		{"[reg-types-1]\nemail1=<*****@*****.**>", &cRegTypes{Reg_Types_1: cRegTypes1{Email1: &mail.Address{"", "*****@*****.**"}}}, true},
		{"[reg-types-1]\nemail1=\"foo bar\" <*****@*****.**>", &cRegTypes{Reg_Types_1: cRegTypes1{Email1: &mail.Address{"foo bar", "*****@*****.**"}}}, true},
		{"[reg-types-1]\nemail1=foo bar <*****@*****.**>", &cRegTypes{Reg_Types_1: cRegTypes1{Email1: &mail.Address{"foo bar", "*****@*****.**"}}}, true},
		{"[reg-types-1]\nemail1=foo bar  <*****@*****.**>", &cRegTypes{Reg_Types_1: cRegTypes1{Email1: &mail.Address{"foo bar", "*****@*****.**"}}}, true},
		{"[reg-types-1]\nemail1=<foo bar> <*****@*****.**>", &cRegTypes{Reg_Types_1: cRegTypes1{}}, false},
		{"[reg-types-1]\nemail1=<foo@[email protected]>", &cRegTypes{Reg_Types_1: cRegTypes1{}}, false},
		{"[reg-types-1]\[email protected]", &cRegTypes{Reg_Types_1: cRegTypes1{Email2: mail.Address{"", "*****@*****.**"}}}, true},
		{"[reg-types-1]\[email protected]", &cRegTypes{Reg_Types_1: cRegTypes1{Email3: []*mail.Address{&mail.Address{"", "*****@*****.**"}}}}, true},
		{"[reg-types-1]\[email protected]", &cRegTypes{Reg_Types_1: cRegTypes1{Email4: []mail.Address{mail.Address{"", "*****@*****.**"}}}}, true},
	} {
		assert(&tt, t)
	}
}
Beispiel #30
0
func getSingleAddress(raw string) *mail.Address {
	addr, err := mail.ParseAddress(raw)
	if err != nil {
		return nil
	}
	return addr
}