AdminInfo.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace app\admin\controller\routine;
  3. use Exception;
  4. use app\common\controller\Backend;
  5. use think\db\exception\PDOException;
  6. use think\exception\ValidateException;
  7. use think\facade\Db;
  8. class AdminInfo extends Backend
  9. {
  10. protected $model = null;
  11. // 排除字段
  12. protected $preExcludeFields = ['username', 'lastlogintime', 'password', 'salt', 'status'];
  13. // 输出字段
  14. protected $authAllowFields = ['id', 'username', 'nickname', 'avatar', 'email', 'mobile', 'motto', 'lastlogintime'];
  15. public function initialize()
  16. {
  17. parent::initialize();
  18. $this->auth->setAllowFields($this->authAllowFields);
  19. $this->model = $this->auth->getAdmin();
  20. }
  21. public function index()
  22. {
  23. $info = $this->auth->getInfo();
  24. $this->success('', [
  25. 'info' => $info
  26. ]);
  27. }
  28. public function edit($id = null)
  29. {
  30. $row = $this->model->find($id);
  31. if (!$row) {
  32. $this->error(__('Record not found'));
  33. }
  34. if ($this->request->isPost()) {
  35. $data = $this->request->post();
  36. if (!$data) {
  37. $this->error(__('Parameter %s can not be empty', ['']));
  38. }
  39. if (isset($data['avatar']) && $data['avatar']) {
  40. $row->avatar = $data['avatar'];
  41. if ($row->save()) {
  42. $this->success(__('Avatar modified successfully!'));
  43. }
  44. }
  45. // 数据验证
  46. if ($this->modelValidate) {
  47. try {
  48. $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  49. $validate = new $validate;
  50. $validate->scene('info')->check($data);
  51. } catch (ValidateException $e) {
  52. $this->error($e->getMessage());
  53. }
  54. }
  55. if (isset($data['password']) && $data['password']) {
  56. $this->model->resetPassword($this->auth->id, $data['password']);
  57. }
  58. $data = $this->excludeFields($data);
  59. $result = false;
  60. Db::startTrans();
  61. try {
  62. $result = $row->save($data);
  63. Db::commit();
  64. } catch (PDOException|Exception $e) {
  65. Db::rollback();
  66. $this->error($e->getMessage());
  67. }
  68. if ($result !== false) {
  69. $this->success(__('Update successful'));
  70. } else {
  71. $this->error(__('No rows updated'));
  72. }
  73. }
  74. }
  75. }