croogo 2 Request blackholed due to "auth" violation - mysql

I have a problem with my old website. Now I try to move it to new server (php5.6) and when i try to save data I have error:
Request blackholed due to "auth" violation.
I serach the place whose do it this error:
if ($this->Node->saveWithMeta($this->request->data)) {
Croogo::dispatchEvent('Controller.Nodes.afterAdd', $this, array('data' => $this->request->data));
$this->Session->setFlash(__('%s has been saved', $type['Type']['title']), 'default', array('class' => 'success'));
if (isset($this->request->data['apply'])) {
$this->redirect(array('action' => 'edit', $this->Node->id));
} else {
$this->redirect(array('action' => 'index'));
}
}
I think error do function saveWithMeta(). This function view like:
public function saveWithMeta(Model $model, $data, $options = array()) {
$data = $this->_prepareMeta($data);
return $model->saveAll($data, $options);
}
Can I replace/edit this function so that it starts to work?
edit
if (!$db->create($this, $fields, $values)) {
$success = $created = false;
} else {
$created = true;
}
These lines cause an error.

Related

captcha not working using scenarios in yii2

I am trying to add captcha validation based on scenario, for which I am first retrieving number of failed attempts from database. For which I am using checkattempts() function. Based on the result I am displaying captcha in view and adding scenario condition in controller as below.
In LoginForm model:
public function rules()
{
return [
[['username', 'password'], 'required', 'on'=>'loginpage'],
[['username', 'password'], 'required', 'on'=>'withCaptcha'],
[['reference_url'], 'safe'],
[['verifyCode'], 'captcha', 'skipOnEmpty' => true,'on'=>'withCaptcha'],
['username','email', 'on'=>'loginpage', 'message'=> 'Please enter a valid email address'],
['password', 'validatePassword', 'on'=>'loginpage'],
['password', 'validatePassword', 'on'=>'withCaptcha'],
];
}
public function checkattempts($uname)
{
$user = \frontend\models\User::findByEmail($uname);
$ip = $this->get_client_ip();
if($user){
$data = (new Query())->select('*')
->from('login_attempts')
->where(['ip' => $ip])->andWhere(['user_ref_id' => $user->id])
->one();
if($data["attempts"] >=3){
return true;
}else{
return false;
}
}
return false;
}
in SiteController.php controller
public function actionLogin() {
if (!\Yii::$app->user->isGuest) {
return $this->redirect(Yii::$app->getUrlManager()->getBaseUrl() . '/../../');
}
$model = new \common\models\LoginForm();
$model->scenario = 'loginpage';
$captcha = false;
if(Yii::$app->request->post()){
$post_variables =Yii::$app->request->post('LoginForm');
if ($model->checkattempts($post_variables['username'])) {
$model->scenario = 'withCaptcha';
$captcha = true;
}
}
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->login(); print_r($model->getErrors()); exit;
} else {
return $this->render('login', [
'model' => $model, 'captcha' => $captcha,
]);
}
In my login.php view:
<?php if($captcha) { ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(),
['template' => '<div class="captcha_img">{image}</div>'
. '<a class="refreshcaptcha" href="#">'
. Html::img('/images/imageName.png',[]).'</a>'
. 'Verification Code{input}',
])->label(FALSE); ?>
<?php } ?>
In my controller when I am tring to print model errors at $model->login() function it is giving below error everytime even though the verification code is correct.
Array ( [verifycode] => Array ( [0] => The verification code is incorrect. ) )
Why is it failing every time. Is there any mistake in the code written?
Thanks in advance

No form errors shown in JsonResponse - Symfony

I have a registration form with fields that are validated in User entity class. The validation works fine, however I can't return JsonResponse with form error messages in it.
My registration form controller method looks like this:
/**
* #Route("/register", name="register")
*/
public function registerAction(Request $request)
{
$user = new User();
$form = $this->createForm(RegistrationType::class, $user);
$form->handleRequest($request);
$errors = "";
if ($form->isSubmitted())
{
if ($form->isValid())
{
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$user->setIsActive(1);
$user->setLastname('none');
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return new JsonResponse(
array(
'message' => 'Success! User registered!',
), 200);
}
else
{
$errors = ($this->get('validator')->validate($form));
return new JsonResponse(
array(
'message' => 'Not registered',
'errors' => $errors,
), 400);
}
}
return $this->render(
'ImmoBundle::Security/register.html.twig',
array('form' => $form->createView(), 'errors' => $errors)
);
}
I get the following json response when I submit the registration form with invalid data:
{"message":"Not registered","errors":{}}
Actually I'm expecting that "errors":{} will contain some error fields, but it doesn't. Does anyone know what the problem here is?
UPD:
My RegistrationType looks like this:
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstname', TextType::class)
->add('email', EmailType::class)
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat password'),
'invalid_message' => "Passwords don't match!",
))
->add('register', SubmitType::class, array('label' => 'Register'));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'ImmoBundle\Entity\User',
'csrf_protection' => true,
'csrf_field_name' => '_token',
'csrf_token_id' => 'authenticate',
));
}
}
UPD2: Found the solution. I needed to do this iteration and then call for getMessage():
$allErrors = ($this->get('validator')->validate($form));
foreach ($allErrors as $error)
{
$errors[] = $error->getMessage();
}
Form validated when you call $form->handleRequest($request);
To get form errors use getErrors method
$errors = $form->getErrors(true); // $errors will be Iterator
to convert errors object to messages array you can use code from this response - Handle form errors in controller and pass it to twig
This is exapmle how i'm process errors in one of my projects
$response = $this->get('http.response_formatter');
if (!$form->isValid()) {
$errors = $form->getErrors(true);
foreach ($errors as $error) {
$response->addError($error->getMessage(), Response::HTTP_BAD_REQUEST);
}
return $response->jsonResponse(Response::HTTP_BAD_REQUEST);
}
It's worked for me.
And also this can help you - Symfony2 : How to get form validation errors after binding the request to the form
You must set error_bubbling to true in your form type by explicitly setting the option for each and every field.

Can't upload files reliably in Yii2

I got this method that's intended to upload a file, but sometimes it does so when $this->imageFile is not instantiated. I have no idea why.
public function upload()
{
$path = Url::to('#webroot/images/photos/');
$filename = strtolower($this->username) . '.jpg';
$this->imageFile->saveAs($path . $filename);
return true;
}
I call the method upload() in beforeSave() like this:
public function beforeSave($insert)
{
if(parent::beforeSave($insert)){
if($this->isNewRecord)
{
$this->password = Yii::$app->security->generatePasswordHash($this->password);
}
$this->upload();
return true;
}
else
{
return false;
}
}
I called this method like 100 times with mixed results. I have no idea why this method call doesn't give the same result. It should either never work or always work, but for some reason the code is not deterministic at all.
public function actionCreate()
{
$model = new Member();
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Another thing, when I use this code, I get a file, but the username is blank so I get a .jpeg file without a name.
public function actionCreate()
{
$model = new Member();
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
$model->upload();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
<?php
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
In the If clause you are redirecting to view and $model disappears between requests naturally. But in else you sending $model to view directly. It looks like the buggy section.
The other one, when you move the $model->upload() to actionCreate, you are placing it before If statement but you are loading the post to the model in if clause so, naturally user wasn't loading when you are trying to upload.
If you are prefer to send $model->upload() to action just be sure to call following method before upload. $model->load(Yii::$app->request->post())

cant import data csv to database in yii2

I am very new to web development.
I'm newbie in here, my first question in stackoverflow..
i am confused what error on code, Code will be store data array csv to a database,
sorry my bad english.
Controller
public function actionUpload()
{
$model = new Skt();
//error_reporting(E_ALL);
//ini_set('display_error', 1);
if ($model->load(Yii::$app->request->post())) {
$file = UploadedFile::getInstance($model, 'file');
$filename = 'Data.' . $file->extension;
$upload = $file->saveAs('uploads/' . $filename);
if ($upload) {
define('CSV_PATH', 'uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
foreach ($filecsv as $data) {
$modelnew = new Skt();
$hasil = explode(",", $data);
$no_surat= $hasil[0];
$posisi= $hasil[1];
$nama= $hasil[2];
$tgl_permanen= $hasil[3];
$grade= $hasil[4];
$tgl_surat= $hasil[5];
$from_date = $hasil[6];
$to_date = $hasil[7];
$modelnew->no_surat = $no_surat;
$modelnew->posisi = $posisi;
$modelnew->nama = $nama;
$modelnew->tgl_permanen = $tgl_permanen;
$modelnew->grade = $grade;
$modelnew->tgl_surat = $tgl_surat;
$modelnew->from_date = $from_date;
$modelnew->to_date = $to_date;
$modelnew->save();
//print_r($modelnew->validate());exit;
}
unlink('uploads/'.$filename);
return $this->redirect(['site/index']);
}
}else{
return $this->render('upload',['model'=>$model]);
}
return $this->redirect(['upload']);
}
Model
class Skt extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'skt';
}
public $file;
public function rules()
{
return [
[['file'], 'required'],
[['file'], 'file', 'extensions' => 'csv', 'maxSize' => 1024*1024*5],
[['no_surat'], 'required'],
[['tgl_surat', 'from_date', 'to_date'], 'string'],
[['no_surat', 'posisi', 'nama', 'tgl_permanen', 'grade'], 'string', 'max' => 255],
];
}
public function attributeLabels()
{
return [
'no_surat' => 'No Surat',
'posisi' => 'Posisi',
'nama' => 'Nama',
'tgl_permanen' => 'Tgl Permanen',
'grade' => 'Grade',
'tgl_surat' => 'Tgl Surat',
'from_date' => 'From Date',
'to_date' => 'To Date',
'file' => 'Select File'
];
}
}
thanks for helping..
change your code to the following to output the errors which could happen when you try to save. Errors could occur depending on your model rules.
if (!$modelnew->save()) {
var_dump($modelnew->getErrors());
}
getErrors() from Api
A better approach is to use exceptions to throw and catch errors on your import. Depends if you want to skip csv lines on errors or not.
finally it working with change this $hasil = explode(";", $data);

I am trying to find a "simple" way to store images (and data about them) using CakePHP and MySQL.This code has got me a bit confused

I went through this article to make a file uploading site with Cakephp,
http://www.tuxradar.com/content/cakephp-tutorial-build-file-sharing-application
I suppose the relevant code to this question is this, a download and an upload function,
function add() {
if (!empty($this->data)) {
$this->Upload->create();
if ($this->uploadFile() && $this->Upload->save($this->data)) {
$this->Session->setFlash(__('The upload has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The upload could not be saved. Please, try again.', true));
}
}
$users = $this->Upload->User->find('list');
$users = $this->Upload->User->find('list');
$this->set(compact('users', 'users'));
}
function uploadFile() {
$file = $this->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK) {
$id = String::uuid();
if (move_uploaded_file($file['tmp_name'], APP.'uploads'.DS.$id)) {
$this->data['Upload']['id'] = $id;
$this->data['Upload']['filename'] = $file['name'];
$this->data['Upload']['filesize'] = $file['size'];
$this->data['Upload']['filemime'] = $file['type'];
return true;
}
}
return false;
}
function download($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid id for upload', true));
$this->redirect(array('action' => 'index'));
}
$this->Upload->bindModel(array('hasOne' => array('UploadsUser')));
$upload = $this->Upload->find('first', array(
'conditions' => array(
'Upload.id' => $id,
'OR' => array(
'UploadsUser.user_id' => $this->Auth->user('id'),
'Upload.user_id' => $this->Auth->user('id'),
),
)
));
if (!$upload) {
$this->Session->setFlash(__('Invalid id for upload', true));
$this->redirect(array('action' => 'index'));
}
$this->view = 'media';
$filename = $upload['Upload']['filename'];
$this->set(array(
'id' => $upload['Upload']['id'],
'name' => substr($filename, 0, strrpos($filename, '.')),
'extension' => substr(strrchr($filename, '.'), 1),
'path' => APP.'uploads'.DS,
'download' => true,
));
}
I am not quite sure what all that code is doing actually, but I am trying to make a page so I can display one of the images instead of downloading them. If make this statement,
<?php echo $this->Html->image('/uploads/download/'.$upload['Upload']['id']);?>
My webpage displays my image but I don't actually have a download folder, I added that extension because it appears that the download function adds it for some reason. If someone could explain what is happening there, that would be great.
You need to make a new controller method to view your images individually, something like this:
public function view($id = null) {
if (!$this->Upload->exists($id)) {
throw new NotFoundException(__('Invalid upload'));
}
$options = array('conditions' => array('Upload.' . $this->Upload->primaryKey => $id));
$this->set('upload', $this->Upload->find('first', $options));
}
And then display the image in your /View/Uploads/view.ctp:
<?php echo $this->Html->image('/uploads/download/'.$upload['Upload']['id']);?>