Example #1
0
func LoadClients(limit, offset int, sort map[string]int) (clients []*models.Client, err error) {
	if limit < 1 {
		limit = 1
	}
	if offset < 0 {
		offset = 0
	}

	var orders []string
	for k, v := range sort {
		if inArray(k, clients_sortable_fields) {
			var o string
			if v == ASCENDING {
				o = "ASC"
			} else {
				o = "DESC"
			}
			orders = append(orders, k+" "+o)
		}
	}

	str := `SELECT id, name, code, secret, redirect_uri, created
	  , allowed_grant_types, allowed_response_types, allowed_scopes
	   FROM oauth_client `

	if len(orders) > 0 {
		str = str + " ORDER BY " + strings.Join(orders, ",")
	}

	str = fmt.Sprintf("%s LIMIT %d OFFSET %d", str, limit, offset)

	clients = make([]*models.Client, 0)
	qs := func(db *sql.DB) error {
		rows, err := db.Query(str)
		if err != nil {
			log.Printf("db query error: %s for sql %s", err, str)
			return err
		}
		defer rows.Close()
		for rows.Next() {
			c := new(models.Client)
			var (
				grandTypes, responseTypes, scopes string
			)
			err = rows.Scan(&c.Id, &c.Name, &c.Code, &c.Secret, &c.RedirectUri, &c.CreatedAt,
				&grandTypes, &responseTypes, &scopes)
			if err != nil {
				log.Printf("rows scan error: %s", err)
				continue
			}
			c.AllowedGrantTypes = strings.Split(grandTypes, ",")
			c.AllowedResponseTypes = strings.Split(responseTypes, ",")
			c.AllowedScopes = strings.Split(scopes, ",")
			clients = append(clients, c)
		}
		return rows.Err()
	}

	if err := withDbQuery(qs); err != nil {
		return nil, err
	}

	return clients, nil
}