Example #1
0
func upload(c *echo.Context) error {
	req := c.Request()
	req.ParseMultipartForm(16 << 20) // Max memory 16 MiB

	// Read form fields
	name := c.Form("name")
	email := c.Form("email")

	// Read files
	files := req.MultipartForm.File["files"]
	for _, f := range files {
		// Source file
		src, err := f.Open()
		if err != nil {
			return err
		}
		defer src.Close()

		// Destination file
		dst, err := os.Create(f.Filename)
		if err != nil {
			return err
		}
		defer dst.Close()

		if _, err = io.Copy(dst, src); err != nil {
			return err
		}
	}
	return c.String(http.StatusOK, "Thank You! %s <%s>, %d files uploaded successfully.",
		name, email, len(files))
}
Example #2
0
/**
 * @api {put} /topics/{id} Updates a topic
 * @apiName UpdateTopic
 * @apiGroup Topics
 *
 * @apiParam {Number} id The id of the topic to update
 * @apiParam {String} [name] The new name of the topic
 */
func (tc *TopicsController) Update(c *echo.Context) error {
	resp := response.New(c)
	defer resp.Render()

	// Getting params
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		resp.SetResponse(http.StatusBadRequest, nil)
		return nil
	}

	// Loading the topic
	topic := new(models.Topic)
	err = topic.Load(id)
	if err != nil {
		resp.SetResponse(http.StatusNotFound, nil)
		return nil
	}

	name := c.Form("name")
	if name != "" {
		topic.Name = name
	}

	err = topic.Update()
	if err != nil {
		resp.SetResponse(http.StatusInternalServerError, nil)
		return nil
	}

	resp.SetResponse(http.StatusOK, topic)
	return nil
}
Example #3
0
func (h *handler) AddToFavPostHandler(c *echo.Context) error {
	s := session.Default(c)
	if s.Get("user") == "" {
		return c.JSON(http.StatusForbidden, "Access denied")
	}
	user, err := h.back.Model.User.GetByLogin(s.Get("user").(string))
	if (err != nil || user == &model.UserRow{}) {
		return c.JSON(http.StatusBadRequest, err.Error())
	}

	p, err := h.back.Model.Package.GetItem(c.Form("package"))
	if err != nil {
		log.Println(err)
		return c.JSON(http.StatusBadRequest, err.Error())
	}

	user.Packages = append(user.Packages, p.Id)
	_, err = h.back.Model.User.Upsert(user)
	if err != nil {
		log.Println(err)
		return c.JSON(http.StatusBadRequest, err.Error())
	}

	return c.JSON(http.StatusOK, nil)
}
Example #4
0
func (h *handler) RemoveFromFavPostHandler(c *echo.Context) error {
	s := c.Get("session").(session.Session)
	if s.Get("username") == "" {
		return c.JSON(http.StatusForbidden, "")
	}
	user := c.Get("user").(model.UserRow)

	p, err := h.back.Model.Package.GetItem(c.Form("package"))
	if err != nil {
		log.Println(err)
		return c.JSON(http.StatusBadRequest, err.Error())
	}

	var packages []bson.ObjectId
	for _, up := range user.Packages {
		if up != p.Id {
			packages = append(packages, up)
		}
	}
	user.Packages = packages
	_, err = h.back.Model.User.Upsert(&user)
	if err != nil {
		log.Println(err)
		return c.JSON(http.StatusBadRequest, err.Error())
	}

	return c.JSON(http.StatusOK, nil)
}
Example #5
0
func (h *handler) RemoveFromFavPostHandler(c *echo.Context) error {

	s := session.Default(c)
	if s.Get("user") == "" {
		return c.JSON(http.StatusForbidden, "Access denied")
	}
	user, err := h.back.Model.User.GetByLogin(s.Get("user").(string))
	if (err != nil || user == &model.UserRow{}) {
		return c.JSON(http.StatusBadRequest, err.Error())
	}
	p, err := h.back.Model.Package.GetItem(c.Form("package"))
	if err != nil {
		log.Println(err)
		return c.JSON(http.StatusBadRequest, err.Error())
	}

	var packages []bson.ObjectId
	for _, up := range user.Packages {
		if up != p.Id {
			packages = append(packages, up)
		}
	}
	user.Packages = packages
	_, err = h.back.Model.User.Upsert(user)
	if err != nil {
		log.Println(err)
		return c.JSON(http.StatusBadRequest, err.Error())
	}

	return c.JSON(http.StatusOK, nil)
}
Example #6
0
func UserRegister(c *echo.Context) error {
	r, err := uhander.Register(c.Form("u"), "")
	if err == nil {
		return c.String(http.StatusOK, r)
	} else {
		return c.String(http.StatusInternalServerError, err.Error())
	}
}
Example #7
0
func UserLogin(c *echo.Context) error {
	r, err := uhander.Login(c.Form("username"), c.Form("password"), "")

	if err == nil {
		return c.String(http.StatusOK, r)
	} else {
		return c.String(http.StatusInternalServerError, err.Error())
	}
}
Example #8
0
// DoContact adds a new contact message into database and sends an email
func DoContact(c *echo.Context) error {
	var contact models.Contact
	var err error

	contact.Name = c.Form("name")
	contact.Email = c.Form("email")
	contact.Company = c.Form("company")
	contact.Reason = c.Form("text")

	if contact.Name == "" {
		return c.Redirect(302, fmt.Sprintf("/contact?error=%s", url.QueryEscape("Empty contact name")))
	}

	if contact.Reason == "" {
		return c.Redirect(302, fmt.Sprintf("/contact?error=%s", url.QueryEscape("Empty contact text")))
	}

	_, err = database.Current.NamedExec(database.Queries.InsertContact, contact)
	if err != nil {
		log.Println(database.Queries.InsertContact)
		log.Println("Cannot insert new contact data:", err)
		return c.Redirect(302, fmt.Sprintf("/contact?error=%s", url.QueryEscape("Cannot create your comment")))
	}

	return c.Redirect(302, fmt.Sprintf("/contact?msg=%s", url.QueryEscape("Thank you! We will contact you back in a few hours.")))
}
Example #9
0
/**
 * 快递查询用户接口POST
 */
func expressQueryUsers(c *echo.Context) error {
	userName := c.Form("userName")
	userPhone := c.Form("userPhone")

	if userName == "" {
		return c.JSON(http.StatusOK, errorMsg{errorNo: expressUserNameEmpty, errorMsg: "expressUserNameEmpty"})
	}

	if userPhone == "" {
		return c.JSON(http.StatusOK, errorMsg{errorNo: expressUserPhoneEmpty, errorMsg: "expressUserPhoneEmpty"})
	}

	engine.Where("user_name = ? and user_phone = ?", userName, userPhone).AllCols().Get(&tcUser)

	return c.JSON(http.StatusOK, tcUser)
}
Example #10
0
func download(c *echo.Context) error {
	type assets struct {
		Background int `json:"background"`
		Face       int `json:"face"`
		Clothes    int `json:"clothes"`
		Mouth      int `json:"mouth"`
		Hair       int `json:"hair"`
		Eye        int `json:"eye"`
	}
	gender_str := c.Form("gender")
	data_str := c.Form("data")

	var gender govatar.Gender
	var _assets assets

	switch gender_str {
	case "male":
		gender = govatar.MALE
	case "female":
		gender = govatar.FEMALE
	default:
		return c.String(http.StatusBadRequest, "Incorrect gender param")
	}

	if err := json.Unmarshal([]byte(data_str), &_assets); err != nil {
		return c.String(http.StatusBadRequest, err.Error())
	}

	img, err := govatar.GenerateFromAssets(gender, []int{_assets.Background - 1, _assets.Face - 1, _assets.Clothes - 1,
		_assets.Mouth - 1, _assets.Hair - 1, _assets.Eye - 1})

	if err != nil {
		return c.String(http.StatusBadRequest, err.Error())
	}

	buf := new(bytes.Buffer)
	if err := png.Encode(buf, img); err != nil {
		return c.String(http.StatusInternalServerError, err.Error())
	}

	c.Response().Header().Set(echo.ContentDisposition, "attachment; filename=avatar.png")
	http.ServeContent(c.Response(), c.Request(), "avatar.png", time.Now(), bytes.NewReader(buf.Bytes()))
	return nil
}
Example #11
0
func postGroup(ctx *echo.Context) error {
	g := Group{
		ID:            ctx.Form("id"),
		Name:          ctx.Form("name"),
		Location:      ctx.Form("timezone"),
		DefaultTarget: ctx.Form("defaultTarget"),
	}
	if g.ID == "" {
		g.ID = uuid.NewV1().String()
	}
	return saveGroup(dbFromContext(ctx), &g)
}
Example #12
0
/**
 *  快递通知接口
 */
func expressEmailMessage(c *echo.Context) error {
	userID := c.Form("userID")         //收件人ID
	takeUserID := c.Form("takeUserID") //取件人ID 通知ID
	var takeUser model.TcUser
	engine.Id(userID).Get(&takeUser) //通过取件人ID获取取件人信息
	go sendMail(takeUser)
	_, err = engine.Insert(&model.TcExpressMail{
		ExpressFromUserId:    userID,
		ExpressToUserId:      takeUserID,
		ExpressCreateUserId:  userID,
		ExpressCreateDate:    time.Now(),
		ExpressToExpressDate: time.Now(),
		ExpressTakeStatus:    expressSucc,
	})
	if err != nil {
		return c.JSON(http.StatusOK, errorMsg{errorNo: expressMailFailed, errorMsg: "expressMailFailed"})
	}
	return c.JSON(http.StatusOK, errorMsg{errorNo: expressMailSucc, errorMsg: "expressMailSucc"})
}
Example #13
0
func (a *Application) login(c *echo.Context) error {
	id := c.Form("Id")
	user := a.Redis.GetUser(domain.ShaHashString(id))
	password := domain.HashPassword([]byte(c.Form("Password")), []byte(id))
	sessionKey := domain.HashPassword([]byte(id), []byte(user.CreateDate.String()))
	if user.Password == password {
		http.SetCookie(c.Response(), &http.Cookie{Name: "login", Value: sessionKey, MaxAge: 2592000})
		userAsJson, err := json.Marshal(user)
		if err != nil {
			fmt.Println(err)
		} else {
			a.Redis.Put(sessionKey, string(userAsJson))
			return c.Redirect(302, "/")
		}
	} else {
		fmt.Println("not a match")
	}

	return c.Redirect(302, "/login?failed=true")
}
Example #14
0
// postRegister регистрирует устройство, чтобы на него можно было отсылать push-уведомления.
func postRegister(c *echo.Context) error {
	pushType := c.Param("push-type") // получаем идентификатор типа уведомлений
	switch pushType {
	case "apns": // Apple Push Notification
	case "gcm": // Google Cloud Messages
	default: // не поддерживаемы тип
		return echo.NewHTTPError(http.StatusNotFound)
	}
	groupID := c.Get("GroupID").(string)  // идентификатор группы
	userID := c.Get("ID").(bson.ObjectId) // идентификатор пользователя
	token := c.Form("token")              // токен устройства
	if len(token) != 32 {
		return echo.NewHTTPError(http.StatusBadRequest, "bad token size")
	}
	btoken, err := hex.DecodeString(token)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "bad token format")
	}
	_, _, _ = btoken, groupID, userID
	return echo.NewHTTPError(http.StatusNotImplemented)
}
Example #15
0
func (h *handler) AddToFavPostHandler(c *echo.Context) error {
	s := c.Get("session").(session.Session)
	if s.Get("username") == "" {
		return c.JSON(http.StatusForbidden, "")
	}
	user := c.Get("user").(model.UserRow)

	p, err := h.back.Model.Package.GetItem(c.Form("package"))
	if err != nil {
		log.Println(err)
		return c.JSON(http.StatusBadRequest, err.Error())
	}

	user.Packages = append(user.Packages, p.Id)
	_, err = h.back.Model.User.Upsert(&user)
	if err != nil {
		log.Println(err)
		return c.JSON(http.StatusBadRequest, err.Error())
	}

	return c.JSON(http.StatusOK, nil)
}
Example #16
0
func PostGroups(c *echo.Context) error {
	res := NewResponseTemplate()

	group := &Group{}
	group.Id = groupSeq
	if group.Name = "Unnamed Group"; len(c.Form("name")) > 0 {
		group.Name = c.Form("name")
	}

	err := SaveGroupImage(c.Request(), group, res)
	if err != nil {
		return c.JSON(res.StatusCode, res)
	}

	err = SaveGroup(group, res)
	if err != nil {
		return c.JSON(res.StatusCode, res)
	}

	res.Content = group
	return c.JSON(http.StatusOK, res)
}
Example #17
0
func CreateCampaign(c *echo.Context) error {
	// POST /campaign
	// User is decoded from JWT Token
	name := c.Form("name")

	log.Printf(name)
	// Grab from JWT instead
	userid := 5

	var campaign Campaign

	if err := db.QueryRow("INSERT INTO campaigns(userid, name) VALUES ($1, $2) RETURNING id", userid, name).Scan(&campaign.Id); err != nil {
		log.Printf("I can't even put it in.")
		log.Fatal(err)
	}

	if err := db.QueryRow("SELECT userid, name FROM campaigns WHERE id=$1", campaign.Id).Scan(&campaign.UserId, &campaign.Name); err != nil {
		log.Fatal(err)
	}

	return c.JSON(http.StatusCreated, campaign)
}
Example #18
0
/**
 *  快递取件接口
 */
func expressTake(c *echo.Context) error {
	expressID := c.Form("expressID") //取件ID
	userID := c.Form("userID")       //取件人ID
	expressIdTmp, err := strconv.ParseInt(expressID, 10, 32)
	expressId := int(expressIdTmp)
	upUsers := &model.TcExpressTake{
		ExpressTakeUserId:    userID,
		ExpressTakeDate:      time.Now(),
		ExpressTakeExpressId: expressId,
	}
	_, err = engine.AllCols().Insert(upUsers)
	if err != nil {
		return c.JSON(http.StatusOK, errorMsg{errorNo: expressTakeFailed, errorMsg: "expressTakeFailed"})
	}
	upMailUsers := &model.TcExpressMail{
		ExpressTakeStatus: expressTakeSucc,
	}
	_, err = engine.Where("express_id = ?", expressID).Cols("express_take_status").Update(upMailUsers)
	if err != nil {
		return c.JSON(http.StatusOK, errorMsg{errorNo: expressTakeFailed, errorMsg: "expressTakeFailed"})
	}
	return c.JSON(http.StatusOK, errorMsg{errorNo: expressTakeSucc, errorMsg: "expressTakeSucc"})
}
Example #19
0
// Create a new lead in database
func (h Handler) Create(c *echo.Context) error {
	mail := c.Form("mail")
	if mail == "" {
		return c.String(http.StatusBadRequest, "mail is mandatory")
	}

	result, err := h.ds.GetHashByMail(mail)
	if result != "" {
		return c.JSON(http.StatusOK, result)
	}

	invited := c.Form("invited")
	h.ds.Create(mail, invited)

	result, err = h.ds.GetHashByMail(mail)
	if err != nil {
		return err
	}

	cookie := http.Cookie{Name: "ownHash", Value: result, Expires: time.Now().Add(365 * 24 * time.Hour)}
	http.SetCookie(c.Response().Writer(), &cookie)

	return c.JSON(http.StatusOK, result)
}
Example #20
0
/**
 * @api {post} /topics Creates a new topic
 * @apiName CreateTopic
 * @apiGroup Topics
 *
 * @apiParam {String} name The name of the topic
 */
func (tc *TopicsController) Create(c *echo.Context) error {
	resp := response.New(c)
	defer resp.Render()

	// Getting params
	name := c.Form("name")
	if name == "" {
		resp.AddErrorDetail(response.ErrorMissingNameParameter)
		resp.SetResponse(http.StatusBadRequest, nil)
		return nil
	}

	// Creating the topic
	topic := new(models.Topic)
	topic.Name = name
	err := topic.Insert()
	if err != nil {
		resp.SetResponse(http.StatusConflict, nil)
		return nil
	}

	resp.SetResponse(http.StatusOK, topic)
	return nil
}
Example #21
0
func requestAddRsvp(c echo.Context) error {
	name := c.Form("name")
	email := c.Form("email")
	res := c.Form("response")
	if name == "" || email == "" {
		c.String(http.StatusBadRequest, "Name and Email must be given. Please go back and try again.")
		return nil
	}

	rsvp := Rsvp{0, name, email, res, time.Now()}
	if err := addRsvp(rsvp); err != nil {
		c.String(http.StatusInternalServerError,
			"Failed to add RSVP at this time. Please try again later")
	}

	c.HTML(http.StatusOK, saveSuccess)
	return nil
}
Example #22
0
func updateBot(c *echo.Context) error {
	mlog.Trace("Функция: updateBot")
	id, err := strconv.Atoi(c.Param("id")) // преобразовать в int
	if err != nil {
		mlog.Error(err)
	} else {
		inf := make(map[string]interface{})
		// TODO перед заполнением проверить наличие переданных значений. И заполнять только те, которые пришли с запросом
		inf["id"] = id
		inf["name"] = c.Form("name")
		inf["login"] = c.Form("login")
		inf["password"] = c.Form("password")

		mlog.Trace("Функция: updateBot. Получены данные ", inf)
		if err := updBot(id, inf); err != nil {
			mlog.Error(err)
		}
	}
	return c.String(http.StatusOK, "ok") // сообщить, что бот изменен
}
Example #23
0
func (a *Application) createUser(c *echo.Context) error {
	userEmail := c.Form("Id")
	valid := domain.ValidateEmail(userEmail)
	if valid {
		role := domain.Role{Name: domain.Normal}

		if a.Redis.DbSize() == 0 {
			role = domain.Role{Name: domain.Admin}
		}

		hashedId := domain.ShaHashString(userEmail)
		user := &domain.User{
			Id:                      hashedId,
			Email:                   userEmail,
			Username:                c.Form("Username"),
			Password:                domain.HashPassword([]byte(c.Form("Password")), []byte(userEmail)),
			CreateDate:              time.Now().UTC(),
			EmailVerified:           false,
			EmailVerificationString: domain.HashPassword([]byte(userEmail), []byte(time.Now().String())),
			Role: role,
		}
		userJSON, err := json.Marshal(user)
		if err != nil {
			fmt.Println(err)
		} else {
			err := a.Redis.AddNewUser(user.Id, string(userJSON))
			if err == nil {
				email.SendVerificationEmail(user.Email,
					hashedId+"/"+user.EmailVerificationString,
					fromEmail,
					emailSendingPasswd)
				return c.Redirect(302, "/")
			}
		}
	} else {
		return c.Redirect(302, "/register?email=err")
	}
	return c.Redirect(302, "/?status=failed")
}
Example #24
0
func createJob(c *echo.Context) error {
	mdb, _ := getDatabase()

	name := c.Form("name")
	schedule := c.Form("schedule")
	script := c.Form("script")

	job := db.Job{
		Name:     name,
		Schedule: schedule,
		Script:   script,
	}

	defer mdb.Session.Close()

	err := db.CreateJob(mdb, job)

	if err != nil {
		return c.JSON(500, struct{ Error string }{err.Error()})
	}

	return c.JSON(200, job)
}
Example #25
0
func updateJob(c *echo.Context) error {

	mdb, _ := getDatabase()

	id := c.Param("id")
	name := c.Form("name")
	schedule := c.Form("schedule")
	script := c.Form("script")

	defer mdb.Session.Close()

	err := db.UpdateJob(mdb, id, db.Job{Name: name, Schedule: schedule, Script: script})

	if err != nil {
		return c.JSON(500, struct{ Error string }{err.Error()})
	}

	return c.JSON(200, struct {
		Name     string
		Schedule string
		Script   string
	}{name, schedule, script})
}
Example #26
0
func Change(c *echo.Context) error {
	var changes []ChangeRequest
	err := json.Unmarshal([]byte(c.Form("changes")), &changes)
	if err != nil {
		return err
	}
	log.Println("Received changes", changes)
	domain := c.Get("domain").(Domain)

	// serialize map file rewrites
	rewrite_lock.Lock()
	defer func() {
		rewrite_lock.Unlock()
	}()
	// find all existing local addresses, but exclude command delivery
	a := readMapFile(domain.MapFile, nil)
	local := make(map[string]bool)
	for i := 0; i < len(a); i++ {
		if strings.Contains(a[i].Email, "@"+domain.Name) && !strings.ContainsAny(a[i].Target, "@|") {
			local[a[i].Target] = true
		}
	}
	// dedupe and normalize changes
	remap := make(map[string]string)
	for _, change := range changes {
		address, err := mail.ParseAddress(change.Alias)
		if err != nil || !strings.HasSuffix(address.Address, "@"+domain.Name) {
			log.Println("invalid alias:", change.Alias)
			return c.Render(http.StatusBadRequest, "error", struct {
				Error string
			}{"invalid alias: " + change.Alias})
		}
		switch change.Op {
		case "remove":
			remap[address.Address] = ""
		case "add":
			if validate(change.Target, local) {
				remap[address.Address] = change.Target
			} else {
				return c.Render(http.StatusBadRequest, "error", struct {
					Error string
				}{"invalid email address list for " + address.Address + ": " + change.Target})
			}
		default:
			log.Fatal("unexpected change request: ", change)
		}
	}
	// rewrite the map file atomically
	tmp_file := domain.MapFile + ".web.new"
	f, err := os.OpenFile(tmp_file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		log.Fatal("could not rewrite map file ", tmp_file, " due to ", err)
	}
	fw := bufio.NewWriter(f)
	readMapFile(domain.MapFile, func(line string, email string) {
		if email == "" {
			fw.WriteString(line + "\n")
		} else {
			dest, ok := remap[email]
			if ok {
				if dest != "" {
					new_line(fw, email, dest)
					// remove any further references
					remap[email] = ""
				}
			} else {
				fw.WriteString(line + "\n")
			}
		}
	})
	for email, dest := range remap {
		if dest != "" {
			new_line(fw, email, dest)
		}
	}
	fw.Flush()
	f.Close()
	err = os.Rename(domain.MapFile, domain.MapFile+".old")
	if err != nil {
		return err
	}
	err = os.Rename(tmp_file, domain.MapFile)
	if err != nil {
		os.Rename(domain.MapFile+".old", domain.MapFile)
		return err
	}
	cmd := exec.Command("postmap", domain.MapFile)
	err = cmd.Run()
	if err != nil {
		os.Rename(domain.MapFile+".old", domain.MapFile)
		return err
	}
	cmd = exec.Command("postfix", "reload")
	err = cmd.Run()
	if err != nil {
		log.Println("postfix reload failed:", err)
	}

	// HTTP 303 is specifically for POST/Redirect/GET
	// see: https://en.wikipedia.org/wiki/Post/Redirect/Get
	c.Response().Header().Set("Location", "/")
	return c.HTML(303, "<script>document.location.href = \"/\";</script>")
}
Example #27
0
// AddComment tries to create a new comment in database, if success will redirect to original post
func AddComment(c *echo.Context) error {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		return c.Render(500, "500", err)
	}

	name := c.Form("name")
	email := c.Form("email")
	content := c.Form("content")
	useEmail, _ := strconv.ParseBool(c.Form("allow-use-email"))
	recaptchaResp := c.Form("g-recaptcha-response")

	if name == "" {
		return c.Redirect(302, fmt.Sprintf("/posts/%d?error=%s", id, url.QueryEscape("You must insert your name")))
	}

	if content == "" {
		return c.Redirect(302, fmt.Sprintf("/posts/%d?error=%s", id, url.QueryEscape("You must comment something")))
	}

	if cr, _ := strconv.ParseBool(config.RecaptchaEnabled); cr {
		// Check recaptcha value
		failmsg := url.QueryEscape("Cannot test if you are not a robot")
		reqbody := fmt.Sprintf("secret=%s&response=%s", config.RecaptchaSecretKey, recaptchaResp)
		resp, err := http.Post("https://www.google.com/recaptcha/api/siteverify", "application/x-www-form-urlencoded", bytes.NewBufferString(reqbody))
		if err != nil {
			log.Println("Error response from Recaptcha api:", err)
			return c.Redirect(302, fmt.Sprintf("/posts/%d?error=%s", id, failmsg))
		}

		var fields struct {
			Success bool `json:"success"`
		}

		resbody, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Println("Error when getting data from recaptcha api:", err)
			return c.Redirect(302, fmt.Sprintf("/posts/%d?error=%s", id, failmsg))
		}

		err = json.Unmarshal(resbody, &fields)
		if err != nil {
			log.Println("Error decoding response from Recaptcha api:", err)
			return c.Redirect(302, fmt.Sprintf("/posts/%d?error=%s", id, failmsg))
		}
		resp.Body.Close()

		if !fields.Success {
			return c.Redirect(302, fmt.Sprintf("/posts/%d?error=%s", id, failmsg))
		}
	}

	// Store comment
	comment := models.Comment{
		PostID:       id,
		ReplyTo:      name,
		ReplyEmail:   sql.NullString{String: email, Valid: true},
		Content:      content,
		AllowedEmail: useEmail,
		Approved:     false,
	}

	_, err = database.Current.NamedExec(database.Queries.InsertComment, comment)
	if err != nil {
		log.Println("Cannot insert new comment:", err)
		return c.Redirect(302, fmt.Sprintf("/posts/%d?error=%s", id, url.QueryEscape("Cannot create your comment")))
	}

	// TODO: Notify comment

	// Return
	msg := url.QueryEscape("Thanks! your comment may take a while to be shown due approvation process")
	return c.Redirect(302, fmt.Sprintf("/posts/%d?msg=%s", id, msg))
}
Example #28
0
// This handles the message sending
func send(c *echo.Context) error {

	var msg Message
	var merge bytes.Buffer

	// Parse out data
	// Type
	if c.Form("type") != "" {
		msg.Type = c.Form("type")
	} else {
		msg.Type = msgType
	}

	// Template
	if c.Form("template") != "" {
		msg.Template = c.Form("template")
	} else {
		msg.Template = msgTemplate
	}

	// FromEmail
	if c.Form("fromEmail") != "" {
		msg.FromEmail = c.Form("fromEmail")
	} else {
		msg.FromEmail = msgFromEmail
	}

	// Subject2
	if c.Form("subject2") != "" {
		msg.Subject2 = c.Form("subject2")
	} else {
		msg.Subject2 = msgSubject2
	}

	// CC
	if c.Form("ccEmail1") != "" {
		msg.CCEmail1 = c.Form("ccEmail1")
	} else {
		msg.CCEmail1 = ""
	}

	if c.Form("ccEmail2") != "" {
		msg.CCEmail2 = c.Form("ccEmail2")
	} else {
		msg.CCEmail2 = ""
	}

	msg.ToName = c.Form("toName")
	msg.ToEmail = c.Form("toEmail")
	msg.Subject = c.Form("subject")
	msg.Body = c.Form("body")

	// Combine body with template
	t := template.Must(template.ParseFiles(filepath.Join("templates", msg.Template)))
	t.Execute(&merge, msg)

	// Send the message
	sg := sendgrid.NewSendGridClient(sendgridUser, sendgridPass)
	m := sendgrid.NewMail()
	m.AddTo(msg.ToEmail)
	m.AddToName(msg.ToName)
	m.SetSubject(msg.Subject)
	m.SetHTML(merge.String())
	m.SetFrom(msg.FromEmail)

	// Copy to sender using BCC
	m.AddBcc(msg.FromEmail)

	// Handle up to 2 CC addresses
	if msg.CCEmail1 != "" {
		m.AddCc(msg.CCEmail1)
	}

	if msg.CCEmail2 != "" {
		m.AddCc(msg.CCEmail2)
	}

	// Based on success log & respond
	if r := sg.Send(m); r == nil {
		fmt.Println("Email sent")
		return c.JSON(201, "Email sent")
	} else {
		fmt.Println(r)
		return c.JSON(400, "There was a problem, the email could not be sent. Please check the logs")
	}

}