MySQL回收某一授權

壹頁書發表於2015-11-16
建立測試表
create table t1(id int);
create table t2(id int);
create table t3(id int);
create table t4(msg varchar(100));

如果授權的時候圖省事兒,使用萬用字元授權.
grant select,insert,update,delete on mvbox.* to 'xx'@'localhost' identified by 'xx';

如果以後需要回收某一張表許可權的時候,就會比較麻煩.
mysql> show grants for xx@'localhost';
+-----------------------------------------------------------------------------------------------------------+
| Grants for xx@localhost                                                                                   |
+-----------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'xx'@'localhost' IDENTIFIED BY PASSWORD '*B30134364A2D14319904C2C807363CF2C81ABD5B' |
| GRANT SELECT, INSERT, UPDATE, DELETE ON `mvbox`.* TO 'xx'@'localhost'                                     |
+-----------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql> revoke insert on mvbox.t1 from xx@'localhost';
ERROR 1147 (42000): There is no such grant defined for user 'xx' on host 'localhost' on table 't1'
mysql>

因為授權是使用的萬用字元,回收也需要使用萬用字元.

如果需要回收t1表的insert許可權,可以使用如下的觸發器.
  1. delimiter //
  2. CREATE TRIGGER tri1 BEFORE INSERT ON t1 FOR EACH ROW
  3. BEGIN
  4.     DECLARE msg varchar(100);
  5.     DECLARE cu varchar(40);
  6.     set cu=(select substring_index((select user()),'@',1)) ;
  7.     IF cu='xx' THEN
  8.             set msg = concat(cu,"You have no right to operate data!please connect DBAs");
  9.             SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = msg;
  10.     END IF;
  11. END;
  12. //
  13. delimiter ;
這時,以xx登入,insert t1表則報錯如下
mysql> insert into t1 values(10);
ERROR 1644 (HY000): xx You have no right to operate data!please connect DBAs


這裡需要注意的是current_user,user函式,在觸發器呼叫的時候,返回的內容是不一樣的.
刪除原來的觸發器,新建一個觸發器測試

  1. drop trigger tri1;
  2. delimiter //
  3. CREATE TRIGGER `tri2` BEFORE INSERT ON `t1` FOR EACH ROW
  4. BEGIN
  5.     insert into t4 values(concat(current_user(),',',user(),',',session_user()));
  6. END;
  7. //
  8. delimiter ;
使用xx使用者登入,執行如下命令
mysql> insert into t1 values(10);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t4;
+------------------------------------------+
| msg                                      |
+------------------------------------------+
| root@localhost,xx@localhost,xx@localhost |
+------------------------------------------+
1 row in set (0.00 sec)

可以發現在觸發器中,current_user()返回的是觸發器的定義者.
而user(),session_user()才是連線的使用者.

mysql>

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-1839760/,如需轉載,請註明出處,否則將追究法律責任。

相關文章