Login using Auth in Laravel 5.4 with or condition - laravel-5.4

I have login form with 2 fields. First can take both email or mobile a nd second one is password.
How can I check this using auth ?
my code snippet is:-
if ( Auth::check([
'email' => $request->email,
'mobile' => $request->email,
'password' => $request->password,
false,
false
]))
{
$user = Auth::user();
return $user;
}
But this thing is combining the keys with and operator. How can I achieve email Or mobile and password.

Add condition before Auth::check() to detect format of provided login (email or mobile). First, change field name to login. Next:
$credentials = [];
if (filter_var($request->login, FILTER_VALIDATE_EMAIL)) {
$credentials['email'] = $request->login;
} else {
$credentials['mobile'] = $request->login;
}
if ( Auth::attempt($credentials)) {
$user = Auth::user();
return $user;
}
And remember to use Auth::attempt() instead of Auth::check() that checking if the user is already logged.

Related

How to create simply REST API Login?

I've trying to create login code in REST Server and while I use POSTMAN to check it, the output always show HTTP_BAD_REQUEST(Login Failed). The code is ignoring security.
I use REST from https://github.com/chriskacerguis/codeigniter-restserver
This is My Controller
public function index_post(){
$data_memb = array(
'id_member'=>$this->post('id_member'),
'password'=>$this->post('password')
);
$result = $this->Member_model_api->loginMember($data_memb);
if ($result == TRUE) {
$this->response([
'status' => true,
'message' => 'Login Successfull'
], REST_Controller::HTTP_OK);
} else {
$this->response([
'status' => false,
'message' => 'Login Failed'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
}
This is My Model
public function loginMember($data_memb)
{
$sql = 'SELECT * FROM member WHERE id_member = ?';
$binds = array($data_memb['id_member']);
$query = $this->db->query($sql, $binds);
if ($query->num_rows()>0) {
$rw_password = $query->result();
if (password_verify($data_memb['password'],
$rw_password[0]->password)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I expect the output is HTTP_OK(Login Successfull), or if you have more reference code, please tell me. Thanks for your help.
Since you are using POST method, you should use form-data while sending request.
I assume there may be some re-formatting issue on the server-side which might be preventing your login functionality to get verified.
Try printing both variables on the server-side and view the output.
var_dump($data_memb)
Nothing needs to send urlencoded in POST request.
Try changing the request type and see, this will work.

yii2 retrieve passwordHash for AccessTokenByUser

for use in Mobile App, I am trying to use Yii2 built in RestApi.
Now what I understand by the reading that we should disable session and set loginUrl property to false.
Now what I want is, I want a login screen for my app and want to authenticate against API.
how I can achieve the same.
Note:
I can authenticate with username and password for different controllers including users controller as well as bearer token.
also I read an example in" yii2 by example"
public function actionAccessTokenByUser($username, $passwordHash)
{
$accessToken = null;
$user = \app\models\User::findOne(['username' => $username, 'password_hash' => $passwordHash]);
//var_dump($passwordHash1);exit;
if($user!=null)
{
$user->access_token = Yii::$app->security->generateRandomString();
$user->save();
$accessToken = $user->access_token;
}
return [ 'access-token' => $accessToken ];
}
my question is how I get the `$passwordHash to supply here. I tried to look back and forth, but couldn't find any solution.
my main purpose is how I can implement a application login for mobile and thereon supply the accesstoken in the background wherever needed.
I believe I have refactored the code to achieve what I am looking. Open to suggestion or any flaw in my implementation.
here is what I have done.
public function actionAccessTokenByUser($username, $password)
{
$accessToken = null;
$username = \app\models\User::findByUsername($username);
if ($username!=null)
{
if($username->validatePassword($password)) $user = $username;
}
// $user = \app\models\User::findOne(['username' => $username, 'password_hash' => $passwordHash]);
if($user!=null)
{
$user->access_token = Yii::$app->security->generateRandomString();
$user->save();
$accessToken = $user->access_token;
}
return [ 'access-token' => $accessToken ];
}

not responding while login

I am new to CodeIgniter, and am trying to write code to log in after registering using a username and password in registration form using a PHPMyAdmin database. I am not getting anything when I try to log in, and it doesn't display an error or any message.
public function login() {
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password' , 'Password');
if($this->form_validation->run() == TRUE){
//check user in database
$this->db->select('username' , 'password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user = $query->row();
if($user->email){
$this->session->set_flashdata("Successful login");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
} else {
$this->session->set_flashdata("Error No such record found");
}
}
// load view and showing login form
$this->load->view('login');
}
First, you should read the documentation, looks like you skip that part, but it's very important!
Let's code a little bit and fix the bugs!
User data
Well, users will enter their data and we will check, if evertyhing is correct, we can redirect user to the protected page. You call for variables (see Query:) but you I'm not seeing on your code. You should put like that, before your query job
$username = $this->input->post("username");
$password = $this->input->post("password");
Now, you will be able to use the where to get the user data. =)
Query:
If read about OOP with PHP, you know that when you pass parameters to a method, each parameter have their own "action". In case of the select method, you should keep the data you want to select, on the same quote, because you the way you do, it's like you passing multiple parameters to the method.
$this->db->select('username, password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
First, to decide if the record exist or not, I prefer this way:
if($query->num_rows() > 0) {
$user_data = $query->row();
// We should verify if the user entered the password that correspond to the account.
// If not, we tell them that the password is incorrect.
if($password != $user_data->password) {
$this->session->set_flashdata("error", "Wrong password!");
return redirect(site_url());
}
// You can use the CI built in methods to work with sessions
$this->session->set_userdata(array(
'username' => $user_data->username,
));
$this->session->set_flashdata("success", "You are logged in!");
return redirect(site_url());
} else {
$this->session->set_flashdata("Error: No such record found");
redirect(site_url());
}
Flash data
Yeah, we use flashdata to show a message for the user. But, you should pass an item and the value of this item. Like that:
$this->session->set_flashdata('success', 'Successfully logged in!");
And, to retrieve the data on your views, you can do like...
<?php
$success = $this->session->flashdata("success");
$error = $this->session->flashdata("error");
if(!empty($success)) {
echo $success;
}
if(!empty($success)) {
echo $error;
}
?>
Recommendations
Sessions: https://codeigniter.com/userguide3/libraries/sessions.html
Database: https://www.codeigniter.com/userguide3/database/query_builder.html
Also, I recommed you, to take a minute on YouTube, to understand CodeIgniter.
If I forgot something, let me know! =)
Great Suggestion by webmasterdro's Answer.
I would like to extend it a little bit.
Looking at your code it looks like you have added the query to the controller.
And as a suggestion, if you are using an MVC framework then try to follow some basic MVC flow. because if you are not following that then it will be useless to use a framework.
User Controller to handle the post data and validations.
Use model to do the database query.
Use __construct for loading the common model or libraries.
Do not save plane password use md5 or other encryption technique.
Store User detail to the session which you can use further in after login.
Codeigniter has a great user guide. Try to follow that.
So, your code Should be your like this below.
Controller:
public function __construct() {
parent::__construct();
// Load model
$this->load->model('login_database');
}
public function your_controller_function_name() {
// Check validation for user input in SignUp form
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form_view');
} else {
$username = $this->input->post("username");
$password = $this->input->post("password");
$result = $this->login_database->registration_insert($username, $password);
//You can do this also if($result != FALSE)
if (!empty($result)) {
// You can set other data to the session also form here
$session_data = array(
'username' => $result['user_name']
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
// You can set flash data here
$this->load->view('your_view');
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('your_login_form_view', $data);
}
}
}
Model:
// Read data using username and password
public function login($username, $password) {
$this->db->select('username');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user_data = $query->row_array();
if ($query->num_rows() == 1) {
return user_data;
} else {
return false;
}
}
I have not added detail related to flash data because the previous answer has explained it properly.

i want to change my status in database when user did something

I have a requirement form in my application, and in that form, when the user inserts the requirements and then submit it, I send an email to a particular vendor.
What I want to do is, when the vendor sees that requirement, I want to
change the status from 0 to 1 automatically.
The code I have is this:
public function requirement()
{
$data["msg"]="";
$this->load->model('RequirementModel');
$data['user']=$this->RequirementModel->getusers();
$data['rolename']=$this->RequirementModel->getrolename();
if($this->input->post())
{
$this->RequirementModel->add_requirement($this->input->post());
$all_users = $this->input->post('user_id');
foreach($all_users as $key)
{
$get_email = $this->RequirementModel->get_user_email_by_id($key);
$role_name = $this->input->post('role_name');
$vacancies = $this->input->post('vacancies');
$experience = $this->input->post('experience');
$jd = $this->input->post('jd');
$hiring_contact_name = $this->input->post('hiring_contact_name');
$hiring_contact_number = $this->input->post('hiring_contact_number');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://md-in-42.webhostbox.net',
'smtp_port' => 465,
'smtp_user' => 'test3#clozloop.com',
'smtp_pass' => 'test3'
);
$this->load->library('email',$config);
$this->email->set_mailtype("html");
$this->email->from('test3#clozloop.com', 'bharathi');
$this->email->to($get_email);
$this->email->subject('this is our requirements pls go through it');
$link = 'Click on this link - Click Here';
$this->email->message($link);
print_r($get_email);
if($this->email->send())
{
echo "email sent";
}
else
{
echo "email failed";
}
}
}
$this->load->view('Requirements/requirements',$data);
}
I don't have any idea how to do this. Can anyone help me?
You can send requirement id in link sent to vendor as a query string.
For example -
$link = 'Click on this link -
<a href="http://localhost/job_portal/index.php/Login
/signin?requirement_id=1">Click Here</a>';
Now in your signin function update requirement id as below -
function signin()
{
if( isset( $_GET['requirement_id'] ) )
{
// update requirement column here
$this->db->where( array( 'requirement_id' => $_GET['requirement_id'] ) );
$this->db->update( 'requirement', array( 'status' => '1' ) );
}
// your sign in code here
}
Now whenever vendor clicks on link and logs in status of particular requirement will be updated.

How to update the updated_at column when the user logs in?

I'm trying to update the updated_at column to the current time, each time a user logs in.
But I get the following error:
InvalidArgumentException A four digit year could not be found Data missing
PHP
$input = Input::all();
$remember = (Input::has('remember')) ? true : false;
$auth = Auth::attempt([
'username' => $input['username'],
'password' => $input['password'],
'active' => 1
],$remember
);
if ($auth)
{
$user = Auth::user();
$user->updated_at = DB::raw('NOW()');
$user->save();
if ($user->userType==1)
{
return Redirect::intended('admin');
}
elseif ($user->userType==2)
{
return Redirect::intended('corporate');
}
elseif ($user->userType==3)
{
return Redirect::intended('trainer');
}
elseif ($user->userType==4)
{
return Redirect::intended('user');
}
}
You can use the Eloquent method touch() for this:
//instead of
$user->updated_at = DB::raw('NOW()');
$user->save();
// simply this:
$user->touch();
For one I would not use the updated_at column as that's the default timestamps name.
You would be better of with last_login
And just use the PHP date method.
$user->updated_at = date('Y-m-d G:i:s');
Hope this helps.
I think you're accidentally assigning a value instead of using array syntax. eg:
Model::create([
'key'='val'
]);
instead of:
Model::create([
'key'=>'val'
]);