How i can fix preg_match() expects parameter error? - php

When i try login to site from Steam, i received error:
ErrorException in SteamController.php line 50:
preg_match() expects parameter 2 to be string, object given
For test i try to delete code from line 50, but nothing happened.
My login function in SteamController.php
public function login()
{
if ($this->steamAuth->validate()) {
$steamID = $this->steamAuth->getSteamId();
$user = User::where('steamid64', $steamID)->first();
if (!is_null($user)) {
$steamInfo = $this->steamAuth->getUserInfo();
$nick = $steamInfo->getNick();
if (preg_match("/Admin|admins|admin|/i", $nick)) {
$nick = 'ADmin';
}
\DB::table('users')->where('steamid64', $steamID)->update(['username' => $nick, 'avatar' => $steamInfo->getProfilePictureFull()]);
if ($user->partner == 0) {
\DB::table('users')->where('steamid64', $steamID)->update(['partner' => \Request::cookie('ref')]);
}
} else {
$steamInfo = $this->steamAuth->getUserInfo();
$nick = $steamInfo->getNick();
if (preg_match("/|Admin|admins|admin/i", $nick)) {
$nick = 'Admin';
}
$user = User::create([
'username' => $nick,
'avatar' => $steamInfo->getProfilePictureFull(),
'steamid' => $steamInfo->getSteamID(),
'steamid64' => $steamInfo->getSteamID64(),
'partner' => \Request::cookie('ref')
]);
}
Auth::login($user, true);
return redirect('/');
} else {
return $this->steamAuth->redirect();
}
}
What i need to do, for fix error?

Due to lack of information, I'm assuming that you're using invisnik/laravel-steam-auth package to handle Steam social login.
Being that case, $steamInfo is a instance of Invisnik\LaravelSteamAuth\SteamInfo which extends Illuminate\Support\Fluent.
So, I'm guessing $steamInfo->getNick() is an attempt to retrieve the private $this->attributes['nick'] property, if that's the case, then you're doing it the wrong way.
$steamInfo->getNick() // returns itself, an object. (Thats probably why you're getting "expects parameter 2 to be string, object given").
// The correct way:
$steamInfo->nick;
// or
$steamInfo->get('nick');
Hope it helps.

Related

How can I display the name of my admin full name after login - Codeigniter

I am having a trouble on displaying my admin's full name, like for example admin full name is John Doe, it is not displaying. I am still learning codeigniter please give me advice thank you!
here is my controller
//Get username
$username = $this->input->post('username');
//Get and encrypt the password
$password = $this->input->post('password');
// Login user
$user_id = $this->role_model->login($username, $password);
if ($user_id) {
// Create session
$user_data = array(
'user_id' => $user_id,
'name' => $user_id->name,
'username' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//Set message
$this->session->set_flashdata('user_loggedin','You are now logged in');
redirect('pages/index');
here is my View - where I would like to display my full name, as you can see 'name' is the data field I have to display but it is does not show anything, it gives an error that says name is not defined.
<li><a> Welcome, <?php echo $this->session->name ?> </a></li>
Model
public function login($username, $password){
//Validate
$this->db->where('username',$username);
$this->db->where('password',$password);
$result = $this->db->get('users');
if ($result->num_rows() == 1) {
return $result->row(0)->id;
}else{
return false;
}
}
Your method login() returns only id = digit (return $result->row(0)->id;), not object (in controller your get $user_id->name).
Do this, in the model:
if ($result->num_rows() == 1) {
return $result->row(0); // fix
}else{
return false;
}
In the controller:
$user = $this->role_model->login($username, $password);
$user_data = array(
'user_id' => $user->id, // fix
'name' => $user->name, // fix
'username' => $username,
'logged_in' => true
);
It shows undefined because it is indeed undefined.
In your view your're trying to echo the returning value of a function called userdata(), does that function actually exist? Or is $this->session->userdata an array? in which that case, you need to use [ index ] to acces a member within an array. i.e. $this->session->userdata['name'], but also, that member needs to exist first.
controller :
if($this->Login_model->login_valid($email,$password))
{
$sessiondata = array(
'username' => $email
);
$this->session->set_userdata('logged_in', $sessiondata);
redirect('narson');
}
else
{
$this->session->set_flashdata('error',"Invalid Username And password");
redirect('login');
}
model:
public function login_valid($username,$password)
{
$this->db->where('username',$username);
$this->db->where('password',$password);
$query = $this->db->get('admin');
if($query->num_rows() > 0)
{
return true;
}
else
{
return false;
}
}

How to request for login with email and plain text password in cakephp3

I am new in php and working on REST API in cakephp3 for my android application.
after setting up php and composer and routing I created login function..
public function login() {
$this->request->allowMethod('post');
$this->loadModel('Users');
$entity = $this->Users->newEntity($this->request->data, ['validate' => 'LoginApi']);
if ($entity->errors()) {
$this->httpStatusCode = 400;
$this->apiResponse['message'] = 'Validation failed.';
foreach ($entity->errors() as $field => $validationMessage) {
$this->apiResponse['error'][$field] = $validationMessage[key($validationMessage)];
}
} else {
$hasher = new DefaultPasswordHasher();
$password = $hasher->hash($entity->password);
$user = $this->Users->find()
->where([
'email' => $entity->email,
'password' => $password
])
->first();
if (empty($user)) {
$this->httpStatusCode = 403;
$this->apiResponse['error'] = 'Invalid email or password.';
return;
}
$payload = ['email' => $user->email, 'name' => $user->name];
$this->apiResponse['token'] = JwtToken::generateToken($payload);
$this->apiResponse['message'] = 'Logged in successfully.';
isset($user);
isset($payload);
}
}
I use 123456 for password and this hasher returns random string every time, but the password which is already saved in database for 123456 is
$2y$10$f7K02jamD7ZeGHLcTkP6Weh6VsthMWHiwqHJmcqbsxuLCKGCQCGCu this.
that is why it gives Invalid password in response.
My question is how to match the exact same string or hashing for request.
thanks in advance.
With reference to this answer
Use this line
password_verify($entity->password, $user->password)
instead of this
$hasher = new DefaultPasswordHasher();
$password = $hasher->hash($entity->password);
you can try this function
public function login()
{
$this->request->allowMethod('post');
$this->loadModel('Users');
$entity = $this->Users->newEntity($this->request->data, ['validate' => 'LoginApi']);
if ($entity->errors()) {
$this->httpStatusCode = 400;
$this->apiResponse['message'] = 'Validation failed.';
foreach ($entity->errors() as $field => $validationMessage) {
$this->apiResponse['error'][$field] = $validationMessage[key($validationMessage)];
}
} else {
$user = $this->Users->find()->where(['email' => $entity->email])->first();
if (count($user)) {
if (password_verify($entity->password, $user->password)) {
$payload = ['email' => $user->email, 'password' => $user->password];
$this->apiResponse['token'] = JwtToken::generateToken($payload);
unset($user->password);
$this->apiResponse['response'] = array($user);
unset($user);
unset($payload);
} else {
$this->httpStatusCode = 403;
$this->apiResponse['error'] = 'Incorrect password';
return;
}
} else {
$this->httpStatusCode = 403;
$this->apiResponse['error'] = 'Email not found';
return;
}
}
}
The general idea would be to hash according to a key you specify.
An advice would be to keep changing the key periodically. You will then need to dehash your save into the clear again using the old key then rehash on new.
I'm not sure if the option is available to you, so you might want to take it with a grain of salt.
Cheers
First of all, CakePHP ships with authentication functionality out of the box, and I'd strongly suggest that you make use of that instead of running your own, given that it sounds as if you're looking for deterministic algorithms, this can very easily backfire.
If you are using CakePHP 3.5+, look into the authentication middleware plugin (currently in RC phase), for earlier CakePHP versions, use the authentication component.
For the sake of completeness, if you were to do this manually, you'd first query the user by its unique identifier (in your case the email address), and then compare the password at PHP level, using the password hashers AbstractPasswordHasher::check() implementation:
$user = $this->Users
->find()
->where([
'email' => $this->request->data('email')
])
->first();
if (!$user ||
$hasher->check($this->request->data('password'), $user->password) !== true
) {
// authentication failed
} else {
// authentication succeeded
}

strpos() expects parameter 1 to be string, object given laravel 5.5

This is my code:
public function getLists(Request $request)
{
$user = $request->user()->id;
$apikey = DB::table('apikey')->where('api_key', '=', $user);
if($apikey){
$mc = new MailChimp($apikey);
$mailchimp_ping = $mc->get('lists',['fields' =>
'lists.id,lists.name']);
return Response::json($mailchimp_ping, 200);
}
else
{
$errorResponse = [
'message' => 'Lists not found!',
'error' => '401'
];
return Response::json( $errorResponse);
}
}
I am trying to get mailchimp list based on logged in user id where i am doing wrong? is my where clause expects something else?
Any help would be highly appreciated!
Use the value() method to execute the query and get the key. For example, if a column with key is called apikey:
$apikey = DB::table('apikey')->where('api_key', $user)->value('apikey');
In my case this error came up when changed this:
Route::view('/report', '/main_pages/orders_parts/report')->name('guzorishi_order_1');
to
Route::get('/report/{order_id}', function ($order_id) {... })->name('guzorishi_order_1');
but forgot Route::view one
rename to Route::get

Laravel 5 Redirect from a sub-method

I'm using Socialite to get user information from facebook. All is going well but my redirect isn't working
Sub-routes
I read that it's not possible to do a redirect from a submethod, or
any method that's not in your routes.
But how else can i redirect the user after I logged them in?
My URL looks like this after the successfull facebook handshake
http://tmdb.app/auth/login/facebook?code=AQBTKNZIxbfdBruAJBqZ8xx9Qnz...
Code
class SocialController extends Controller {
public function login(Authenticate $authenticate, Request $request)
{
return $authenticate->execute($request->has('code'), $this);
}
public function userHasLoggedIn($data)
{
$user = User::where('provider_id', $data->id)->first();
if( !$user )
{
$user = User::create([
'name' => $data->name,
'email' => $data->email,
'provider' => 'facebook',
'provider_id' => $data->id
]);
}
// NOT WORKING!
return redirect('test');
}
}
Your login function should be handling the redirect.
I'm guessing execute returns $data if the user is sucessfully logged in and false if not.
class SocialController extends Controller {
public function login(Authenticate $authenticate, Request $request)
{
if($data = $authenticate->execute($request->has('code'), $this))
{
$user = User::where('provider_id', $data->id)->first();
// maybe delegate the user creation to another class/service?
if( !$user )
{
$user = User::create([
'name' => $data->name,
'email' => $data->email,
'provider' => 'facebook',
'provider_id' => $data->id
]);
}
return redirect('test');
}
return redirect('fail_view');
}
}
You can do it using PHP header function in Laravel sub method. I try it and works properly. Hope it can help you.
// You can using the following code
$url= url("about-laravel");
header("Location:" . $url);
exit;
// Or using the following code to redirect and keep set flash message
$result= $this->yourMethod(); // return redirect($this->route)->with('flash_message', 'I\'m Flash Message'); for TRUE or NULL for false
if( $result ){
return $result;
}

Laravel 4.2 session::get() method not returning session data in controllers

Hi help me,
login code
public function store()
{
$credentials = array(
'u_email' => Input::get('email'),
'password' => Input::get('password'));
if (Auth::attempt($credentials) ) {
$user = Auth::user()->toArray();
$userrole = with(new User)->get_user_role($user['u_id']);
$userobj['u_id'] = $user['u_id'];
$userobj['u_shortcode'] = $user['u_shortcode'];
$userobj['utype'] = $user['utype'];
$userobj['u_title'] = $user['u_title'];
$userobj['u_fname'] = $user['u_fname'];
$userobj['u_lname'] = $user['u_lname'];
$userobj['u_email'] = $user['u_email'];
$userobj['u_role'] = $userrole;
$userobj['id'] = Session::getId();
Session::put('admin', $userobj);
$value = Session::get('admin');
return Response::json([
'user' => $userobj ],
202
);
}else{
return Response::json([
'flash2' => 'Authentication failed'],
202
);
}
}
and my second controller is:
public function get_sessionobj()
{
var_dump(Session::all());
$value = Session::get('admin');
print_r($value);
exit();
}
when i am calling second controller after login then session data not printed. in login controller Session::get('admin') function returning data. and i am using file driver for session storage. I have seen my session file there was some data like this:
a:5:{s:6:"_token";s:40:"XrUgs7QLPlXvjvyzFaTdmDpqGL0aSZRzkJS0il9f";s:38:"login_82e5d2c56bdd0811318f0cf078b78bfc";s:1:"1";s:5:"admin";a:9:{s:4:"u_id";s:1:"1";s:11:"u_shortcode";s:5:"u1001";s:5:"utype";s:1:"1";s:7:"u_title";s:3:"Mr.";s:7:"u_fname";s:6:"Aristo";s:7:"u_lname";s:5:"Singh";s:7:"u_email";s:24:"chandan.singh#jetwave.in";s:6:"u_role";a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}s:2:"id";s:40:"cd074f7f61fcc88b3d92c482e57e8a12dc888958";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1410525787;s:1:"c";i:1410525787;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
Call a function get_sessionobj() in store function
Example:
public function store(){
$this->get_sessionobj();
}

Categories