diff pkg/auth/opendb.go @ 1341:a0892b578553

Added comments how to use the impersonating database connections from the session middleware.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Mon, 26 Nov 2018 10:45:51 +0100
parents cabf4789e02b
children 7cccf7fef3e8
line wrap: on
line diff
--- a/pkg/auth/opendb.go	Mon Nov 26 10:32:37 2018 +0100
+++ b/pkg/auth/opendb.go	Mon Nov 26 10:45:51 2018 +0100
@@ -27,10 +27,14 @@
 )
 
 var (
+	// ErrNoMetamorphUser is returned if no metamorphic user is configured.
 	ErrNoMetamorphUser = errors.New("No metamorphic user configured")
-	ErrNotLoggedIn     = errors.New("Not logged in")
+	// ErrNotLoggedIn is returned if there is the user is not logged in.
+	ErrNotLoggedIn = errors.New("Not logged in")
 )
 
+// OpenDB opens up a database connection with a given username and password.
+// The other credentials are taken from the configuration.
 func OpenDB(user, password string) (*sql.DB, error) {
 
 	// To ease SSL config ride a bit on parsing.
@@ -74,7 +78,7 @@
 	return db, nil
 }
 
-func MetamorphConn(ctx context.Context, user string) (*sql.Conn, error) {
+func metamorphConn(ctx context.Context, user string) (*sql.Conn, error) {
 	db, err := mm.open()
 	if err != nil {
 		return nil, err
@@ -102,6 +106,8 @@
 WHERE oid IN (SELECT oid FROM cte) AND rolname <> current_user
 AND EXISTS (SELECT 1 FROM users.list_users WHERE username = current_user)`
 
+// AllOtherRoles loggs in as user with password and returns a list
+// of all roles the logged in user has in the system.
 func AllOtherRoles(user, password string) (Roles, error) {
 	db, err := OpenDB(user, password)
 	if err != nil {
@@ -126,8 +132,12 @@
 	return roles, rows.Err()
 }
 
+// RunAs runs a given function fn with a database connection impersonated
+// as the given role.
+// To make this work a metamorphic user has to be configured in
+// the system configuration.
 func RunAs(ctx context.Context, role string, fn func(*sql.Conn) error) error {
-	conn, err := MetamorphConn(ctx, role)
+	conn, err := metamorphConn(ctx, role)
 	if err != nil {
 		return err
 	}
@@ -135,6 +145,8 @@
 	return fn(conn)
 }
 
+// RunAsSessionUser is a convinience wrapper araound which extracts
+// the logged in user from a session and calls RunAs with it.
 func RunAsSessionUser(req *http.Request, fn func(*sql.Conn) error) error {
 	token, ok := GetToken(req)
 	if !ok {