Ejemplo n.º 1
0
func (user *User) Register(db *gorm.DB) error {
	var err error
	user.VerificationCode, err = GenerateVerificationCode(db)
	if err != nil {
		return err
	}

	user.Password = auth.NewBcryptHasher().Hash(user.Password)
	user.CreatedAt = time.Now()

	return db.Save(user).Error
}
Ejemplo n.º 2
0
func (this *Users) Login(res http.ResponseWriter, req *http.Request, render render.Render) {
	var data struct{ Username, Password string }

	if decode(req, render, &data) != nil {
		return
	}

	user, err := models.GetUserByUsername(this.db, data.Username)
	if err != nil {
		switch err {
		case gorm.RecordNotFound:
			utils.HttpError(res, http.StatusUnauthorized)
		default:
			utils.HttpError(res, http.StatusInternalServerError)
		}
		return
	}

	if auth.NewBcryptHasher().Check(user.Password, data.Password) != nil {
		utils.HttpError(res, http.StatusUnauthorized)
		return
	}

	token, err := models.GenerateApiToken(this.db)
	if err != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	user.Token = token
	if this.db.Model(user).UpdateColumn("token", token).Error != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	user.Password = ""

	if user.FetchSchedules(this.db) != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	if user.FetchSyncs(this.db) != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	render.JSON(http.StatusOK, user)
}