Mercurial > gemma
view pkg/auth/opendb.go @ 471:1b08432a0e5d
Cosmetics.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Thu, 23 Aug 2018 10:11:50 +0200 |
parents | ff9dbe14f033 |
children | b2dc9c2f69e0 |
line wrap: on
line source
package auth import ( "database/sql" "errors" "github.com/jackc/pgx" "github.com/jackc/pgx/stdlib" "gemma.intevation.de/gemma/pkg/config" ) func OpenDB(user, password string) (*sql.DB, error) { // To ease SSL config ride a bit on parsing. cc, err := pgx.ParseConnectionString("sslmode=" + config.DBSSLMode()) if err != nil { return nil, err } // Do the rest manually to allow whitespace in user/password. cc.Host = config.DBHost() cc.Port = uint16(config.DBPort()) cc.User = user cc.Password = password cc.Database = config.DBName() return stdlib.OpenDB(cc), nil } 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 AND EXISTS (SELECT 1 FROM users.list_users WHERE username = current_user)` var ErrNoMetamorphUser = errors.New("No metamorphic user configured") func AllOtherRoles(user, password string) (Roles, 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 := Roles{} // 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() } func RunAs(role string, fn func(*sql.DB) error) error { user := config.MetamorphDBUser() if user == "" { return ErrNoMetamorphUser } db, err := OpenDB(user, config.MetamorhpDBPassword()) if err != nil { return nil } defer db.Close() if _, err = db.Exec(`SELECT public.setrole_plan($1)`, role); err == nil { err = fn(db) } return err }