This is Register Function in AuthController.php
public function register(Request $request)
{
if($request->type == 'ServiceMen')
{
$u = Workers::where('mobile',$request->mobile)->first();
if($u != null)
{
if(Auth::attempt(['mobile' => $request->mobile, 'password' => 'password'])){
echo "in";
$user = Auth::user();
$success['token'] = $user->createToken('jhbasdj')->plainTextToken;
$success['mobile'] = $user->mobile;
//return response()->json($success, 200);
}
echo "else";
}
}
elseif($request->type == 'User')
{
$u = User::where('mobile',$request->mobile)->first();
if($u==null)
{
$input = $request->all();
$input['password'] = bcrypt('password');
$user = User::create($input);
}
if(Auth::attempt(['mobile' => $request->mobile, 'password' => 'password'])){
$user = Auth::user();
$success['token'] = $user->createToken('kjsdbvk')->plainTextToken;
$success['mobile'] = $user->mobile;
return response()->json($success, 200);
}
}
}
I need to login staff from workers table and user from user model but user authentication works fine. I don't know how to login with workers model as a staff.
please help me with this.
Related
When i am trying to expiry otp, is not working but i do not know what i am doing wrong. I set expiry time with Carbon but still not working. What should i do?. It needs config in app/config or something?
This is a part of my controller code
if(!$device_serial_number)
{
return ('error');
} else {
$otp = rand(100000,999999);
// Cache::put([$otp], now()->addSeconds(20));
$otp_expires_time = Carbon::now()->addSeconds(20);
Cache::put(['otp_expires_time'], $otp_expires_time);
Log::info("otp = ".$otp);
$user = User::where('phonenumber', $request->phonenumber)->update(['otp' => $otp]);
$token = auth()->user()->createToken('Laravel Password Grant Client')->accessToken;
// Log::info($request);
// $user = User::where([['phonenumber', '=', request('phonenumber')],['otp','=', request('otp')]])->first();
return response()->json(array(
'otp_expires_at'=> $otp_expires_time,
'otp' => $otp,
'token' => $token));
This is a part of my middleware code
Log::info($request);
$user = User::where([['phonenumber', '=', request('phonenumber')],['otp','=', request('otp')],['otp_expires_time', '=', request('otp_expires_time')]])->first();
$otp_expires_time = Carbon::now()->addSeconds(20);
if($user)
{
if(!$otp_expires_time > Carbon::now())
{
return response('the time expired');
} else {
Auth::login($user, true);
return response()->json(array(
'message' => 'You are logged in',
['user' => auth()->user()]));
return response('You are logged in');
$otp = rand(1000,9999);
Cache::put([$otp], now()->addSeconds(10));
$otp_expires_time = Carbon::now('Asia/Kolkata')->addSeconds(10);
Log::info("otp = ".$otp);
Log::info("otp_expires_time = ".$otp_expires_time);
Cache::put('otp_expires_time', $otp_expires_time);
$user = User::where('email','=',$request->email)->update(['otp' => $otp]);
$user = User::where('email','=',$request->email)->update(['otp_expires_time' => $otp_expires_time]);
As the title says, i have a little bit of trouble in this area of the application. So basically, in my UserController i hash the password & in the login page it's verified with the standard security tool. Everything from the form to the user is good, but the check fails to return true. I don't have any interactions with the password in beforeSave/beforeValidate. Any ideas?
UserController:
public function actionRegister()
{
$model = new User(['scenario' => 'register']);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->password_usr = Yii::$app->security->generatePasswordHash($model->password_usr);
if ($model->save()) {
Yii::$app->session->setFlash('success', 'User created');
return $this->redirect('/site/login');
} else {
die(print_r($model->getErrors()));
}
}
return $this->render('register', [
'model' => $model,
]);
}
SiteController:
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->login();
return $this->goBack();
}
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
User model:
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_usr);
}
Login form is the default as the yii2 generates
Maybe this is a problem
die(print_r($model->getErrors()));
login
public function actionLogin()
{
$this->layout = "login";
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
$model->password = '';
}
return $this->render('login', [
'model' => $model,
]);
}
signup
public function actionSignup()
{
$this->layout = "login";
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
the problem was the password field in the database, it was varchar(30) whilst generatePasswordHash returns a 60 char string
I want to change my password which is been hashed while saving.
How can i change the password?
'password' => Hash::make($data->password).
My Controller
$request->validate([
'oldpass' => 'required',
'password' => 'required|alphaNum|min:6',
'password_confirmation' => 'required|same:newpass',
]);
$id = $request->id;
$users = Auth::user()->whereId($id)->get();
foreach ($users as $user) {
if ($oldpass == $user->password) {
$user->update([
'password' => Hash::make($request->newpass)
]);
return view('\balance');
} else {
return 'error';
}
}
You should use Hash::check($old_password, $hashed_password), something like this:
public function passwordChange(Request $request, User $user_name) {
// find the loggedin user
$user = User::find(Auth::user()->id);
// validate rules
$validator = Validator::make($request->all(), [
'old_password' => 'required|min:6',
'password' => 'required_with:password_confirmation|required|min:6',
'password_confirmation' => 'confirmed|required|min:6',
]);
// what to do if validator fails
if ($validator->fails()) {
return redirect($user->user_name . '/settings')->withErrors($validator)->withInput();
} else {
$old_password = $request->input('old_password');
$new_password = $request->input('password');
$hashed_password = Auth::user()->password;
// checking the old pass with new one
if (Hash::check($old_password, $hashed_password)) {
$user->update([
'password'=> Hash::make($new_password)
]);
return redirect($user->user_name . '/settings')->with('success', 'Your Password updated.');
} else {
return redirect($user->user_name . '/settings')->with('success', 'Your Old password is wrong!');
}
}
}
Please also notice 'password' => 'required_with:password_confirmation and 'password_confirmation' => 'required|same:newpass' on validator. Hope it helps.
I have the below code in studentsController.php to add data to 2 tables from a form but im getting error. It is to add to students table, then add some data to the users table too. I feel i'm supposed to add something at the top via "use' keyword but I don't know.please help.
public function actionCreate() {
$model = new model();
$user = new Users();
if ($model->load(Yii::$app->request->post())) {
$model->id = Yii::$app->generateid->getGUID(); //this line caused the error
$model->save();
$studentId = $model->id;
if($user->load(Yii::$app->request->post()))
{
$user->id = $model->id;
$user->firstname = $model->firstname;
$user->lastname = $model->lastname;
$user->username = $model->phone;
$user->password = 'pass123'; //default password
$user->role = 'student';
$user->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'user' => $user,
]);
}
}
You seem to miss generateid in your web.php
It should be something like this
GenerateIDs.php inside #app/components folder
<?php
namespace app\components;
class GenerateIDs extends \yii\base\Component
{
public function getGUID()
{
//do your stuff here
}
//....
}
then in your #app/config/web.php you have something like
<?php
return [
'components' => [
'generateid' => [
'class'=>'app\components\GenerateIDs',
// other configurations for the component
],
],
];
then you can use it in your app as you wish
public function actionCreate() {
$model = new model();
$user = new Users();
if ($model->load(Yii::$app->request->post())) {
$model->id = Yii::$app->generateid->getGUID(); //this line caused the error
$model->save();
$studentId = $model->id;
if($user->load(Yii::$app->request->post()))
{
$user->id = $model->id;
$user->firstname = $model->firstname;
$user->lastname = $model->lastname;
$user->username = $model->phone;
$user->password = 'pass123'; //default password
$user->role = 'student';
$user->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'user' => $user,
]);
}
Please take a look at Yii2 guide on Components
This problem isset only in Chrome and Firefox. Opera and Safari works fine.
On login, I don't checking rememberMe option.
allowAutoLogin set to TRUE
Here is my login method from LoginForm model:
public function login()
{
if ($this->_identity === NULL)
{
$this->_identity = new UserIdentity($this->login, $this->password);
$this->_identity->authenticate();
}
if ($this->_identity->errorCode === UserIdentity::ERROR_NONE)
{
$duration = $this->rememberMe ? 3600 * 24 * 30 : 0; // 30 days
Yii::app()->user->login($this->_identity, $duration);
return TRUE;
}
else
return FALSE;
}
And here is my action:
public function actionLogin()
{
$model = new LoginForm;
// if it is ajax validation request
if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if (isset($_POST['LoginForm']))
{
$model->attributes = $_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if ($model->validate() && $model->login()) $this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login', array('model' => $model));
}
In the config (protected/config/main.php) you can change allowAutoLogin to false
'components' => array(
'user' => array(
// enable cookie-based authentication
'allowAutoLogin' => false,
),
Read more about Yii login states here http://www.yiiframework.com/doc/api/1.1/CWebUser