- Как работать с пользователями в PostgreSQL
- Создание нового пользователя
- 1. Создание пользователя
- 2. Назначение прав на использование базы данных
- 3. Настройка файла pg_hba.conf
- 4. Проверка
- Настройка прав доступа к базе с помощью групп
- Редактирование пользователя
- 1. Смена пароля
- Удаление пользователей и групп
- Назначение особых прав пользователям PostgreSQL
- Учетная запись для резервного копирования
- Графический интерфейс
- CREATE USER
- Synopsis
- Description
- Parameters
- Notes
- Examples
- Compatibility
- How to manage PostgreSQL databases and users from the command line
- Creating PostgreSQL users
- Creating PostgreSQL databases
- Adding an existing user to a database
- Deleting PostgreSQL databases
- Deleting PostgreSQL users
- Creating user, database and adding access on PostgreSQL
- Creating user
- Creating Database
- Giving the user a password
- Granting privileges on database
- Doing purely via psql
Как работать с пользователями в PostgreSQL
Часть нижеописанных операций нужно выполнять в командной оболочке PostgreSQL. Она может быть запущена от пользователя postgres — чтобы войти в систему от данного пользователя, вводим:
* если система выдаст ошибку, связанную с нехваткой прав, сначала повышаем привилегии командой sudo su или su.
Теперь запускаем командную оболочку PostgreSQL:
$ psql -Upostgres template1
* в данном примере, вход выполняется от учетной записи postgres к шаблонной базе template1.
Для просмотра всех пользователей СУБД:
=# select * from pg_user;
Создание нового пользователя
Для того, чтобы была возможность подключения к СУБД PostgreSQL от нового пользователя, необходимо создать данного пользователя, назначить ему права, выполнить настройку файла pg_hba.conf.
1. Создание пользователя
а) Добавление новой роли (пользователя) из оболочки SQL:
=# CREATE USER dmosk WITH PASSWORD ‘myPassword’;
* в примере создана роль dmosk с паролем myPassword.
б) Добавление новой роли (пользователя) из командной строки Linux:
createuser -P dmosk
2. Назначение прав на использование базы данных
Даем права на базу командой:
=# GRANT ALL PRIVILEGES ON DATABASE «database1» to dmosk;
Теперь подключаемся к базе, к которой хотим дать доступ:
* в примере подсоединимся к базе с названием database1.
а) Так мы добавим все права на использование всех таблиц в базе database1 учетной записи dmosk:
database1=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO «dmosk»;
* в большинстве случаев, используется схема по умолчанию public. Но администратор может создать новую схему. Это нужно учитывать при назначении прав.
б) Также можно дать доступ к базе для определенных таблиц:
database1=# GRANT ALL PRIVILEGES ON TABLE table1 IN SCHEMA public TO «dmosk»;
* в данном примере мы даем права на таблицу table1.
Выходим из SQL-оболочки:
3. Настройка файла pg_hba.conf
Для возможности подключиться к СУБД от созданного пользователя, необходимо проверить настройки прав в конфигурационном файле pg_hba.conf.
Для начала смотрим путь расположения данных для PostgreSQL:
В ответ мы получим, что-то на подобие:
* в данном примере /var/lib/pgsql/9.6/data/ — путь расположения конфигурационных файлов.
Добавляем права на подключение нашему созданному пользователю:
.
# IPv4 local connections:
host all dmosk 127.0.0.1/32 md5
.
* в данном примере мы разрешили подключаться пользователю dmosk ко всем базам на сервере (all) от узла 127.0.0.1 (localhost) с требованием пароля (md5).
* необходимо, чтобы данная строка была выше строки, которая прописана по умолчанию
host all all 127.0.0.1/32 ident.
После перезапускаем службу:
systemctl restart postgresql-9.6
* в данном примере установлен postgresql версии 9.6, для разных версий на разных операционных системах команды для перезапуска сервиса могут быть разные.
4. Проверка
Для теста пробуем подключиться к Postgre с помощью созданного пользователя:
psql -Udmosk template1 -h127.0.0.1
Настройка прав доступа к базе с помощью групп
Сначала создадим групповую роль:
=# CREATE ROLE «myRole» NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION;
* данной командой создана группа myRole с минимальными правами.
Теперь добавим ранее созданного пользователя dmosk в эту группу:
=# GRANT «myRole» TO dmosk;
Подключимся к базе данных, для которой хотим настроить права
и предоставим все права для группы myRole всем таблицам базы database1
database1=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO GROUP «myRole»;
Редактирование пользователя
1. Смена пароля
Рассмотрим несколько примеров смены пароля пользователя.
=# ALTER USER postgres PASSWORD ‘password’
* в данном примере мы зададим пароль password для пользователя postgres.
С запросов ввода пароля:
* после ввода данной команды система потребует дважды ввести пароль для пользователя (в нашем примере, postgres).
Из командной строки Linux:
sudo -u postgres psql -U postgres -d postgres -c «ALTER USER postgres PASSWORD ‘password'»
* по сути, мы выполняем также запрос в оболочке sql.
Удаление пользователей и групп
Удаление пользователя выполняется следующей командой:
=# DROP USER dmosk;
database1=# REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM «dmosk»;
* обратите внимание, данный запрос отличается от предоставления прав двумя моментами: 1) вместо GRANT пишем REVOKE; 2) вместо TO «dmosk» пишем FROM «dmosk»;
Назначение особых прав пользователям PostgreSQL
Помимо ALL PRIVILEGES можно выдавать права на особые операции, например:
=# GRANT SELECT, UPDATE, INSERT ON ALL TABLES IN SCHEMA public TO «dmosk»;
* команда позволит выдать права на получение данных, их обновление и добавление. Другие операции, например, удаление будут запрещены для пользователя dmosk.
Назначение прав для определенной таблицы:
database1=# GRANT ALL PRIVILEGES ON table_users TO «dmosk»;
* в данном примере мы предоставим все права на таблицу table_users в базе данных database1;
Учетная запись для резервного копирования
Для выполнения резервного копирования лучше всего подключаться к базе с минимальными привилегиями.
Сначала создаем роль, которую будем использовать для выполнения резервного копирования:
=# CREATE USER bkpuser WITH PASSWORD ‘bkppasswd’;
* мы создадим учетную запись bkpuser с паролем bkppasswd.
Предоставляем права на подключения к базе
=# GRANT CONNECT ON DATABASE database TO bkpuser;
* в данном примере к базе database.
Подключаемся к базе (в нашем примере database):
Даем права на все последовательности в схеме:
=# GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO bkpuser;
* мы дали права для схемы public. Это схема является схемой по умолчанию, но в вашем случае она может быть другой. В таком случае, подставляем свое значение.
Графический интерфейс
Иногда проще воспользоваться программой для выставления прав и работы с PostgreSQL. Могу посоветовать приложение pgAdmin. Оно позволит в оконном режиме не только создать и удалить пользователей, но и полноценно работать с СУБД.
Источник
CREATE USER
Synopsis
Description
CREATE USER adds a new user to a PostgreSQL database cluster. Refer to Chapter 17 and Chapter 19 for information about managing users and authentication. You must be a database superuser to use this command.
Parameters
The name of the new user.
The SYSID clause can be used to choose the PostgreSQL user ID of the new user. This is normally not necessary, but may be useful if you need to recreate the owner of an orphaned object.
If this is not specified, the highest assigned user ID plus one (with a minimum of 100) will be used as default.
These clauses define a user’s ability to create databases. If CREATEDB is specified, the user being defined will be allowed to create his own databases. Using NOCREATEDB will deny a user the ability to create databases. If not specified, NOCREATEDB is the default.
These clauses determine whether a user will be permitted to create new users himself. CREATEUSER will also make the user a superuser, who can override all access restrictions. If not specified, NOCREATEUSER is the default.
A name of an existing group into which to insert the user as a new member. Multiple group names may be listed.
Sets the user’s password. If you do not plan to use password authentication you can omit this option, but then the user won’t be able to connect if you decide to switch to password authentication. The password can be set or changed later, using ALTER USER.
These key words control whether the password is stored encrypted in the system catalogs. (If neither is specified, the default behavior is determined by the configuration parameter password_encryption.) If the presented password string is already in MD5-encrypted format, then it is stored encrypted as-is, regardless of whether ENCRYPTED or UNENCRYPTED is specified (since the system cannot decrypt the specified encrypted password string). This allows reloading of encrypted passwords during dump/restore.
Note that older clients may lack support for the MD5 authentication mechanism that is needed to work with passwords that are stored encrypted.
The VALID UNTIL clause sets an absolute time after which the user’s password is no longer valid. If this clause is omitted the password will be valid for all time.
Notes
Use ALTER USER to change the attributes of a user, and DROP USER to remove a user. Use ALTER GROUP to add the user to groups or remove the user from groups.
PostgreSQL includes a program createuser that has the same functionality as CREATE USER (in fact, it calls this command) but can be run from the command shell.
The VALID UNTIL clause defines an expiration time for a password only, not for the user account per se. In particular, the expiration time is not enforced when logging in using a non-password-based authentication method.
Examples
Create a user with no password:
Create a user with a password:
Create a user with a password that is valid until the end of 2004. After one second has ticked in 2005, the password is no longer valid.
Create an account where the user can create databases:
Compatibility
The CREATE USER statement is a PostgreSQL extension. The SQL standard leaves the definition of users to the implementation.
Источник
How to manage PostgreSQL databases and users from the command line
This article describes how to add and delete PostgreSQL databases and users from the command line.
Creating PostgreSQL users
A default PostgresSQL installation always includes the postgres superuser. Initially, you must connect to PostgreSQL as the postgres user until you create other users (which are also referred to as roles).
To create a PostgreSQL user, follow these steps:
- At the command line, type the following command as the server’s root user:
You can now run commands as the PostgreSQL superuser. To create a user, type the following command:
Creating PostgreSQL databases
To create a PostgreSQL database, follow these steps:
- At the command line, type the following command as the server’s root user:
You can now run commands as the PostgreSQL superuser. To create a database, type the following command. Replace user with the name of the user that you want to own the database, and replace dbname with the name of the database that you want to create:
- PostgreSQL users that have permission to create databases can do so from their own accounts by typing the following command, where dbname is the name of the database to create:
Adding an existing user to a database
To grant an existing user privileges to a database, follow these steps:
- Run the psql program as the database’s owner, or as the postgres superuser.
- Type the following command. Replace permissions with the permissions you want to grant, dbname with the name of the database, and username with the user:
Deleting PostgreSQL databases
Similar to the createdb command for creating databases, there is the dropdb command for deleting databases. To delete a database, you must be the owner or have superuser privileges.
Type the following command, replacing dbname with the name of the database that you want to delete:
Deleting PostgreSQL users
Similar to the createuser command for creating users, there is the dropuser command for deleting users.
To delete a specific user, type the following command. Replace username with the name of the user that you want to delete:
If the user owns any databases or other objects, you cannot drop the user. Instead, you receive an error message similar to the following:
You should change the database’s owner (or drop the database entirely), and then you can drop the user.
Источник
Creating user, database and adding access on PostgreSQL
NOTE : Right off the bat — this is valid as on March 2017, running on Ubuntu 16.04.2, with PostgreSQL 9.6
One nice thing about PGSQL is it comes with some utility binaries like createuser and createdb. So we will be making use of that.
As the default configuration of Postgres is, a user called postgres is made on and the user postgres has full superadmin access to entire PostgreSQL instance running on your OS.
The above command gets you the psql command line interface in full admin mode.
In the following commands, keep in mind the are to denote variables you have to set yourself. In the actual command, omit the <>
Creating user
Creating Database
Giving the user a password
Granting privileges on database
And yeah, that should be pretty much it !
Doing purely via psql
Your OS might not have the createuser or createdb binaries, or you may, for some reason want to do it purely via psql, then these are the three magic commands —
Obligatory shameless self-plug :
I am one of the co-founders of Coding Blocks — A Software Programming bootcamp, based out of New Delhi, India. Among other things, we teach Full Stack Web Development using NodeJS, via both classroom programmes, as well as online classes. You can follow our Medium to find more articles on Android and Web development.
Источник