feat(email): endpoint for sending auth code
This commit is contained in:
@ -50,7 +50,7 @@ func (a *Auth) IsCodeValid(email string, code string) bool {
|
||||
return existingCode.Valid.After(time.Now()) && existingCode.Code == code
|
||||
}
|
||||
|
||||
func NewAuth(mailer Mailer) Auth {
|
||||
func CreateAuth(mailer Mailer) Auth {
|
||||
return Auth{
|
||||
codes: make(map[string]Code),
|
||||
mailer: mailer,
|
||||
|
@ -23,6 +23,22 @@ func (m MailClient) getMessage() (*mail.Msg, error) {
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (m MailClient) SendCode(to string, code string) error {
|
||||
msg, err := m.getMessage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := msg.To(to); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
msg.Subject("Login to Haystack")
|
||||
msg.SetBodyString(mail.TypeTextPlain, code)
|
||||
|
||||
return m.client.DialAndSend(msg)
|
||||
}
|
||||
|
||||
func CreateMailClient() (MailClient, error) {
|
||||
client, err := mail.NewClient(
|
||||
"smtp.mailbox.org",
|
||||
|
@ -41,6 +41,13 @@ func main() {
|
||||
imageModel := models.NewImageModel(db)
|
||||
userModel := models.NewUserModel(db)
|
||||
|
||||
mail, err := CreateMailClient()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
auth := CreateAuth(mail)
|
||||
|
||||
go ListenNewImageEvents(db)
|
||||
|
||||
r := chi.NewRouter()
|
||||
@ -218,8 +225,28 @@ func main() {
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
})
|
||||
|
||||
log.Println("Listening and serving on port 3040.")
|
||||
r.Post("/login", func(w http.ResponseWriter, r *http.Request) {
|
||||
type LoginBody struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
loginBody := LoginBody{}
|
||||
err := json.NewDecoder(r.Body).Decode(&loginBody)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprintf(w, "Request body was not correct")
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: validate it's an email
|
||||
|
||||
auth.CreateCode(loginBody.Email)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
log.Println("Listening and serving on port 3040.")
|
||||
if err := http.ListenAndServe(":3040", r); err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
|
Reference in New Issue
Block a user