Reset Password by email

Hi All
Can you please tell me how to implement reset the password by email for my web application?. I don’t have any idea how to develop it
thanks
Sudesh

When user requests to reset password, generate a secure key, assign it to the user. create link and send it to user with email. when user clicks the link, check if key is correct let user to change password. this is the simplest way as i know. i can share sample code if you like.

Pls do.

I used MailJet as a email service. All messages and mail content is Turkish :slight_smile:

func requestResetPasswordEmail(c *gin.Context) {
	var rrpef RequestResetPasswordEmailForm
	err := c.BindJSON(&rrpef)
	if err != nil {
		errorMessage := "Form bilgileri alınamadı!"
		l.Error(errorMessage)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error_message": errorMessage,
		})
		return
	}
	emailAddress := rrpef.EmailAddress
	u, err := db.GetUserByEmailAddress(emailAddress)
	if err != nil {
		errorMessage := err.Error()
		l.Error(errorMessage)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error_message": errorMessage,
		})
		return
	}
	userId := u.Id
	name := u.Name
	rpr, err := db.GetResetPasswordRequestByUserId(userId)
	if err != nil {
		errorMessage := err.Error()
		l.Error(errorMessage)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error_message": errorMessage,
		})
		return
	}
	if rpr != nil {
		resetPasswordRequestInterval := co.ResetPasswordRequestInterval
		availableAt := rpr.CreatedAt.Add(time.Duration(resetPasswordRequestInterval) * time.Minute)
		leftDuration := int(availableAt.Sub(time.Now().UTC()).Seconds())
		if leftDuration > 0 {
			errorMessage := fmt.Sprintf("Tekrar şifre sıfırlama talebinde bulunmadan önce %v saniye bekleyin!", leftDuration)
			l.Error(errorMessage)
			c.JSON(http.StatusInternalServerError, gin.H{
				"error_message": errorMessage,
			})
			return
		}
	}
	key := kg.GenerateStringKey(64)
	ipAddress := c.ClientIP()
	rpr = &db.ResetPasswordRequest{
		UserId:    userId,
		Key:       key,
		IpAddress: ipAddress,
		CreatedAt: time.Now().UTC(),
	}
	err = db.InsertResetPasswordRequest(rpr)
	if err != nil {
		errorMessage := err.Error()
		l.Error(errorMessage)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error_message": errorMessage,
		})
		return
	}
	m := ec.Message{
		EmailAddress: emailAddress,
		Name:         name,
		Subject:      "Şifre Sıfırlama Talebi",
		HtmlPart: `<p>Şifrenizi değiştirmek için aşağıdaki bağlantıya tıklayın:</p>
			<a href="http://market.atiaup.com/change_password/` + key + `">http://market.atiaup.com/change_password/` + key + `</a>
			<p>Eğer şifre sıfırlama talebinde bulunmaduysanız bu maile cevap vererek bizim ile irtibata geçebilirsiniz.</p>`,
	}
	err = ec.Send(&m)
	if err != nil {
		errorMessage := err.Error()
		l.Error(errorMessage)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error_message": errorMessage,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success_message": "Şifre değiştirme bağlantısı e-posta adresinize gönderildi. Kullanıcı girişi sayfasına yönlendiriliyorsunuz.",
	})
}

func publicChangePassword(c *gin.Context) {
	key := c.Param("key")
	_, err := db.GetResetPasswordRequestByKey(key)
	if err != nil {
		errorMessage := err.Error()
		l.Error(errorMessage)
		renderTemplateWithMessages(c, "public_change_password.html", "", "", errorMessage)
		return
	}
	renderTemplateWithKey(c, "public_change_password.html", key)
}

func publicUpdatePassword(c *gin.Context) {
	var upwkf UpdatePasswordWithKeyForm
	err := c.BindJSON(&upwkf)
	if err != nil {
		errorMessage := "Form bilgileri alınamadı!"
		l.Error(errorMessage)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error_message": errorMessage,
		})
		return
	}
	key := upwkf.Key
	password := upwkf.Password
	rpr, err := db.GetResetPasswordRequestByKey(key)
	if err != nil {
		errorMessage := err.Error()
		l.Error(errorMessage)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error_message": errorMessage,
		})
		return
	}
	userId := rpr.UserId
	u, err := db.GetUser(userId)
	if err != nil {
		errorMessage := err.Error()
		l.Error(errorMessage)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error_message": errorMessage,
		})
		return
	}
	companyId := u.CompanyId
	name := u.Name
	emailAddress := u.EmailAddress
	err = db.UpdateUserPassword(companyId, userId, password)
	if err != nil {
		errorMessage := err.Error()
		l.Error(errorMessage)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error_message": errorMessage,
		})
		return
	}
	m := ec.Message{
		EmailAddress: emailAddress,
		Name:         name,
		Subject:      "Şifre Değiştirme Bilgisi",
		HtmlPart: `<p>Şifreniz değiştirildi.</p>
			<p>Eğer şifrenizi siz değiştirmediyseniz bu maile cevap vererek bizim ile irtibata geçebilirsiniz.</p>`,
	}
	err = ec.Send(&m)
	if err != nil {
		errorMessage := err.Error()
		l.Error(errorMessage)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error_message": errorMessage,
		})
		return
	}
	err = db.DeleteResetPasswordRequest(userId)
	if err != nil {
		errorMessage := err.Error()
		l.Error(errorMessage)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error_message": errorMessage,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success_message": "Şifreniz değiştirildi. Kullanıcı girişi sayfasına yönlendiriliyorsunuz. Kullanıcı adınız ve yeni şifreniz ile giriş yapabilirsiniz.",
	})
}
1 Like

thanks lot ermanimer

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.