Ejemplo n.º 1
0
func (r *UserRepository) InsertPassword(user *models.User) error {
	user.HashPassword = cleanPassword(user.Password)

	_, err := r.S.Exec(user.User_ID, user.HashPassword)

	if err != nil {
		fmt.Println(err)
		return err
	}

	user.HashPassword = nil
	user.Password = ""

	return err
}
func RegisterUserDB(user *models.User, env *Env) (err error) {
	var user_id int64
	var username string
	var email string
	var stmt *sql.Stmt

	query := "SELECT user_id, email, username FROM users WHERE username=? || email=?"
	tx, err := env.Db.BeginTx()
	if err != nil {
		return err
	}
	err = tx.QueryRow(query, user.Username, user.Email).Scan(&user_id, &username, &email)
	if err != nil && err != sql.ErrNoRows {
		return err
	}

	if err == nil {
		if user.Username == username {
			err = errors.New(fmt.Sprintf("Username %s already taken", user.Username))
			return err
		} else if user.Email == email {
			err = errors.New(fmt.Sprintf("Email %s already taken", user.Username))
			return err
		}
	}

	//store user and password into DB:
	if err == sql.ErrNoRows {
		query := "INSERT INTO users(username,email) VALUES(?,?)"
		stmt, err = tx.Prepare(query)
		if err != nil {
			err = errors.New("error in tx.Prepare()")
			return err
		}

		repo := &data.UserRepository{S: stmt}
		user_id, err = repo.CreateUser(user)
		if err != nil {
			err = errors.New("error in repo.CreateUser()")
			return err
		}
		user.User_ID = user_id

		query = "INSERT INTO passwords(user_id,password) VALUES(?,?)"
		stmt, err = tx.Prepare(query)
		if err != nil {
			err = errors.New("error in tx.Prepare()")
			return err
		}

		repo = &data.UserRepository{S: stmt}
		err = repo.InsertPassword(user)
		if err != nil {
			err = errors.New("error in repo.CreateUser() -> repo.InsertPassword()")
			return err
		}
	}

	//just to make sure:
	user.User_ID = user_id
	user.HashPassword = nil
	user.Password = ""

	defer func() {
		if err == nil {
			tx.Commit()
		} else {
			tx.Rollback()
		}
		stmt.Close()
	}()

	return
}