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

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()
]
);

Related

Modified user registration in Laravel 5.7 stopped working (Field 'last_name' doesn't have a default value, but data is complete)

I have a Laravel 5.7 app. Users can't register themselves, instead another user has to be logged in to access the registration page. This worked until a few weeks ago (we don't need to register users often), but has stopped working now.
This is the error I get (current_user#example.org is a placeholder for the email address of the user who is currently logged in, not for the new user's address.):
production.ERROR: SQLSTATE[HY000]: General error: 1364 Field 'last_name' doesn't have a default value (SQL: insert into `users` (`updated_at`, `created_at`) values (2020-01-15 10:09:52, 2020-01-15 10:09:52)) {"userId":1,"email":"current_user#example.org","exception":"[object] (Illuminate\\Database\\QueryException(code: HY000): SQLSTATE[HY000]: General error: 1364 Field 'last_name' doesn't have a default value (SQL: insert into `users` (`updated_at`, `created_at`) values (2020-01-15 10:09:52, 2020-01-15 10:09:52)) at /html/myproject/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, PDOException(code: HY000): SQLSTATE[HY000]: General error: 1364 Field 'last_name' doesn't have a default value at /html/myproject/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458)
[stacktrace]
This is my RegisterController. I logged $data in the create() function. Everything (including $data['last_name'] seems to be in place:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Log;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/register';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'required|max:40',
'last_name' => 'required|max:40',
'role' => 'required|max:15',
'email' => 'required|email|max:255|unique:users',
'phone' => 'max:30',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
// Create flash message
$flashMessage = '<p>New user registered: ' .
$data['first_name'] .
' ' .
$data['last_name'] .
'</p>';
// Show flash message on next page view
session()->flash('flashMessage', $flashMessage);
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'role' => $data['role'],
'email' => $data['email'],
'phone' => $data['phone'],
'password' => bcrypt($data['password']),
]);
}
}
This is the RegistersUsers trait:
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Registered;
use Log;
trait RegistersUsers
{
use RedirectsUsers;
/**
* Show the application registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
return view('auth.register');
}
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
// $this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
/**
* Get the guard to be used during registration.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
// registered() is empty
}
Open your Model User.php and add this line protected $guarded = []; or include last_name in the $fillable array. I hope this helps.

Subquery in SELECT using Yii2 ActiveRecord

Is it possible to convert this kind of SQL into ActiveRecord query in Yii2:
SELECT
*,
(select count(*) from pendaftar where pendaftar.prodi_pilihan_1 = a.id_prodi_penerima)as jum1,
(select count(*) from pendaftar where pendaftar.prodi_pilihan_2 = a.id_prodi_penerima)as jum2
FROM prodi_penerima as a
I have two relational models that are Pendaftar and ProdiPenerima.
This is Pendaftar model:
...
* #property ProdiPenerima $prodiPilihan1
* #property ProdiPenerima $prodiPilihan2
...
/**
* #return \yii\db\ActiveQuery
*/
public function getPekerjaanIdPekerjaan()
{
return $this->hasOne(Pekerjaan::className(), ['id_pekerjaan' => 'pekerjaan_id_pekerjaan']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUserPendaftar()
{
return $this->hasOne(User::className(), ['id' => 'id_user_pendaftar']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProdiPilihan1()
{
return $this->hasOne(ProdiPenerima::className(), ['id_prodi_penerima' => 'prodi_pilihan_1']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProdiPilihan2()
{
return $this->hasOne(ProdiPenerima::className(), ['id_prodi_penerima' => 'prodi_pilihan_2']);
}
And this is ProdiPenerima model:
...
* #property Pendaftar[] $pendaftars
* #property Pendaftar[] $pendaftars0
...
/**
* #return \yii\db\ActiveQuery
*/
public function getPendaftars()
{
return $this->hasMany(Pendaftar::className(), ['prodi_pilihan_1' => 'id_prodi_penerima']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPendaftars0()
{
return $this->hasMany(Pendaftar::className(), ['prodi_pilihan_2' => 'id_prodi_penerima']);
}
prodi_pilihan_1 and prody_pilihan_2 are foreign keys in pendaftar table, that key was referenced from ProdiPenerima table.
$result = ProdiPenerima::find()
->select([
'*',
'jum1' => Pendaftar::find()
->select(['COUNT(*)'])
->where('pendaftar.prodi_pilihan_1 = a.id_prodi_penerima'),
'jum2' => Pendaftar::find()
->select(['COUNT(*)'])
->where('pendaftar.prodi_pilihan_2 = a.id_prodi_penerima')
])
->alias('a')
->asArray()
->all();
Results can be accessed by:
foreach ($result as $row) {
echo $row['jum1'];
}
That because asArray() was used, so query return array of arrays instead of array of models.
If you need models, you should add properties into your models to store result of subqueries:
class ProdiPenerima extends ActiveRecord {
public $jum1;
public $jum2;
// ...
}
Then remove isArray() from query:
$result = ProdiPenerima::find()
->select([
'*',
'jum1' => Pendaftar::find()
->select(['COUNT(*)'])
->where('pendaftar.prodi_pilihan_1 = a.id_prodi_penerima'),
'jum2' => Pendaftar::find()
->select(['COUNT(*)'])
->where('pendaftar.prodi_pilihan_2 = a.id_prodi_penerima')
])
->alias('a')
// ->asArray()
->all();
Results can be accessed by:
foreach ($result as $model) {
echo $model->jum1;
}
But note that using asArray() will be faster, so unless you need access some model methods (or rely on typecasting of values from DB) I would prefer arrays.

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

FOSRest Symfony POST using json

I'm new with the symfony framework. I'm trying to create webservices with FOSRest bundle but I had a problems when I tried to implement the POST method for one entity with json.
Test:
public function testJsonPostNewTesteAction(){
$this->client->request(
'POST',
'/api/teste/new',
array(),
array(),
array(
'Content-Type' => 'application/json',
'Accept' => 'application/json'
),
'{"Teste":{"title":"O teu title"}}'
);
$response = $this->client->getResponse();
$this->assertJsonResponse($response, Codes::HTTP_CREATED);
}
Controller:
/**
*
* #Config\Route(
* "/teste/new",
* name="postTestNew"
* )
* #Config\Method({"POST"})
*
* #param Request $request the request object
*
* #return View|Response
*/
public function postNewTeste(Request $request){
return $this->processFormTest($request);
}
/**
* Method for create the process form to Advertisements
*
* #param Request $request
*
* #return mixed
*/
private function processFormTest(Request $request){
$form = $this->createForm(
new TesteType(),
new Teste()
);
$form->bind($request);
//$from->handleRequest($request);
if ($form->isValid()) {
$test = $form->getData();
return $test;
}
return View::create($form, Codes::HTTP_BAD_REQUEST);
}
The problem is when I use the handleRequest(), the method isValid() returns false because the form didn't submit. So I try to change the handleRequest to the bind method. In the last case, the method isValid() returns true but the method getData() returns a null object.
I don't know if the problem is the type form class bellow.
Type Form:
/**
* The constant name to that type
*/
const TYPE_NAME = "Teste";
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options){
parent::buildForm($builder, $options);
$builder->add("title", ValidationType::TEXT);
}
/**
* {#inheritdoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver){
$resolver->setDefaults(
array(
'csrf_protection' => false,
'cascade_validation' => true,
'data_class' => 'oTeuGato\DatabaseBundle\Entity\Teste'
)
);
}
/**
* Returns the name of this type.
*
* #return string The name of this type
*/
public function getName(){
return AdvertisementType::TYPE_NAME;
}
I need to POST the entity with both ways. Anyone sugest anything for my problem?
Thanks for the patience!
Got the same issue with the form binding, the only way i found to solve it was to set an empty string to the form getName function:
/**
* Returns the name of this type.
*
* #return string The name of this type
*/
public function getName(){
return '';
}
And i would suggest to use the handleRequest method when you bind your data because the bind method is deprecated:
private function processFormTest(Request $request){
$form = $this->createForm(
new TesteType(),
new Teste()
);
$from->handleRequest($request);
if ($form->isValid()) {
$test = $form->getData();
return $test;
}
return View::create($form, Codes::HTTP_BAD_REQUEST);
}
It looks more like a hack but seems like it's the only way for now:
https://github.com/FriendsOfSymfony/FOSRestBundle/issues/585
I am not entirely sure but I think it's because you're sending the data with: 'Content-Type' => 'application/json'
in stead of 'Content-Type' => 'application/x-www-form-urlencoded'
Or at least I think that's the reason why the handleRequest is not doing it's thing.

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.