Session always returns null facebook php sdk - session

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

Related

Laravel Date assign errorr

I have small problem in app. Backend is Laravel and Front end is Nuxtjs.
When User registered on app,then users must be wait antill Administartor approved.
When Admin approved this user we give them 3 months subscription.
In my code this part is not working.
$user->activated_at = now();
$user->activated_at = date('Y-m-d H:i');
{
$user = User::find($id);
if (is_null($user)) {
return $this->sendError('admin_messages.user_not_found');
}
$user->status = User::ACTIVE;
$user->activated_at = now();
$user->activated_at = date('Y-m-d H:i');
dd($user->activated_at);
$user->save();
Mail::to($user->email)->queue(new ApproveNotificationMail($user));
return $this->sendResponse('admin_messages.user_activated');
}
$user->activated_at = \Carbon\Carbon::now()->format('Y-m-d H:i');
You can use mutator in your User model, to force activated_at format:
public function setActivatedAtAttribute( $value ) {
$this->attributes['activated_at'] = (new Carbon($value))->format('Y-m-d H:i');
}
You can define a format for date columns using:
protected $dateFormat = 'Y-m-d H:i';
Note that you can directly use:
$user->activated_at = \Carbon\Carbon::now()->format('Y-m-d H:i');

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

Requesting SOAP using CURL on Codieigniter 4

I am consuming a service using CURL. I am able to connect all the functions of the services in the form of a CXF Service List using the following code.
$client = \Config\Services::curlrequest();
$response = $client->request('GET', 'www.soapservice.co.za/service');
var_dump($response->getBody());
Var Dump Returns a string with Available services
The service has 10 functions listed in this manner getDataFunction.
How do I invoke the function? Or how do I get the contents of the body and start using Service functions?
Any help would be appreciated
This is how I resolved my issue using Codeignter 4 and Soap Client.
public function ownersearch()
{
helper(['form']);
$username = "";
$password = "";
$url = 'getProperty?wsdl';
$first_name = $this->request->getVar('first_name');
$second_name = $this->request->getVar('second_name');
$last_name = $this->request->getVar('last_name');
$user_id = $this->request->getVar('user_id');
$session_id = session()->get('user_id');
$client = new \SoapClient($url);
$deedsusagemodel = new UsageLogModel();
$args = [
'idNumber'=> $user_id,
'username'=> $username,
'password' => $password,
'officeCode' => 1
];
$usageData = [
'user_id' => $session_id
];
if($user_id != Null){
$response = $client->getFunctionByIDNumber($args);
$ndata = $response->return;
if($ndata->errorResponse->errorCode == 64)
{
$error = $ndata->errorResponse->errorDescription;
return $this->fail($error);
}
if($ndata->errorResponse->errorCode == 550)
{
$error = $ndata->errorResponse->errorDescription;
return $this->fail($error);
}
else{
$usagemodel->insert($usageData);
return $this->respond($ndata, 200);
}
}
}

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.

Laravel Sentry Update the User

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

Resources