与go-gorm框架一起使用的动态查询

时间:2019-01-17 06:36:53

标签: go go-gorm

我正在编写一个动态查询,并使用go-gorm的db.Raw()函数执行它。我想防止对已构建的查询进行SQL注入攻击。

我正在编写此查询,以使所有用户都具有服务器端分页,搜索和过滤器。 我的查询工作非常完美,但是有SQL注入攻击的威胁。

// GetUserGridDataWithPagination - gets data to show in users grid to admin with pagination
func (controller Admin) GetUserGridDataWithPagination(
    filterBy string,
    searchBy string,
    sortBy string,
    sortOrder string,
    pageSize uint16,
    pageNumber uint16,
) ([]model.AdminUserGridData, int64, uint16, error) {
    var list []model.AdminUserGridData
    query := `SELECT * FROM users_master`
    query1 := `SELECT count(*) FROM users_master`
    clause := ` WHERE `
    filterCondition := ""
    searchCondition := ""
    sortCondition := ""
    if filterBy != "all" {
        filterCondition = ` WHERE role = '` + filterBy + `'`
        clause = ` AND `
    }
    if searchBy != "" {
        search := "'%" + searchBy + "%'"
        searchCondition = clause +
            `name ilike ` + search + ` OR
                email ilike ` + search + ` OR
                phone ilike ` + search + ` OR
                profession ilike ` + search + ` OR
                role ilike ` + search + ` OR
                kyc_status ilike ` + search
    }
    if sortBy != "" {
        column := ""
        if sortBy == "kycStatus" {
            column = "kyc_status"
        } else {
            column = sortBy
        }
        if sortOrder != "" {
            sortCondition = ` ORDER BY ` + column + ` ` + sortOrder
        }
    }
    if filterCondition != "" {
        query = query + filterCondition
        query1 = query1 + filterCondition
    }
    if searchCondition != "" {
        query = query + searchCondition
        query1 = query1 + searchCondition
    }
    if sortCondition != "" {
        query = query + sortCondition
    }
    query = query + ` LIMIT ? OFFSET ?`
    // fetch records from database
    if err := controller.database.Raw(query, pageSize, (pageSize * (pageNumber - 1))).Scan(&list).Error; err != nil {
        log.Error(err)
        return nil, 0, 0, errors.New("Error while processing your request")
    }
    // fetch total no of records from database
    type RowCount struct {
        Count int64 `json:"count"`
    }
    var rowCount RowCount
    if err := controller.database.Raw(query1).Scan(&rowCount).Error; err != nil {
        log.Error(err)
        return nil, 0, 0, errors.New("Error while processing 
your request")
    }
    return list, rowCount.Count, pageNumber, nil
}

我在项目中做了很多次。因此,我正在寻找一种无需更改查询即可纠正此问题的方法,而是使用任何第三方库来纠正此问题。 (就像我们在使用sql-escape-string的nodejs中所做的一样 软件包可在npm获得)

1 个答案:

答案 0 :(得分:1)

您应该使用gorm查询生成器并在args中传递参数: Where(query interface{}, args ...interface{}) *DB。足够了。 由于上述gorm方法正在更改您正在构建的SQL查询的内部状态,因此可以编写如下代码:

var usersMasterList []UsersMaster // gorm Model
if filterBy != "all" {
    controller.database.Where("role = ?", filterBy)
}
if searchBy != "" {
    controller.database.Or("name ilike ?", search)
    controller.database.Or("email ilike ?", search)
    //...
}
//...
controller.database.Find(&usersMasterList)

代码未经测试。 您可以在此处了解更多信息:http://gorm.io/docs/query.html

或者您也可以使用regexp从这些字符串中过滤非字母数字字符:

rx := regexp.MustCompile("[^a-zA-Z0-9]+")
yourString = rx.ReplaceAllString(yourString, "")

强烈建议您尽快重写代码,这样代码将更加安全和可读。