package controllers import ( "fmt" "git.myrkvi.com/myrkvi/bin/config" "git.myrkvi.com/myrkvi/bin/global" "git.myrkvi.com/myrkvi/bin/models" "git.myrkvi.com/myrkvi/bin/utils" "github.com/go-mail/mail" "github.com/labstack/echo/v4" "github.com/sirupsen/logrus" "github.com/spf13/viper" "gorm.io/gorm" ) func PostEmailHandler(c echo.Context) error { code := c.Param("id") adminCode := c.FormValue("adminKey") email := c.FormValue("email") if !viper.GetBool("smtp.enabled") { return utils.RenderErrorToast(c, "function not available") } file := models.File{} result := global.DB.Where("page_key = ?", code).First(&file) if result.Error == gorm.ErrRecordNotFound { return utils.RenderErrorToast(c, "the file does not exist") } else if result.Error != nil { return utils.RenderErrorToast(c, "server error occurred") } if adminCode != file.AdminKey { return utils.RenderErrorToast(c, "incorrect deletion key") } if file.Email != "" { return utils.RenderErrorToast(c, "this file is already associated with an email") } file.Email = email result = global.DB.Save(&file) if result.Error != nil { logrus.WithError(result.Error). WithFields(logrus.Fields{ "file code": file.PageKey, "email": email, }).Errorln("failed to save email for file") return utils.RenderErrorToast(c, "server error occurred") } smtp := config.SMTP dial := mail.NewDialer(smtp.Host, int(smtp.Port), smtp.Username, smtp.Password) message := mail.NewMessage() message.SetHeader("From", smtp.From) message.SetHeader("To", email) message.SetHeader("Subject", fmt.Sprintf("[bin] Deletion key for file '%s'", file.Filename)) message.SetBody( "text/plain", fmt.Sprintf( "Deletion key for the file located at %s is %s.\r\nYou can also use this link: %s", fmt.Sprintf("%s/b/%s", config.BaseURL, file.PageKey), file.AdminKey, fmt.Sprintf("%s/b/%s?delcode=%s", config.BaseURL, file.PageKey, file.AdminKey), ), ) err := dial.DialAndSend(message) if err != nil { return utils.RenderErrorToast(c, "could not send email") } return c.HTML(200, "

email sent!

") }