3v-Hosting Blog

Adding a new user to PostgreSQL

Administration

6 min read


PostgreSQL is the powerful, open-source relational database management system (RDBMS) you need for extensive capabilities for data storage, retrieval, and management. In any multi-user environment, you must add and manage users effectively to maintain security, grant appropriate privileges, and ensure smooth database operations. This article provides a definitive, step-by-step guide to adding a new user in PostgreSQL, exploring various perspectives and practical scenarios.

 

 

 

Understanding PostgreSQL Roles

 

PostgreSQL employs a role-based access control system. Roles in PostgreSQL can act as users or groups, depending on how they are configured. Every database operation performed by a user is executed within the scope of their assigned role. It is essential to understand roles before creating a new user, as a user is essentially a role with the LOGIN attribute.

Roles can have different permissions, such as:

    - The ability to create databases (CREATEDB).
    - The privilege to create other roles (CREATEROLE).
    - The ability to access the database server (LOGIN).

When adding a new user, it's important to consider the role's required permissions and limitations to ensure secure and efficient database access.

 

 

 

Preparing the Environment

 

Before adding a new user, ensure you have access to the PostgreSQL server with administrative privileges. Administrative roles, such as postgres (default superuser), have the necessary permissions to manage roles and privileges.

To log in as the postgres user, use the following command:

    sudo -i -u postgres

Once logged in, access the PostgreSQL command-line interface (psql) by executing:

    psql

You are now ready to add a new user.

 

 

 

Adding a New User in PostgreSQL

 

To create a new user, PostgreSQL provides the CREATE ROLE command, which can be used in conjunction with specific attributes. A new user must have the LOGIN attribute to access the database.

Here’s a basic example of adding a new user:

    CREATE ROLE new_user WITH LOGIN PASSWORD 'secure_password';


    new_user: Replace this with the username you want to create.
    PASSWORD: Always choose a strong password to ensure security.


Alternatively, you can use the shorthand command:

    CREATE USER new_user WITH PASSWORD 'secure_password';

The CREATE USER command is a simplified version of CREATE ROLE that automatically includes the LOGIN attribute.

 


 

Other useful articles in our Blog:


    - Creating a New User and Granting Permissions in MySQL

    - A Comprehensive Guide: How to Find and Optimize Slow Queries in MySQL

    - How to remotely connect to MySQL

    - Bash If Statement: Syntax, Variations, Use Cases, Commands, and More!

 



Assigning Privileges to the New User

 

By default, a new user has no permissions on any database. To allow the user to interact with a specific database, you must explicitly grant privileges.

Grant Database Access: Assign the new user access to a database:

    GRANT CONNECT ON DATABASE example_db TO new_user;


Grant Schema Access: If the database has multiple schemas, provide access to a specific schema:

    GRANT USAGE ON SCHEMA public TO new_user;


Grant Table-Level Privileges: Enable the user to interact with tables:

    GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO new_user;


Grant Future Privileges: To ensure the user has privileges on tables created in the future:

    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO new_user;

Assigning the least privileges necessary is a critical practice in database security to reduce potential risks.

 

 

 

Best Practices for User Management in PostgreSQL

 

Use Group Roles: Instead of managing individual user privileges, create group roles with predefined permissions and assign users to these groups. For example:

    CREATE ROLE dev_team WITH LOGIN PASSWORD 'team_password';
    GRANT CONNECT, TEMPORARY ON DATABASE example_db TO dev_team;


Add individual users to the group:

    GRANT dev_team TO new_user;


Rotate Passwords Regularly: Enforce regular password updates to minimize security vulnerabilities.

    ALTER USER new_user WITH PASSWORD 'new_secure_password';


Audit User Activity: Use PostgreSQL's logging features to monitor user activity and ensure compliance with access policies.
Revoke Unnecessary Privileges: Periodically review and revoke unnecessary privileges to prevent privilege creep:

    REVOKE SELECT ON ALL TABLES IN SCHEMA public FROM new_user;

 

 

 

Automating User Creation with Scripts

 

For environments where user creation is frequent, automation can save time and ensure consistency. Below is an example of a simple script to add a new user:

    #!/bin/bash
    USER_NAME=$1
    PASSWORD=$2
    DATABASE=$3

    psql -U postgres -c "CREATE USER $USER_NAME WITH PASSWORD '$PASSWORD';"
    psql -U postgres -c "GRANT CONNECT ON DATABASE $DATABASE TO $USER_NAME;"


Save this script as create_user.sh and run it with the necessary arguments:

    bash create_user.sh new_user secure_password example_db

This approach is particularly useful for DevOps pipelines and CI/CD workflows.

 

 

 

Common Errors and Troubleshooting

 

    Error: role "new_user" does not exist: Ensure the user has been created and assigned the LOGIN attribute.
    Error: permission denied for database: Verify that the user has the appropriate CONNECT privilege for the database.
    Error: could not connect to server: Check that PostgreSQL is running and accepting connections on the specified port.

 

 

 

Conclusion

Adding a new user in PostgreSQL is a fundamental task that requires careful consideration of role management, privilege assignment, and security best practices. By understanding the role-based architecture of PostgreSQL and following structured processes, administrators can effectively manage users while ensuring database integrity and security. Mastering user management is essential for efficient database administration, whether you're working in a small development environment or a large-scale enterprise system.