How to solve error "Invalid view" in registration function? - reactjs

I am having an error during the registration of a recruiter for the application I am working for
here is the error I am having in the network while sending the form information :
code:500
error: "Invalid view."
message: "Erreur lors de la création du compte"
here is the code
public function personnal(AccountCreateRequest $request)
{
try {
$http = new \GuzzleHttp\Client;
$exists = false;
$userData = $request->input('user');
$userData['password'] = bcrypt($userData['password']);
$userData['gender'] = ($userData['title'] === 'M.') ? 'm' : 'f';
if (array_get($userData, 'ref')) {
$user = User::where('ref', $userData['ref'])->firstOrFail();
$user->fill($userData);
$exists = true;
} else {
$userData['ref'] = User::generateId();
$user = new User($userData);
}
$user->source = 'website';
$user->optin_platform = 1;
if ($user->role === 'seeker') {
$user->is_active = 1;
$user->save();
$seeker = new UserSeeker([
'registration_date' => Carbon::now(),
'available_in' => 1,
'token' => bin2hex(uniqid(rand())),
'resume_path' => $request->input('seeker.resume_path'),
'resume_date' => Carbon::now(),
]);
$seeker = $user->seeker()->save($seeker);
$seeker->location()->associate(Address::create($request->input('location')))->save();
} else {
$user->is_active = 0;
$user->save();
// $size = $request->input('company.size', $request->session()->get('info'));
$companyData = $request->input('company');
$company = Company::create($companyData);
$recruiter = $user->recruiter()->save(new UserRecruiter([
'company_id' => $company->id,
]));
}
DB::commit();
$this->json['response'] = ['ref' => $user->ref];
$this->json['code'] = $this->code['created'];
dd($this->json);
} catch (MissingParamsException $e) {
DB::rollback();
$this->setError($e, $e->getMessage(), 'missing');
} catch (\Exception $e) {
DB::rollback();
$this->setError($e, 'Erreur lors de la création du compte');
} finally {
return ($this->response());
}

I resolve my issue by changing the is_active parameters to 1

Related

Codeigniter 3.1.9 - CI_Session is filling up my database on every refresh

I have been getting back into Codeigniter as support was picked up by BCIT. I have a problem with ci_sessions and the database driver which is regenerating the encrypted session ID and storing new data in my database on every page refresh. I'm so frustrated right now! I have both secure file storage and database for both common drivers. I want to use both or either but the effect on my application is the same whether I am using a database or files. The ci_session keeps refreshing and it is not ideal for logins, registration or any account type. Please help me see what I am doing wrong? Much appreciation granted in advance.
Config:
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'users';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
Controllers:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* User Management class created by CodexWorld
*/
class Limousers extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('user');
}
/*
* User account information
*/
public function account(){
print_r($_SESSION);
$data = array();
print_r($this->session->userdata());
if($this->session->userdata('isUserLoggedIn')){
$data['user'] = $this->user->getRows(array('id'=>$this->session->userdata('userId')));
//load the view
$this->load->view('limousers/account', $data);
}else{
redirect('limousers/login');
exit;
}
}
/*
* User login
*/
public function login(){
print_r($_SESSION);
if($this->session->userdata('isUserLoggedIn'))
{
print_r($this->session->userdata);
redirect('limousers/account');
exit;
}
$data = array();
if($this->session->userdata('success_msg')){
$data['success_msg'] = $this->session->userdata('success_msg');
$this->session->unset_userdata('success_msg');
}
if($this->session->userdata('error_msg')){
$data['error_msg'] = $this->session->userdata('error_msg');
$this->session->unset_userdata('error_msg');
}
if($this->input->post('loginSubmit')){
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'password', 'required');
if ($this->form_validation->run() == true) {
$con['returnType'] = 'single';
$con['conditions'] = array(
'email'=>$this->input->post('email'),
'password' => md5($this->input->post('password')),
'status' => '1'
);
$checkLogin = $this->user->getRows($con);
if($checkLogin){
$this->session->set_userdata('name',$con['conditions']['email']);
$this->session->set_userdata('isUserLoggedIn',TRUE);
$this->session->set_userdata('userId',$checkLogin['id']);
redirect('limousers/account');
exit;
}else{
$data['error_msg'] = 'Wrong email or password, please try again.';
}
}
}
//load the view
$this->load->view('limousers/login', $data);
}
/*
* User registration
*/
public function registration(){
print_r($_SESSION);
$data = array();
$userData = array();
if($this->input->post('regisSubmit')){
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_email_check');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_rules('conf_password', 'confirm password', 'required|matches[password]');
$userData = array(
'name' => strip_tags($this->input->post('name')),
'email' => strip_tags($this->input->post('email')),
'password' => md5($this->input->post('password')),
'gender' => $this->input->post('gender'),
'phone' => strip_tags($this->input->post('phone'))
);
if($this->form_validation->run() == true){
$insert = $this->user->insert($userData);
if($insert){
$this->session->set_userdata('success_msg', 'Your registration was successfully. Please login to your account.');
redirect('limousers/login');
exit;
}else{
$data['error_msg'] = 'Some problems occured, please try again.';
}
}
}
$data['user'] = $userData;
//load the view
$this->load->view('limousers/registration', $data);
}
/*
* User logout
*/
public function logout(){
$this->session->unset_userdata('isUserLoggedIn');
$this->session->unset_userdata('userId');
$this->session->sess_destroy();
redirect('limousers/login');
exit;
}
/*
* Existing email check during validation
*/
public function email_check($str){
$con['returnType'] = 'count';
$con['conditions'] = array('email'=>$str);
$checkEmail = $this->user->getRows($con);
if($checkEmail > 0){
$this->form_validation->set_message('email_check', 'The given email already exists.');
return FALSE;
} else {
return TRUE;
}
}
}
Models:
<?php if ( ! defined('BASEPATH')) exit('No direct script access
allowed');
class User extends CI_Model{
function __construct() {
$this->userTbl = 'users';
}
/*
* get rows from the users table
*/
function getRows($params = array()){
$this->db->select('*');
$this->db->from($this->userTbl);
//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach ($params['conditions'] as $key => $value) {
$this->db->where($key,$value);
}
}
if(array_key_exists("id",$params)){
$this->db->where('id',$params['id']);
$query = $this->db->get();
$result = $query->row_array();
}else{
//set start and limit
if(array_key_exists("start",$params) &&
array_key_exists("limit",$params)){
$this->db->limit($params['limit'],$params['start']);
}elseif(!array_key_exists("start",$params) &&
array_key_exists("limit",$params)){
$this->db->limit($params['limit']);
}
$query = $this->db->get();
if(array_key_exists("returnType",$params) &&
$params['returnType'] == 'count'){
$result = $query->num_rows();
}elseif(array_key_exists("returnType",$params) &&
$params['returnType'] == 'single'){
$result = ($query->num_rows() > 0)?$query- >row_array():FALSE;
}else{
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
}
}
//return fetched data
return $result;
}
/*
* Insert user information
*/
public function insert($data = array()) {
//add created and modified data if not included
if(!array_key_exists("created", $data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists("modified", $data)){
$data['modified'] = date("Y-m-d H:i:s");
}
//insert user data to users table
$insert = $this->db->insert($this->userTbl, $data);
//return the status
if($insert){
return $this->db->insert_id();
}else{
return false;
}
}
}

Rendering view for DOMPDF in phalconPHP

I have been try to convert template to PDF with DOMPDF in phalconPHP with angularJS at the front. But I am getting 500 internal server error response from it. DOMPDF is included fine in the controller as I loaded static HTML in load_html() function, it worked fine. Below is the report action from ReportsController. Don't bother with the whole code and just skip to the DOMPDF related code at the end. And $patients is the array that contains all the data which the template is going to need.
ReportController's reportAction:
public function reportAction()
{
$patientsModel = new Patients();
$patients = array();
$patients['data'] = array();
$tmpfilters = $this->queryfilters;
unset($tmpfilters['limit']);
$tmpfilters2 = array();
$tmpfilters2['models'] = "PRM\\Models\\Patients";
if( isset( $tmpfilters['conditions'] ) )
{
$tmpCondition = preg_replace("/[^0-9]/", '', $tmpfilters['conditions']);
$tmpfilters2['conditions'] = "clinic = " . $tmpCondition . " AND status = 24";
}
else
{
$tmpfilters2['conditions'] = "status = 24";
}
$tmpActivePatients = new Patients();
$tmpActivePatients = $tmpActivePatients->find($tmpfilters2);
$patients['activeTotal'] = $tmpActivePatients->count();
$tmpfilters3 = array();
$tmpfilters3['models']['m'] = "PRM\\Models\\Activity";
$tmpfilters3['models']['s'] = "PRM\\Models\\Patients";
if( isset( $tmpfilters['conditions'] ) )
{
$tmpCondition2 = preg_replace("/[^0-9]/", '', $tmpfilters['conditions']);
$tmpfilters3['conditions'] = "m.clinic = " . $tmpCondition2 . " AND " . "s.clinic = " . $tmpCondition2 . " AND m.patient=s.id AND m.duration > 1";
}
else
{
$tmpfilters3['conditions'] = "m.patient = s.id AND m.duration > 1";
}
$tmpPatientDuration = new Query($tmpfilters3);
$tmpPatientDuration = $tmpPatientDuration->getQuery()->execute();
//$builder = $this->modelsManager->createBuilder();
$patients['billableTotal'] = $tmpPatientDuration->count();
//$builder->addFrom('PRM\\Models\\Activity', 'a')->innerJoin('PRM\\Models\\Patients', 'p.id=a.patient', 'p')->where('a.duration > 1 AND p.status = 24');
//$result = $builder->getQuery()->execute();
//$patients['billableTotal'] = $result->count();
foreach ($tmpPatientDuration as $patient) {
array_push($patients['data'], array(
'id' => $patient->id,
'firstname' => $patient->s->firstname,
'lastname' => $patient->s->lastname,
'duration' => $patient->m->duration,
'billingCode' => "CPT 99490"));
/*'icd1' => Ccm::findFirstById($patient->icd1)->icdcode,
//'icd2' => Ccm::findFirstById($patient->icd2)->icdcode,
//'clinic' => Clinics::findFirstById($patient->clinic)->name,
'duration' => Activity::sum([
"column" => "duration",
"conditions" => "patient = '{$patient->id}'",
]),
'response' => Activity::findFirst([
"conditions" => "patient = '{$patient->id}' and activity='Communication' ",
"order" => "id desc"
])->description,
'status' => Status::findFirstById($patient->status)->name));*/
}
$html = $this->view->getRender("reports", "report", $patients);
$dompdf = new domPdf();
$dompdf->load_html($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
//$this->response->setJsonContent($patients);
$this->response->setContentType('application/pdf');
$this->response->setContent($dompdf->stream());
$this->response->send();
}
Here is the angularJS controller's code:
$http.get('common/reports/report', {responseType: 'arraybuffer'}).success(
function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}).error(
function (data) {
angular.forEach(data, function (error) {
$scope.error[error.field] = error.message;
console.log(error.field);
});
$alert({title: 'Error!', content: data.flash.message, placement: 'top-right', type: data.flash.class , duration: 10, container: '.site-alert'});
}
);
error logs:
error log for the above problem

Persisting data to database. persist not working

I wrote a controller action that is supposed to add an element (meeting) to the database here it is:
public function newAction(Request $request){
$meeting = new Meeting();
$meetingUser = new MeetingUser();
$project = new Project();
$projectName = "SocialPro";//$request->get('projectName');
echo($projectName);
$users = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findProjectUser($projectName);
//$form = $this->createForm('SocialPro\MeetingBundle\Form\MeetingType', $meeting);
//$form->handleRequest($request);
//if ($form->isSubmitted() && $form->isValid()) {
$userconn = $this->container->get('security.token_storage')->getToken()->getUser();
echo($userconn->getId());
if ($request->isMethod('POST')) {
echo("message form");
$role = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findUserRole($userconn)[0]['role'];
$date = $request->get('date');
if ($role == "PROJECT_MASTER" || $role == "TEAM_MASTER") {
for ($i = 0; $i < count($users); $i++) {
$meetings = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findMeetingUser($users[$i]['id'], $date);
}
if ($meetings == null || count($meetings) == 0) {
$project = $this->getDoctrine()->getRepository('SocialProProjectBundle:Project')->findBy(array("name" = >$projectName));
$meeting->setDescription($request->get('description'));
$meeting->setDate(new \DateTime($request->get('date')));
$meeting->setTime($request->get('time'));
$meeting->setProjectName($request->get('projectName'));
$meeting->setProject($project[0]);
$meetingUser->setMeetings($meeting);
$meetingUser->setUsers($userconn);
var_dump($meetingUser);
$meeting->setMeetingUser(array($meetingUser));
//$project->setMeetings($meeting->getId());
$em = $this->getDoctrine()->getManager();
$em->persist($meeting);
$em->persist($meetingUser);
$em->flush();
// $meetingUser->setUsers($request->get(''));
return $this->redirectToRoute('reunion_show', array('id' = > $meeting->getId()));
}
else {
echo("Membre indisponible");
}
}
else {
echo("Must be MASTER to create meeting");
}
}
return $this->render('SocialProMeetingBundle::ajoutMeeting.html.twig', array('users' = >$users));
// $em = $this->getDoctrine()->getManager();
//$em->persist($meeting);
//$em->flush($meeting);
// return $this->redirectToRoute('meeting_show', array('id' => $meeting->getId()));
//}
//return $this->render('SocialProMeetingBundle:ajouMeeting', array(
// 'meeting' => $meeting,
//'form' => $form->createView(),
//));
}
When I submit the form it gives me a site not available page. I tested it line by line and everything is working perfectly. Turns out the problem is in the
$em->persist($meeting);
And I have no idea how to fix it.
You must call flush immediately after calling persist like so:
$em->persist( $meeting );
$em->flush();
$em->persist( $meetingUser );
$em->flush();
Then it will persist both.

How to get data from a database using a loop?

In my database I've got different username: "fabio97", "antonino", "lauretta". I want to get them from DB to have an array like this:
$dati = array("str"=>array("n1"=>"fabio97", "n2"=>"antonino", "n3"=>"lauretta"));
is it correct write:
...
"str" => array("n".$i=>"Ti sei incrociato con ".$array_db[username]),
...
into a loop
...
$i = 0;
$array_user = mysql_fetch_array($query);
while ($array_db = mysql_fetch_array ($query_db)) {
...
if ($array_user[square] == $array_db[square]) {
$dati = array(
"data" => array(
'address_complete'=>$data->results[0]->formatted_address,
'address_square'=>$data->results[0]->address_components[1]->long_name,
'location'=>$data->results[0]->address_components[2]->long_name,
'postal_code'=>$data->results[0]->address_components[7]->long_name,
'data_ora'=>$tmp_date
),
"str" => array("n".$i=>"Ti sei incrociato con ".$array_db[username]),
"index" => $i
);
$i++;
}
}
and to call them with Ajax:
... success:function(msg){
if(msg){
$("#location").html(Object.keys(msg.str).map(x => msg.str[x]).join(", "));
}else{
$("#location").html('Not Available');
}

Problem, OpenID Simple Registration Extension

I use OpenID Simple Registration on CakePHP like this post but this don't work for me.
my code in controller is here:
function openid() {
$returnTo = 'http://'.$_SERVER['SERVER_NAME'].$this->webroot.'customers/openid';
if (!empty($this->data)) {
try {
$this->Openid->authenticate($this->data['OpenidUrl']['openid'], $returnTo, 'http://'.$_SERVER['SERVER_NAME'].$this->webroot, array('email'), array('nickname'));
} catch (InvalidArgumentException $e) {
$this->setMessage($this->data);
} catch (Exception $e) {
$this->setMessage($e->getMessage());
}
}
elseif (count($_GET) > 1) {
$response = $this->Openid->getResponse($returnTo);
$this->set("test",$_GET);
if ($response->status == Auth_OpenID_CANCEL) {
$this->Session->write('OpenIdStatus','Verification cancelled');
} elseif ($response->status == Auth_OpenID_FAILURE) {
$this->Session->write('OpenIdStatus','OpenID verification failed: '.$response->message);
} elseif ($response->status == Auth_OpenID_SUCCESS) {
$this->Session->write('OpenIdStatus','successfully authenticated!');
$sregResponse = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
$sregContents = $sregResponse->contents();
$this->set("message",$sregContents);
}
}
}
What is my wrong?!
The authenticate method only expects four params in the current version. The following snippet:
$this->Openid->authenticate($this->data['OpenidUrl']['openid'], $returnTo, 'http://'.$_SERVER['SERVER_NAME'].$this->webroot, array('email'), array('nickname'));
has to look like:
$this->Openid->authenticate($this->data['OpenidUrl']['openid'], $returnTo, 'http://'.$_SERVER['SERVER_NAME'].$this->webroot, array('sreg_required' => array('email'), 'sreg_optional' => array('nickname')));

Resources