Laravel Sentry Update the User - laravel

I have a problem with Sentry. The problem is probably that under $user = Sentry::getUserProvider()->findById($id);it is not only finding one user, but many users. Thus it cannot recognize the method user->save.
How can I solve this problem?
I am trying to build a form to edit my user details.
Thank you.
My form looks like this:
{{ Form::open(array('url' => 'profile/useredit')) }}
{{ Form::text('address',null) }}
<br>
{{Form::submit('Submit', array('class' => 'btn btn-default'))}}
{{ Form::close() }}
/**
* Edit the user profile under profile/user
*
* #return View
*/
public function postUseredit(){
try {
$id= Session::get(Config::get('sentry::sentry.session.user'));
// Get the user information
$user = Sentry::getUserProvider()->findById($id);
} catch (UserNotFoundException $e) {
// Prepare the error message
$error = Lang::get('users/message.user_not_found', compact('id'));
// Redirect to the user management page
return Redirect::route('users')->with('error', $error);
}
try {
// Update the user
$user->first_name = Input::get('first_name');
$user->last_name = Input::get('last_name');
$user->email = Input::get('email');
$user->dob = Input::get('dob');
$user->bio = Input::get('bio');
$user->gender = Input::get('gender');
$user->country = Input::get('country');
$user->state = Input::get('state');
$user->city = Input::get('city');
$user->address = Input::get('address');
$user->postal = Input::get('postal');
$user->activated = Input::get('activate')?1:0;
/*
// is new image uploaded?
if ($file = Input::file('pic'))
{
$fileName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/users/';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10).'.'.$extension;
$file->move($destinationPath, $safeName);
//delete old pic if exists
if(File::exists(public_path() . $folderName.$user->pic))
{
File::delete(public_path() . $folderName.$user->pic);
}
//save new file path into db
$user->pic = $safeName;
}
*/
/*
// Get the current user groups
$userGroups = $user->groups()->lists('group_id', 'group_id');
// Get the selected groups
$selectedGroups = Input::get('groups', array());
// Groups comparison between the groups the user currently
// have and the groups the user wish to have.
$groupsToAdd = array_diff($selectedGroups, $userGroups);
$groupsToRemove = array_diff($userGroups, $selectedGroups);
// Assign the user to groups
foreach ($groupsToAdd as $groupId) {
$group = Sentry::getGroupProvider()->findById($groupId);
$user->addGroup($group);
}
// Remove the user from groups
foreach ($groupsToRemove as $groupId) {
$group = Sentry::getGroupProvider()->findById($groupId);
$user->removeGroup($group);
}
*/
// Was the user updated?
if ($user->save()) {
// Prepare the success message
$success = Lang::get('users/message.success.update');
// Redirect to the user page
return Redirect::route('profile/user', $id)->with('success', $success);
}
// Prepare the error message
$error = Lang::get('users/message.error.update');
} catch (LoginRequiredException $e) {
$error = Lang::get('users/message.user_login_required');
}
// Redirect to the user page
return Redirect::route('profile/user', $id)->withInput()->with('error', $error);
}

Instead of
$user = Sentry::getUserProvider()->findById($id);
try this
$user = Sentry::findUserById($id);

Related

Insert fields after success payment

Hope you all have a good day..
At first i have a form that user should fill before redirect to PayTabs page for payment
But i don't need the form to be inserted in database before success payment
public function index(Request $request): RedirectResponse
{
$response = $this->request(
url: 'https://secure-global.paytabs.com/payment/request',
payload: $this->transactionPayload(
amount: 0
)
);
Transaction::create([
'paytabs_transaction_reference' => $response->json()['tran_ref'] ?? null
]);
Cart::where('opened', '=', 0)->where('user_id', Auth::id())->update(['paytabs_transaction_reference' => $response->json()['tran_ref'] ?? null]);
$cart_id = Cart::latest()->first()->id;
$payment = new Payment;
$payment->cart_id = $cart_id;
$payment->country_id = $request->input('country_id');
$payment->delivery_id = $request->input('delivery_id');
$payment->address = $request->input('address');
$payment->street = $request->input('street');
$payment->home = $request->input('home');
$payment->email = $request->input('email');
$payment->save();
return redirect()->away($response['redirect_url']);
}
public function return(Request $request): string
{
$category = Category::all();
$products = Product::all();
$validSignature = $this->validateSignature($request->all());
if ($validSignature) {
if ($request->respStatus == 'A') {
$transaction = Transaction::where('paytabs_transaction_reference', $request->tranRef)->first();
$transaction->paid = true;
$transaction->save();
DB::table('carts')->where('user_id', Auth::id())->where('opened', 0 )->update(['opened' => 1]);
return view('index', compact('category', 'products'))->with('success', 'Payment has been done successfully. Thank you!') . $request->respMessage;
}
return view('index', compact('category', 'products')) . $request->respMessage;
} else {
return 'Invalid Transaction Signature';
}
}
Here the form will be inserted even if he back from the next page
<form role="form" action="{{ route('index') }}" method="post">
#csrf
.......
</form>
That's my form should be to INDEX function to redirect to payment page
You Need To Make A Validation To Your Form

Customize Laravel 8 Passport methods

The login validation I use is not Laravel's default. How do I customize Passport methods?
The following code I use to validate with web middleware.
$username = $request->username;
$password = strtoupper(md5($request->password));
$system = env("CODE_SYSTEM", 12);
$sql = "SELECT user.validate( '$system' , '$username', '$password')";
$stmt = DB::select(DB::raw($sql));
$result = $stmt[0]->validation;
if ($result == "ok") {
$user = new User();
$id = DB::table('users')->select('id')
->where('username' , $username)->first();
$user = User::find($id->id);
return $user;
}
To customize you need add the validateForPassportPasswordGrant() at User method, example:
public function validateForPassportPasswordGrant($password)
{
$password = strtoupper(md5($request->password));
$system = env("CODE_SYSTEM", 12);
$sql = "SELECT user.validate( '$system' , '$this->username', '$password')";
$stmt = DB::select(DB::raw($sql));
$result = $stmt[0]->validation;
if ($result == "ok") {
return true;
}
return false;
}
If you need to change the user column name where the passport search username:
public function findForPassport($username)
{
return $this->where('the_username_column', $username)->first();
}

How can I store the web push notification settings after the login in database

I want to send web push notification on the browser. I used this tutorial to
send the notification. This is working fine and show the details.
{
"endpoint":"https://fcm.googleapis.com/fcm/send/ftB1OYn5bJY:APA91bGNcquGDcUXr29JiVV5Zos4Vi7FzmZ_wJQMITEXt8FlVBRBtgrPdLnPR6GALtnCOe9RNPP1cmC_bkv9D1BE1o6_-0cMXQsodpPoRCeOP5EDt6EwqK0ys36MbCi3HNTWf7ZcItVi",
"expirationTime":null,
"keys":{"p256dh":"BLJQqNovnlJ28d5xteX8whwdby6l0BYLvC_iyNtY2nO7YXQSI-EOvdOs1LXy8F_EuH2MZi0FU_HoCO-5GRQYYVQ",
"auth":"tDcEgiy5M5tJ3_vXuuQ9uw"}
}
but I want to integrate with my Laravel API.
After the user login, I want to save the endpoint, public key, and auth
to the database.
Login Controller
public function authenticate(Request $request)
{
$credentials = $request->only('username', 'password');
// return $credentials;
$response = array(
'status' => 'Failed',
'msg' => '',
'is_success' => false,
'data' => ''
);
try {
if (!$token = JWTAuth::attempt($credentials)) {
$response["msg"] = "Wrong Username or Password";
$response["status"] = "Failed";
$response["is_success"] = false;
} else {
if (Auth::user()->is_active == 0) {
$response["msg"] = "Your account has not been activated";
$response["status"] = "Failed";
$response["is_success"] = false;
} else {
$data = array();
$user = User::find(Auth::user()->id);
$data['id'] = $user->id;
$data['fname'] = $user->fname;
$data['lname'] = $user->lname;
$data['email'] = $user->email;
$data['username'] = $user->username;
$response["msg"] = "Login Successfully";
$response["status"] = "Success";
$response["data"] = compact('token');
$response["user"] = Auth::user();
}
}
} catch (\Exception $th) {
$response["msg"] = $th->getMessage();;
$response["status"] = "Failed";
$response["is_success"] = false;
}
return $response;
}
I think the best way to solve this, is to make another model for that data, a one to one relationship between user model and push notification data model. Make a controller for CRUD operations on this new model, and just have another http call from the front end to store the data.

Session always returns null facebook php sdk

Hi I'm trying to get data from a user from facebook after he logs in whit facebook. But my session variable is always null .I'm currently using the laravel 4 framework. The code that you are seeing is being called as the callback function from facebook login.
$code = Input::get('code');
if (strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
$facebook = new Facebook(Config::get('facebook'));
$uid = $facebook->getUser();
if ($uid == 0) return Redirect::to('/')->with('message', 'There was an error');
$me = $facebook->api('/me');
$profile = Profile::whereUid($uid)->first();
if (empty($profile)) {
$user = new User;
$user->name = $me['first_name'].' '.$me['last_name'];
$user->email = $me['email'];
$user->save();
$profile = new Profile();
$profile->uid = $uid;
return $uid;
$profile->username = $me['name'];
$profile = $user->profiles()->save($profile);
}
$profile->access_token = $facebook->getAccessToken();
$profile->save();
$user = $profile->user;
Auth::login($user);
FacebookSession::setDefaultApplication(
Config::get('facebook.appId'),
Config::get('facebook.secret')
);
$helper = new FacebookRedirectLoginHelper('http://projectweb.app:8000/');
$session = $helper->getSessionFromRedirect();
if(isset($session))
{
$request = new FacebookRequest($session,'GET','/me');
$response = $request->execute();
$graph = $response->getGraphObject(GraphUser::classname());
$name = $graph->getName();
return $name;
}
else
{
return 'no sesssion';
}
You better try using a Laravel specific Package for that, here it is one, where you also have the details about installing and using it.
https://github.com/SammyK/LaravelFacebookSdk

How to validate duplicate entries before inserting to database - Codeigniter

I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.

Resources