Inheritance: implements Pagekit\Auth\UserInterface, implements JsonSerializable, use trait Pagekit\System\Model\DataModelTrait, use trait UserModelTrait
Exemplo n.º 1
0
 /**
  * @Request({"user", "key"})
  */
 public function activateAction($username, $activation)
 {
     $message = '';
     if (empty($username) || empty($activation) || !($user = User::where(['username' => $username, 'activation' => $activation, 'status' => User::STATUS_BLOCKED, 'login IS NULL'])->first())) {
         return AuthController::messageView(['message' => __('Invalid key.'), 'success' => false]);
     }
     if ($admin = $this->module->config('registration') == 'approval' and !$user->get('verified')) {
         $user->activation = App::get('auth.random')->generateString(32);
         $this->sendApproveMail($user);
         $message = __('Your email has been verified. Once an administrator approves your account, you will be notified by email.');
     } else {
         $user->set('verified', true);
         $user->status = User::STATUS_ACTIVE;
         $user->activation = '';
         $this->sendWelcomeEmail($user);
         if ($admin) {
             $message = __('The user\'s account has been activated and the user has been notified about it.');
         } else {
             $message = __('Your account has been activated.');
         }
     }
     $user->save();
     App::message()->success($message);
     return App::redirect('@user/login');
 }
Exemplo n.º 2
0
 /**
  * @Request({"user", "key"})
  */
 public function confirmAction($username = "", $activation = "")
 {
     if (empty($username) || empty($activation) || !($user = User::where(compact('username', 'activation'))->first())) {
         return $this->messageView(__('Invalid key.'), $success = false);
     }
     if ($user->isBlocked()) {
         return $this->messageView(__('Your account has not been activated or is blocked.'), $success = false);
     }
     $error = '';
     if ('POST' === App::request()->getMethod()) {
         try {
             if (!App::csrf()->validate()) {
                 throw new Exception(__('Invalid token. Please try again.'));
             }
             $password = App::request()->request->get('password');
             if (empty($password)) {
                 throw new Exception(__('Enter password.'));
             }
             if ($password != trim($password)) {
                 throw new Exception(__('Invalid password.'));
             }
             $user->password = App::get('auth.password')->hash($password);
             $user->activation = null;
             $user->save();
             App::message()->success(__('Your password has been reset.'));
             return App::redirect('@user/login');
         } catch (Exception $e) {
             $error = $e->getMessage();
         }
     }
     return ['$view' => ['title' => __('Reset Confirm'), 'name' => 'system/user/reset-confirm.php'], 'username' => $username, 'activation' => $activation, 'error' => $error];
 }
Exemplo n.º 3
0
 /**
  * {@inheritdoc}
  */
 public function findByCredentials(array $credentials)
 {
     if (isset($credentials['password'])) {
         unset($credentials['password']);
     }
     return User::where($credentials)->first();
 }
 /**
  * @Request({"user": "******"}, csrf=true)
  */
 public function saveAction($data)
 {
     $user = App::user();
     if (!$user->isAuthenticated()) {
         App::abort(404);
     }
     try {
         $user = User::find($user->id);
         if ($password = @$data['password_new']) {
             if (!App::auth()->getUserProvider()->validateCredentials($user, ['password' => @$data['password_old']])) {
                 throw new Exception(__('Invalid Password.'));
             }
             if (trim($password) != $password || strlen($password) < 3) {
                 throw new Exception(__('Invalid Password.'));
             }
             $user->password = App::get('auth.password')->hash($password);
         }
         if (@$data['email'] != $user->email) {
             $user->set('verified', false);
         }
         $user->name = @$data['name'];
         $user->email = @$data['email'];
         $user->validate();
         $user->save();
         return ['message' => 'success'];
     } catch (Exception $e) {
         App::abort(400, $e->getMessage());
     }
 }
 /**
  * @Access("userprofile: view profiles")
  * @Route("/")
  * @Route("/page/{page}", name="page", requirements={"page" = "\d+"})
  * @Request({"filter": "array", "page":"int", "limit":"int"})
  */
 public function indexAction($filter = [], $page = 1, $limit = 0)
 {
     $userprofile = App::module('bixie/userprofile');
     $node = App::node();
     $query = User::query();
     $filter = array_merge(array_fill_keys(['search', 'order', 'access'], ''), $filter);
     extract($filter, EXTR_SKIP);
     $query->where(['status' => User::STATUS_ACTIVE, 'login IS NOT NULL']);
     if ($search) {
         $query->where(function ($query) use($search) {
             $query->orWhere(['username LIKE :search', 'name LIKE :search', 'email LIKE :search'], ['search' => "%{$search}%"]);
         });
     }
     if ($roles = $node->get('show_roles')) {
         $query->whereInSet('roles', $roles);
     }
     if (preg_match('/^(username|name|email|registered|login)\\s(asc|desc)$/i', $order, $match)) {
         $order = $match;
     } else {
         $order = [1 => 'username', 2 => 'asc'];
     }
     $default = $userprofile->config('list.profiles_per_page');
     $limit = min(max(0, $limit), $default) ?: $default;
     $count = $query->count('id');
     $total = ceil($count / $limit);
     $page = max(1, min($total, $page));
     $profileUsers = array_map(function ($user) {
         return ProfileUser::load($user);
     }, $query->offset(($page - 1) * $limit)->limit($limit)->orderBy($order[1], $order[2])->get());
     $title = $node->get('page_title') ?: __('User Profiles');
     return ['$view' => ['title' => $title, 'name' => 'bixie/userprofile/profiles.php'], '$data' => [], 'config' => $userprofile->config(), 'profileUsers' => $profileUsers, 'total' => $total, 'page' => $page, 'title' => $title, 'search' => $search, 'node' => $node];
 }
Exemplo n.º 6
0
 /**
  * {@inheritdoc}
  */
 public function main(App $app)
 {
     $app['user'] = function ($app) {
         if (!($user = $app['auth']->getUser())) {
             $user = User::create(['roles' => [Role::ROLE_ANONYMOUS]]);
         }
         return $user;
     };
 }
Exemplo n.º 7
0
 /**
  * @Access(admin=true)
  * @Request({"order": "array"})
  */
 public function adminMenuAction($order)
 {
     if (!$order) {
         App::abort(400, __('Missing order data.'));
     }
     $user = User::find(App::user()->id);
     $user->set('admin.menu', $order);
     $user->save();
     return ['message' => __('Order saved.')];
 }
Exemplo n.º 8
0
 /**
  * @Access("user: manage users")
  * @Request({"id": "int"})
  */
 public function editAction($id = 0)
 {
     if (!$id) {
         $user = User::create(['roles' => [Role::ROLE_AUTHENTICATED]]);
     } else {
         if (!($user = User::find($id))) {
             App::abort(404, 'User not found.');
         }
     }
     return ['$view' => ['title' => $id ? __('Edit User') : __('Add User'), 'name' => 'system/user/admin/user-edit.php'], '$data' => ['user' => $user, 'config' => ['statuses' => User::getStatuses(), 'roles' => array_values($this->getRoles($user)), 'emailVerification' => App::module('system/user')->config('require_verification'), 'currentUser' => App::user()->id]]];
 }
 /**
  * @Route("/", methods="GET")
  * @Route("/{id}", methods="GET", requirements={"id"="\d+"})
  */
 public function indexAction($id = 0)
 {
     $self = App::user();
     $userprofile = App::module('bixie/userprofile');
     $id = $id ?: $self->id;
     if (!$self->hasAccess('user: manage users') && $id != $self->id) {
         App::abort(403, 'Insufficient permissions.');
     }
     if (!($user = User::find($id))) {
         App::abort(404, 'User not found.');
     }
     return ['config' => $userprofile->config(), 'fields' => Field::getProfileFields(), 'profilevalues' => Profilevalue::getUserProfilevalues($user), 'user' => ['id' => $user->id, 'username' => $user->username, 'name' => $user->name, 'email' => $user->email]];
 }
Exemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 public function collect()
 {
     if (null === $this->auth) {
         return ['enabled' => false, 'authenticated' => false, 'user_class' => null, 'user' => '', 'roles' => []];
     }
     try {
         $user = $this->auth->getUser();
     } catch (\Exception $e) {
         $user = null;
     }
     if (null === $user) {
         return ['enabled' => true, 'authenticated' => false, 'user_class' => null, 'user' => '', 'roles' => []];
     }
     return ['enabled' => true, 'authenticated' => $user->isAuthenticated(), 'user_class' => get_class($user), 'user' => $user->getUsername(), 'roles' => array_map(function ($role) {
         return $role->name;
     }, User::findRoles($user))];
 }
Exemplo n.º 11
0
 /**
  * {@inheritdoc}
  */
 public static function queryProfileValues($condition, $exact = false)
 {
     /** @var QueryBuilder $query */
     $query = User::where(['status' => User::STATUS_ACTIVE]);
     $query->from('@system_user AS u')->select('u.*');
     $params = [];
     foreach ($condition as $slug => $search) {
         $slg = str_replace('-', '_', $slug);
         $query->leftJoin(sprintf('@userprofile_field AS pf_%s', $slg), sprintf('pf_%1$s.slug = :slug_%1$s', $slg))->leftJoin(sprintf('@userprofile_value AS pv_%s', $slg), sprintf('pv_%1$s.field_id = pf_%1$s.id AND pv_%1$s.user_id = u.id', $slg));
         if ($exact) {
             $query->where(sprintf('pv_%1$s.value = :search_%1$s', $slg));
         } else {
             $query->where(sprintf('pv_%1$s.value LIKE :search_%1$s', $slg));
             $search = "%{$search}%";
         }
         $params["slug_{$slg}"] = $slug;
         $params["search_{$slg}"] = $search;
     }
     $query->params($params);
     return $query;
 }
Exemplo n.º 12
0
 /**
  * {@inheritdoc}
  */
 public function match(array $parameters = [])
 {
     if (isset($parameters['id'])) {
         return $parameters;
     }
     if (!isset($parameters['slug'])) {
         App::abort(404, 'Userprofile not found.');
     }
     $slug_key = App::module('bixie/userprofile')->config('slug_key', 'username');
     $slug = $parameters['slug'];
     $id = false;
     foreach ($this->cacheEntries as $entry) {
         if ($entry[$slug_key] === $slug) {
             $id = $entry['id'];
         }
     }
     if (!$id) {
         switch ($slug_key) {
             case 'id':
                 $user = User::find($slug);
                 break;
             case 'name':
                 $user = User::where(['name' => $slug])->first();
                 break;
             case 'username':
                 $user = User::findByUsername($slug);
                 break;
             default:
                 $user = false;
                 break;
         }
         if (!$user) {
             App::abort(404, 'Userprofile not found.');
         }
         $this->addCache($user);
         $id = $user->id;
     }
     $parameters['id'] = $id;
     return $parameters;
 }
Exemplo n.º 13
0
 /**
  * @Request({"user", "key"})
  */
 public function activateAction($username, $activation)
 {
     if (empty($username) || empty($activation) || !($user = User::where(['username' => $username, 'activation' => $activation, 'login IS NULL'])->first())) {
         App::abort(400, __('Invalid key.'));
     }
     $verifying = false;
     if ($this->module->config('require_verification') && !$user->get('verified')) {
         $user->set('verified', true);
         $verifying = true;
     }
     if ($this->module->config('registration') === 'approval' && $user->status === User::STATUS_BLOCKED && $verifying) {
         $user->activation = App::get('auth.random')->generateString(32);
         $this->sendApproveMail($user);
         $message = __('Your email has been verified. Once an administrator approves your account, you will be notified by email.');
     } else {
         $user->status = User::STATUS_ACTIVE;
         $user->activation = '';
         $this->sendWelcomeEmail($user);
         $message = $verifying ? __('Your account has been activated.') : __('The user\'s account has been activated and the user has been notified about it.');
     }
     $user->save();
     App::message()->success($message);
     return App::redirect('@user/login');
 }
Exemplo n.º 14
0
 /**
  * Updates user's last login time
  */
 public function onUserLogin(LoginEvent $event)
 {
     User::updateLogin($event->getUser());
 }
Exemplo n.º 15
0
 /**
  * @Saved
  */
 public static function saved($event, User $user)
 {
     if (!$user->hasRole(Role::ROLE_AUTHENTICATED)) {
         $user->roles[] = Role::ROLE_AUTHENTICATED;
     }
 }
Exemplo n.º 16
0
}, 'view.scripts' => function ($event, $scripts) use($app) {
    $version = $app->module('bixie/pk-framework')->getVersionKey($app->package('bixie/userprofile')->get('version'));
    $scripts->register('link-userprofile', 'bixie/userprofile:app/bundle/link-userprofile.js', '~panel-link', ['version' => $version]);
    $scripts->register('user-section-userprofile', 'bixie/userprofile:app/bundle/user-section-userprofile.js', ['~user-edit', 'bixie-fieldtypes'], ['version' => $version]);
}, 'view.data' => function ($event, $data) use($app) {
    $route = $app->request()->attributes->get('_route');
    if (strpos($route, '@userprofile') === 0 || $route == '@user/edit') {
        $data->add('$fieldtypes', ['ajax_url' => 'api/userprofile/profile/ajax']);
    }
    //load profile
    if (in_array($route, ['@userprofile', '@userprofile/registration', '@user/edit'])) {
        $self = $app->user();
        $edit_id = $app->request()->get('id');
        if ($route == '@user/edit') {
            //blank user when admin creates new user
            $user = $edit_id ? \Pagekit\User\Model\User::find($edit_id) : \Pagekit\User\Model\User::create();
        } else {
            $user = $self;
        }
        if ($self->hasAccess('user: manage users') || $user->id == $self->id) {
            $profileUser = ProfileUser::load($user);
            $data->add('$userprofile', ['fields' => array_values(\Bixie\Userprofile\Model\Field::getProfileFields()), 'profilevalues' => $app->module('bixie/userprofile')->getProfile($user), 'profile_user' => $profileUser]);
        }
    }
}, 'view.styles' => function ($event, $styles) use($app) {
    $route = $app->request()->attributes->get('_route');
    if (strpos($route, '@userprofile') === 0 || in_array($route, ['@user/edit'])) {
        foreach ($app->module('bixie/userprofile')->getFieldTypes() as $type) {
            $type->addStyles($styles);
        }
    }
Exemplo n.º 17
0
 /**
  * Updates user's last access time
  */
 public function onUserAccess()
 {
     if ($user = App::user() and $user->isAuthenticated()) {
         User::updateAccess($user);
     }
 }
Exemplo n.º 18
0
 public function onRoleDelete($event, $role)
 {
     User::removeRole($role);
 }
Exemplo n.º 19
0
 /**
  * @Route("/{id}", methods="DELETE", requirements={"id"="\d+"})
  * @Request({"id": "int"}, csrf=true)
  */
 public function deleteAction($id)
 {
     if (App::user()->id == $id) {
         App::abort(400, __('Unable to delete yourself.'));
     }
     if ($user = User::find($id)) {
         $user->delete();
     }
     return ['message' => 'success'];
 }
Exemplo n.º 20
0
 /**
  * @param array $data
  * @return array
  */
 public function toArray($data = [])
 {
     $this->getProfile();
     $data['avatar_image'] = $this->getAvatar();
     return array_merge($this->user->toArray($data, ['password', 'activation']), $this->data);
 }
Exemplo n.º 21
0
 public function hasAccess($expression)
 {
     return $this->isAdministrator() || parent::hasAccess($expression);
 }