Esempio n. 1
0
 /**
  * @Request({"id": "int", "user": "******", "password", "roles": "array"}, csrf=true)
  * @Response("json")
  */
 public function saveAction($id, $data, $password, $roles = null)
 {
     try {
         // is new ?
         if (!($user = $this->users->find($id))) {
             if ($id) {
                 throw new Exception(__('User not found.'));
             }
             if (empty($password)) {
                 throw new Exception(__('Password required.'));
             }
             $user = new User();
             $user->setRegistered(new \DateTime());
         }
         $self = $this->user->getId() == $user->getId();
         if ($self && $user->isBlocked()) {
             throw new Exception(__('Unable to block yourself.'));
         }
         $name = trim(@$data['username']);
         $email = trim(@$data['email']);
         if (strlen($name) < 3 || !preg_match('/^[a-zA-Z0-9_\\-]+$/', $name)) {
             throw new Exception(__('Username is invalid.'));
         }
         if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
             throw new Exception(__('Email is invalid.'));
         }
         if ($this->users->where(['id <> :id'], compact('id'))->where(function ($query) use($name) {
             $query->orWhere(['username = :username', 'email = :username'], ['username' => $name]);
         })->first()) {
             throw new Exception(__('Username not available.'));
         }
         if ($this->users->where(['id <> :id'], compact('id'))->where(function ($query) use($email) {
             $query->orWhere(['username = :email', 'email = :email'], ['email' => $email]);
         })->first()) {
             throw new Exception(__('Email not available.'));
         }
         $data['username'] = $name;
         $data['email'] = $email;
         if ($email != $user->getEmail()) {
             $user->set('verified', false);
         }
         if (!empty($password)) {
             $user->setPassword($this['auth.password']->hash($password));
         }
         if ($this->user->hasAccess('system: manage user permissions')) {
             if ($self && $user->hasRole(RoleInterface::ROLE_ADMINISTRATOR) && (!$roles || !in_array(RoleInterface::ROLE_ADMINISTRATOR, $roles))) {
                 $roles[] = RoleInterface::ROLE_ADMINISTRATOR;
             }
             $user->setRoles($roles ? $this->roles->query()->whereIn('id', $roles)->get() : []);
         }
         $this->users->save($user, $data);
         return ['message' => $id ? __('User saved.') : __('User created.'), 'user' => $this->getInfo($user)];
     } catch (Exception $e) {
         return ['error' => $e->getMessage()];
     }
 }