view auth/opendb.go @ 196:b67208d82543

Make test output more comprehensive Running all tests in one transaction ensures the final output tells about any failing test, not just in the last transaction (i.e. test script). The price is that no traces of the tests are left in the database because we have to rollback in order to have no left-over test roles in the cluster.
author Tom Gottfried <tom@intevation.de>
date Fri, 20 Jul 2018 18:31:45 +0200
parents a98a282f00e1
children 0777aa6de45b
line wrap: on
line source

package auth

import (
	"database/sql"
	"fmt"
	"strings"

	"gemma.intevation.de/gemma/config"

	_ "github.com/jackc/pgx/stdlib"
)

const driver = "pgx"

// dbQuote quotes strings to be able to contain whitespace
// and backslashes in database DSN strings.
var dbQuote = strings.NewReplacer(`\`, `\\`, `'`, `\'`).Replace

// dbDSN creates a data source name suitable for sql.Open on
// PostgreSQL databases.
func dbDSN(host string, port uint, dbname, user, password string, sslmode string) string {
	return fmt.Sprintf("host=%s port=%d dbname=%s user=%s password=%s sslmode=%s",
		dbQuote(host), port, dbQuote(dbname),
		dbQuote(user), dbQuote(password), sslmode)
}

func opendb(user, password string) (*sql.DB, error) {
	dsn := dbDSN(
		config.Config.DBHost, config.Config.DBPort,
		config.Config.DBName,
		user, password,
		config.Config.DBSSLMode)
	return sql.Open(driver, dsn)
}

const allRoles = `
WITH RECURSIVE cte AS (
   SELECT oid FROM pg_roles WHERE rolname = current_user
   UNION ALL
   SELECT m.roleid
   FROM   cte
   JOIN   pg_auth_members m ON m.member = cte.oid
)
SELECT rolname FROM pg_roles
WHERE oid IN (SELECT oid FROM cte) AND rolname <> current_user`

func AllOtherRoles(user, password string) ([]string, error) {
	db, err := opendb(user, password)
	if err != nil {
		return nil, err
	}
	defer db.Close()
	rows, err := db.Query(allRoles)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	roles := []string{} // explicit empty by intention.

	for rows.Next() {
		var role string
		if err := rows.Scan(&role); err != nil {
			return nil, err
		}
		roles = append(roles, role)
	}
	return roles, rows.Err()
}