暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

删除用户风险大,试试锁定用户

digoal 2019-05-08
731

作者

digoal

日期

2019-05-08

标签

PostgreSQL , 权限 , 数据库 , owner , 关系


背景

PostgreSQL 对象属于且必须属于一个用户,如果要把这个用户删掉,首先要删除这个用户所拥有的对象,或者把这些对象的OWNER改成其他用户。

删除用户时,这个用户不能拥有数据库中的任何对象。

如果还有属于这个用户的对象,会报错,例如:

postgres=# drop role r4; ERROR: 2BP01: role "r4" cannot be dropped because some objects depend on it DETAIL: owner of view v_ecs_china owner of tablespace tbs_8001 owner of database _abc owner of table bb owner of table b LOCATION: DropRole, user.c:1064

r4这个用户,还有tablespace, database, view, table等对象属于R4。所以不允许删除。

那么你可能会问,难道不能直接删除用户,而不清理对象吗?显然不能,因为用户被删除,这些对象属于谁呢?对象没有默认的OWNER。

又或者删除用户时,自动删除关联对象呢?也不能,PG暂时没有提供这个语法,可能出于安全考虑。

postgres=# drop role sup cascade; ERROR: syntax error at or near "cascade" LINE 1: drop role sup cascade; ^

但是很多对象删除带了cascade语法,删除级联对象,例如drop schema。

```
postgres=# drop schema ora;
ERROR: 2BP01: cannot drop schema ora because other objects depend on it
DETAIL: foreign table ora.tbl123 depends on schema ora
rule r1 on table tbl123 depends on foreign table ora.tbl123
rule r2 on table tbl123 depends on foreign table ora.tbl123
rule r3 on table tbl123 depends on foreign table ora.tbl123
HINT: Use DROP ... CASCADE to drop the dependent objects too.
LOCATION: reportDependentObjects, dependency.c:971

drop schema ora cascade; 就可以删除ora以及这个schema下面的所有对象。
```

实际上如果业务上只是不想让这个用户再连接数据库,可以用其他方法。例如锁定用户

锁定用户例子

1、锁定例子

```
1、标记用户被锁定
comment on role r4 is 'locked by digoal';

2、修改用户的连接限制为0
alter role r4 connection limit 0;

3、不允许用户登陆
alter role r4 nologin;

4、清密码(可选,已经不能登录了,不清理密码也可以,当然清理也可以)
alter role r4 encrypted password '';

5、将用户名重命名(可选)
alter role r4 renmae to _droped_r4;
```

锁定后,用户无法使用原来的账号登陆,也无法使用重命名后的账号登陆

```
digoal@pg11-test-> psql postgres r4
psql: FATAL: role "r4" does not exist

digoal@pg11-test-> psql postgres _droped_r4
psql: FATAL: role "_droped_r4" is not permitted to log in
```

2、解锁例子

```
1、重命名用户为原始用户名(可选)
alter role _droped_r4 rename to r4;

2、删除注释
comment on role r4 is '';

3、修改连接限制为不限
alter role r4 connection limit -1;

4、允许用户登陆
alter role r4 login;

5、重新修改密码(可选,如果之前清空了密码,那么这里要重新设置密码)
alter role r4 encrypted password 'new pwd';
```

PostgreSQL 许愿链接

您的愿望将传达给PG kernel hacker、数据库厂商等, 帮助提高数据库产品质量和功能, 说不定下一个PG版本就有您提出的功能点. 针对非常好的提议,奖励限量版PG文化衫、纪念品、贴纸、PG热门书籍等,奖品丰富,快来许愿。开不开森.

9.9元购买3个月阿里云RDS PostgreSQL实例

PostgreSQL 解决方案集合

德哥 / digoal's github - 公益是一辈子的事.

digoal's wechat

文章转载自digoal,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论