How can i set expire time in otp in laravel8? - api

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

Related

i was trying to check api on postman using phalcon and i got respon 400

I got this error when i try to check using postman... u can see the error below
i got this massage
"code":400,"response":"Failed","message":"Your username is not registered. Please register a new user now!","data":null
public function loginAction()
{
$this->view->disable();
$credentials = $this->request->getJsonRawBody();
$response = new Response();
$username = $credentials->username;
$password = $credentials->password;
// $user = User::findFirst("user_username = '$username'");
$user = User::findFirst([
'conditions' => 'username = :username:',
'bind' => [
'username' => $username
]
]);
if($user !== NULL) {
$checkPassword = $this->security->checkHash($password, $user->password);
if($checkPassword === true) {
$this->session->set('username', [
'id' => $username->id,
'username' => $user->username,
]);

Laravel 8 API Authentication

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.

get data value from jsonResponse Laravel 8

I have two controller
the first one has a register method:
public function register(Request $request)
{
$generalTrait = new GeneralTrait;
$user = new User;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->type = $request->type;
$user->save();
return $generalTrait->returnData('user',$user);
}
and the second also has register method:
public function register(Request $request)
{
$generalTrait = new GeneralTrait;
$user = (new UserAuthController)->register($request);
$admin = Admin::create([
'admin_name' => $request->admin_name,
//'user_id' => $response->user->user_id,
'user_id' => $user_id
]);
//Admin created, return success response
return $generalTrait->returnSuccessMessage('Admin created successfully');
}
when I try to get data from (JsonResponse) $user I find this error:
ErrorException: Undefined property: Illuminate\Http\JsonResponse::$user
returnDate method in GeneralTrait return:
public function returnData($key, $value, $msg = ""){
return response()->json([
'status' => true,
'errNum' => "5000",
'msg' => $msg,
$key => $value
]);
}
I find same Error when I try to get the status from the $response
How can I fix it?
I fix it by replacing returnData with:
public function returnData($key, $value, $msg = ""){
return [
'status' => true,
'errNum' => "5000",
'msg' => $msg,
$key => $value
];}
so to get user_id from user I said:
'user_id' => ($response["user"])->user_id
I wish I knew what my mistake was, and how I could have fixed it some other way

Change Password in hashed function in laravel 5.6

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.

how to create logged in session in yii

i tried using hybrid auth for a facebook login on my yii app, but couldn't get it to work. so decided to work on my own. i managed to get it to retrieve data and store it in my DB. but yii, still doesn't detect user as logged in. here is part of my code in my controllers/FacebookController.php
if (app()->request->isAjaxRequest) {
$user = app()->request->getParam('user');
Shared::debug($user);
// verify one last time that facebook knows this guy
if ($user['id'] === app()->facebook->getUser()) {
if (!empty($user['email']))
{
$model = User::model()->findByEmail($user['email']);
}
else if (!empty($user['username']) && empty($user['email'])) //incase we don't get an email, we use a facebook email
{
$email = $user['username'].'#facebook.com';
$model = User::model()->findByEmail($email);
}
else
{
$model = false;
}
if (!empty($model))
{
// facebook email matches one in the user database
$identity = new UserIdentity( $model->email , null );
$identity->_ssoAuth = true;
$identity->authenticate();
if ($identity->errorCode === UserIdentity::ERROR_NONE) {
print_r($identity);
app()->user->login($identity, null);
echo json_encode(array('error' => false, 'success' => url('/')));
app()->end();
}
else {
echo json_encode(array('error' => 'System Authentication Failed', 'code' => 'auth'));
app()->end();
}
}
in my code above, when i print_r($identity); the object below is echoed. and FYI, the email xxxxxx#facebook.com is stored in the DB but app()->user->isGuest() still returns true. what am i doing wrong here?
UserIdentity Object
(
[_ssoAuth] => 1
[_id:UserIdentity:private] => 19
[username] => xxxxxx#facebook.com
[password] =>
[errorCode] => 0
[errorMessage] =>
[_state:CBaseUserIdentity:private] => Array
(
)
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
http://yiiframework.com/doc/api/1.1/CWebUser#login-detail
Instead of passing a null into app()->user->login($identity, null) try passing in a duration like
$duration = 3600*24*30; //30 days
app()->user->login($identity, $duration);
I have had problems setting duration to 0. Not sure why either. But this worked for me before