silvermobi/handler/forget_password.go

69 lines
1.5 KiB
Go

package handler
import (
"context"
"crypto/rand"
"encoding/base64"
"git.coopgo.io/coopgo-apps/silvermobi/models"
gomail "gopkg.in/mail.v2"
)
func generateRandomPassword(length int) (string, error) {
buffer := make([]byte, length)
_, err := rand.Read(buffer)
if err != nil {
return "", err
}
password := base64.StdEncoding.EncodeToString(buffer)[:length]
return password, nil
}
func (h *SilverMobiHandler) ForgetAccount(ctx context.Context, username string, namespace string) (response bool,
accessCode string) {
var (
err error
account *models.Account
)
account, err = h.Services.MobilityAccounts.GetAccountUsername(ctx, username, namespace)
if err != nil {
return false, ""
}
message := []byte("Hello dear,\nYour new Silvermobi password is: ")
password, _ := generateRandomPassword(10)
if update := h.Services.MobilityAccounts.UpdatePassword(ctx, account.ID, password); !update {
return false, ""
}
m := gomail.NewMessage()
m.SetHeader("From", h.Config.GetString("emailing.smtp.username"))
m.SetHeader("To", username)
m.SetHeader("Subject", "Silvermobi Password Recovery")
message = append(message, []byte(password)...)
m.SetBody("text/plain", string(message))
d := gomail.NewDialer(
h.Config.GetString("emailing.smtp.host"),
h.Config.GetInt("emailing.smtp.port"),
h.Config.GetString("emailing.smtp.username"),
h.Config.GetString("emailing.smtp.password"),
)
d.StartTLSPolicy = gomail.MandatoryStartTLS
if err = d.DialAndSend(m); err != nil {
return false, ""
}
return true, password
}