CakePHP and DefaultPasswordHasher syntax error - cakephp-3.0

I have no clue why but for the line
use Cake\Auth\DefaultPasswordHasher;
I'm getting an error
Error: syntax error, unexpected '?'
and full code of user.php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\Auth\DefaultPasswordHasher;
/**
* User Entity
*
* #property int $id
* #property string $email
* #property string $password
* #property \Cake\I18n\Time $created
* #property \Cake\I18n\Time $modified
*
* #property \App\Model\Entity\Bookmark[] $bookmarks
*/
class User extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* #var array
*/
protected $_accessible = [
'*' => true,
'id' => false
];
/**
* Fields that are excluded from JSON versions of the entity.
*
* #var array
*/
protected $_hidden = [
'password'
];
protected function _setPassword($value){
$hasher = new DefaultPasswordHasher();
return $hasher->hash($value);
}
}
Any thoughts? I'm using latest CakePHP

Please try with this one. Please update your CakePHP project with composer, it will update all dependency if you miss something.
namespace App\Model\Entity;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;
class User extends Entity
{
// Make all fields mass assignable except for primary key field "id".
protected $_accessible = [
'*' => true,
'id' => false
];
// ...
protected function _setPassword($password)
{
return (new DefaultPasswordHasher)->hash($password);
}
// ...
}
Also please read this doc here. Hope it should be help you to solve this issue.

use Cake\ORM\Entity;
use Cake\Auth\DefaultPasswordHasher;
/**
* User Entity
*
* #property int $id
* #property string $email
* #property string $password
* #property string $role
* #property \Cake\I18n\Time $created
* #property \Cake\I18n\Time $modified
*/
class User extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* #var array
*/
protected $_accessible = [
'*' => true,
'id' => false
];
/**
* Fields that are excluded from JSON versions of the entity.
*
* #var array
*/
protected $_hidden = [
'password'
];
protected function _setPassword($password) {
return (new DefaultPasswordHasher)->hash($password);
}
}

Related

Column 'ip' cannot be null (SQL: insert into `logins` (`ip`, `steamid`, `time`)

insert into `logins` (`ip`, `steamid`, `time`)
I use php7.0 and phpmyadmin on vmware ubuntu server 16.04.6
I tried to fix it myself but I'm not really good at those kind of things if you need any more code tell me.
any help if welcome
the site wont let me post the full code here is the full code
This is the AuthController code
<?php namespace App\Http\Controllers;
use Invisnik\LaravelSteamAuth\SteamAuth;
use Illuminate\Support\Facades\DB;
use App\User;
use Auth;
use Carbon\Carbon;
class AuthController extends Controller
{
/**
* The SteamAuth instance.
*
* #var SteamAuth
*/
protected $steam;
/**
* The redirect URL.
*
* #var string
*/
protected $redirectURL = '192.168.1.12';
/**
* AuthController constructor.
*
* #param SteamAuth $steam
*/
public function __construct(SteamAuth $steam)
{
$this->steam = $steam;
}
/**
* Redirect the user to the authentication page
*
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function redirectToSteam()
{
return $this->steam->redirect();
}
/**
* Get user info and log in
*
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function handle()
{
if($this->steam->validate())
{
$info = $this->steam->getUserInfo();
$findUser = DB::table('users')->where('steamid', $info->steamID64)->first();
if(is_null($findUser))
{
$hasThisIp = DB::table('users')->where('ip', $this->getIp())->count();
if(!is_null($hasThisIp)) {
$connections = json_decode(json_encode($hasThisIp), true);
if($connections > 3) return view('connections');
else {
$array = array('<','>');
$numele = $info->personaname;
$name = str_replace($array, '*', $numele);
DB::table('users')->insert(
[
'name' => $name,
'steamid' => $info->steamID64,
'avatar' => $info->avatarfull,
'token' => csrf_token(),
'ip' => $this->getIp()
]
);

Yii2 Trying to get property 'chnmem_stid' of non-object

I'm using Yii2 Advanced and I'm getting this error
Trying to get property 'chnmem_stid' of non-object
The error is in this function in $isMember->chnmem_stid;
public function actionChannel($id)
{
$model = $this->findModelUID($id);
$isMember = AxChnPermission::ChnMember($model->channel_id);
$memberStt = array(1,2,3);
if (in_array($isMember->chnmem_stid, $memberStt))
{
$dataProviderPost = AxChannelProvider::ContentProviderMember ($model->channel_id);
}
else
{
$dataProviderPost = AxChannelProvider::ContentProviderGuest ($model->channel_id);
}
return $this->render('/channel/_viewPost', [
'model' => $this->findModelUID($id),
'isMember' => $isMember,
'dataProviderPost' => $dataProviderPost,
]);
}
the function AxChnPermission::ChnMember($model->channel_id); is
public static function ChnMember($chn_id)
{
$member = ChnMember::findOne(['user_id' => Yii::$app->user->id, 'channel_id' => $chn_id]);
return $member;
}
so the function I want to return only one result, The "chnmem_stid" is set to hasOne in model
/**
* This is the model class for table "chnmember".
*
* #property string $member_note
* #property int $user_id
* #property int $channel_id
* #property int $channel_admin
* #property int $chnmem_stid
* #property string $chnmem_date
* #property int $dsh_statut
*
* #property Channel $channel
* #property User $user
* #property ChnmemberStatut $chnmemSt
* #property Channel $channelAdmin
*/
/**
* #return \yii\db\ActiveQuery
*/
public function getChnmemSt()
{
return $this->hasOne(ChnmemberStatut::className(), ['chnmem_stid' => 'chnmem_stid']);
}
The error appears if return of this function is NULL
public static function ChnMember($chn_id)
{
$member = ChnMember::findOne(['user_id' => Yii::$app->user->id, 'channel_id' => $chn_id]);
return $member;
}
Your function AxChnPermission::ChnMember() may return null (if requested record does not exist). And this is probably the case, since error message says that $isMember is not object. You need to make additional check for this case:
$isMember = AxChnPermission::ChnMember($model->channel_id);
if ($isMember === null) {
// throw exception?
}

Symfony2 implement PATCH method to update user fileds

How can I update FOS USER user details using PATCH method. So when I pass partial details in Json, only these details are updated.
User entity
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
abstract class User extends BaseUser
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string]
* #ORM\Column(name="first_name", type="string", length=255, nullable=true)
*/
private $firstName;
/**
* #var string
* #ORM\Column(name="last_name", type="string", length=255, nullable=true)
*/
private $lastName;
// getters and setters are here
}
For example. I have user Jack Nickolson and my json is:
{"firstName": "John"}
Only first name is updated.
This is my controller. How do I set new parameters to user, without specifing which parameters?
/**
* #Route("/update", name="api_user_update")
* #Security("has_role('ROLE_USER')")
* #Method("PATCH")
*/
public function updateAction(Request $request){
$jsonContent = $request->getContent();
$params = json_decode($jsonContent);
$em = $this->getDoctrine()->getEntityManager();
$response = new JsonResponse();
$user = $this->getUser();
// do something to update user details
$this->get('fos_user.user_manager')->updateUser($user);
$em->persist($user);
$em->flush();
$response->setContent([
"status" => "user ". $user->getUsername() ." is updated"
]);
return $response;
}
UPDATE
I tried to use an answer below, so this what I have now
public function updateAction(Request $request){
$em = $this->getDoctrine()->getEntityManager();
$response = new JsonResponse();
$user = $this->getUser();
$editForm = $this->createForm('CoreBundle\Form\UserType', $user);
$requestData = $request->getContent();
$requestData = json_encode($requestData, true);
$editForm->submit($requestData, false);
$this->get('fos_user.user_manager')->updateUser($user);
$em->persist($user);
$em->flush();
$response->setContent([
"status" => "user ". $user->getUsername() ." is updated"
]);
return $response;
}
Well, my entity was not updated. What am I doing wrong?
You need to prepare and create UserType form for partial updated.
Then, when processing a submitted form, you'll need to pass a false $clearMissing option to your form's submit method call in the controller:
$form->submit($request, false);
Thanks to that option the form component will only update the fields passed from the request.
and then flush user:
$em->flush();
Also if you want send data like:
{"firstName": "John"}
your UserType form should have method:
public function getBlockPrefix()
{
return "";
}
You can also use nice and powerfull https://github.com/FriendsOfSymfony/FOSRestBundle

How to declare a EventSubscriber in config.yml using bazinga_geocoder.geocoder service?

I am planning to make a reverse geocoding based on the BazingaGeocoderBundle. A simple way to do that is write this simple code in the controller:
$result = $this->container
->get('bazinga_geocoder.geocoder')
->using('google_maps')
->reverse(48.79084170157100,2.42479377175290);
return $this->render("MinnAdsBundle:Motors:test.html.twig",
array('result'=>var_dump($result)));
Until here, things are going well.
My objective is to make the code nicer & resuable. So, I used this article to write my own GeocoderEventSubscriber as describer below:
<?php
namespace Minn\AdsBundle\Doctrine\Event;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Event\LifecycleEventArgs;
//use Geocoder\Provider\ProviderInterface;
use Bazinga\Bundle\GeocoderBundle\Geocoder\LoggableGeocoder;
/**
* Subscribes to Doctrine prePersist and preUpdate to update an
* the address components of a MotorsAds entity
*
* #author majallouli
*/
class MotorsAdsGeocoderEventSubscriber implements EventSubscriber {
protected $geocoder;
public function __construct(LoggableGeocoder $geocoder){
$this->geocoder = $geocoder;
}
/**
* Specifies the list of events to listen
*
* #return array
*/
public function getSubscribedEvents(){
return array(
'prePersist',
'preUpdate',
);
}
/**
* Sets a new MotorsAds's address components if not present
*
* #param LifecycleEventArgs $eventArgs
*/
public function prePersist(LifecycleEventArgs $eventArgs){
$motorsAds = $eventArgs->getEntity();
if($motorsAds instanceof \Minn\AdsBundle\Entity\MotorsAds){
if( !$motorsAds->getCountry()){
$em = $eventArgs->getEntityManager();
$this->geocodeMotorsAds($motorsAds,$em);
}
}
}
/**
* Sets an updating MotorsAds's address components if not present
* or any part of address updated
*
* #param PreUpdateEventArgs $eventArgs
*/
public function preUpdate(PreUpdateEventArgs $eventArgs){
$motorsAds = $eventArgs->getEntity();
if($motorsAds instanceof \Minn\AdsBundle\Entity\MotorsAds){
if( !$motorsAds->getCountry() ){
$em = $eventArgs->getEntityManager();
$this->geocodeMotorsAds($motorsAds,$em);
$uow = $em->getUnitOfWork();
$meta = $em->getClassMetadata(get_class($motorsAds));
$uow->recomputeSingleEntityChangeSet($meta, $motorsAds);
}
}
}
/**
* Geocode and set the MotorsAds's address components
*
* #param type $motorsAds
*/
private function geocodeMotorsAds($motorsAds,$em){
$result = $this->geocode
->using('google_maps')
->reverse($motorsAds->getLat(),$motorsAds->getLng());
$motorsAds->setCountry(
$em->getRepository("MinnAdsBundle:Country")->findCountryCode($result['countryCode']));
}
}
After that, I declared my EventSubscriber as a service:
services:
# ...
geocoder_motorsads.listener:
class: Minn\AdsBundle\Doctrine\Event\MotorsAdsGeocoderEventSubscriber
arguments: [#bazinga_geocoder.geocoder] # almost sure that the error is here!!
tags:
- { name: doctrine.event_subscriber }
Actually, I get this error:
ContextErrorException: Notice: Undefined property: Minn\AdsBundle\Doctrine\Event\MotorsAdsGeocoderEventSubscriber::$geocode in /home/amine/NetBeansProjects/tuto/src/Minn/AdsBundle/Doctrine/Event/MotorsAdsGeocoderEventSubscriber.php line 78
I am almost sure that error is in the declaration of arguments of the EventSubscriber. Is it #bazinga_geocoder.geocoder?
Thank you for your help!
Your property is $this->geocoder but you're calling $this->geocode, you're spelling it wrong.

Yii mysql datetime empty

I have a problem with a Yii model, I create a MySQL table with two datetime column.
And create the model with gii. The problem is that when I get the data from the model I get the datetime fields empty.
<?php
/**
* This is the model class for table "Template".
*
* The followings are the available columns in table 'Template':
* #property string $tmpId
* #property integer $fanPageId
* #property string $name
* #property string $title
* #property string $description
* #property string $headerFile
* #property string $msgNotTlt
* #property string $msgNotMsg
* #property string $msgNotImg
* #property string $msgNotLnk
* #property string $terms
* #property string $strProm
* #property string $endProm
*/
class Template extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* #param string $className active record class name.
* #return Template the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'Template';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('fanPageId', 'numerical', 'integerOnly'=>true),
array('name, title, description, headerFile, msgNotTlt, msgNotMsg, msgNotImg, msgNotLnk, terms', 'length', 'max'=>11),
array('strProm, endProm', 'safe'),
//array('endProm, strProm', 'type', 'type'=>'datetime', 'datetimeFormat'=>'yyyy/M/d H:m:s'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('tmpId, fanPageId, name, title, description, headerFile, msgNotTlt, msgNotMsg, msgNotImg, msgNotLnk, terms, strProm, endProm', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'tmpId' => 'Tmp',
'fanPageId' => 'Fan Page',
'name' => 'Name',
'title' => 'Title',
'description' => 'Description',
'headerFile' => 'Header File',
'msgNotTlt' => 'Msg Not Tlt',
'msgNotMsg' => 'Msg Not Msg',
'msgNotImg' => 'Msg Not Img',
'msgNotLnk' => 'Msg Not Lnk',
'terms' => 'Terms',
'strProm' => 'Str Prom',
'endProm' => 'End Prom',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('tmpId',$this->tmpId,true);
$criteria->compare('fanPageId',$this->fanPageId);
$criteria->compare('name',$this->name,true);
$criteria->compare('title',$this->title,true);
$criteria->compare('description',$this->description,true);
$criteria->compare('headerFile',$this->headerFile,true);
$criteria->compare('msgNotTlt',$this->msgNotTlt,true);
$criteria->compare('msgNotMsg',$this->msgNotMsg,true);
$criteria->compare('msgNotImg',$this->msgNotImg,true);
$criteria->compare('msgNotLnk',$this->msgNotLnk,true);
$criteria->compare('terms',$this->terms,true);
$criteria->compare('strProm',$this->strProm,true);
$criteria->compare('endProm',$this->endProm,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
In rules of you model add the two columns:
array('datetime_1, datetime_2', 'safe'),
array('id, <attributes>, datetime_1, datetime_2', 'safe', 'on'=>'search'),
If possible, post you code/model...