I want to create a forgot password functionality of admin panel but, now I am using the custom admin login functionality in my AdminController. how can I create a forgot password functionality with a token for the admin panel ?
MY AdminController Code Here ...
login Method
public function login(Request $request)
{
if($request->isMethod('post')) {
$data = $request->input();
$adminCount = Admin::where([
'username' => $data['username']
'password'=> md5($data['password']),
'status'=> 1
])->count();
if($adminCount > 0){
//echo "Success"; die;
Session::put('adminSession', $data['username']);
return redirect('/admin/dashboard');
}else{
//echo "failed"; die;
return redirect('/admin')->with('flash_message_error','Invalid Username or Password');
}
}
return view('admin.admin_login');
}
Reset Method
public function reset(ResetPasswordRequest $request)
{
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->resetPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect($this->redirectPath())->with('status', trans($response));
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}
You should try this:
public function reset(ResetPasswordRequest $request)
{
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->resetPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect($this->redirectPath())->with('status', trans($response));
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}
Related
in this simple code i created function to created users into database, after created them i can't verify username and password there and i get false
public function store(RequestUsers $request)
{
$user = User::create(array_merge($request->all(), ['username'=>'testtest', 'password' => bcrypt('testtest')]));
if ($user->id) {
dd(auth()->validate(['username'=>'testtest','password'=>$user->password]));
} else {
}
}
what's problem of my code which i can't verify created user?
full my login controller:
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if (auth()->validate($request->only('username','password'))) {
$user = User::whereUsername($request->username)->first();
if ($user->lock) {
$request->session()->flash('error',__('message.your_account_locked'));
return view('layouts.backend.pages.auth.account.locked_account');
}elseif (!$user->active) {
$checkActivationCode = $user->activationCode()->where('expire', '>=', Carbon::now())->latest()->first();
if ($checkActivationCode != null) {
if ($checkActivationCode->expire > Carbon::now()) {
$this->incrementLoginAttempts($request);
$request->session()->flash('error',__('message.please_active_your_account'));
return view('layouts.backend.pages.auth.account.active_account');
}
}else{
return redirect()->to('/page/userAccountActivation/create');
}
}
}
if ($this->attemptLogin($request)) {
//dd('aaaaaa');
return $this->sendLoginResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
public function redirectToProvider()
{
return Socialite::driver('google')->redirect();
}
public function handleProviderCallback()
{
$socialUser = Socialite::driver('google')->stateless()->user();
$user = User::whereEmail($socialUser->getEmail())->first();
//dd($socialUser->getAvatar());
if (!$user) {
$data = [
'name' => $socialUser->getName(),
'email' => $socialUser->getEmail(),
'avatar' => str_replace('sz=50', 'sz=150', $socialUser->getAvatar()),
'mobileNumber' => '',
'loginType'=>'google',
'password' => bcrypt($socialUser->getId()),
];
//dd($data);
$user = User::create($data);
}
if ($user->active == 0) {
$user->update([
'active' => 1
]);
}
auth()->loginUsingId($user->id);
return redirect('/system/UserLoginWithGoogle');
}
public function show()
{
return view('auth.login');
}
protected function validateLogin(Request $request)
{
$this->validate($request, [
'username' => 'required|string',
'password' => 'required|string',
'g-recaptcha-response', 'recaptcha'
]);
}
}
dd(auth()->validate(['username'=>'testtest','password'=>$user->password]));
Validate method expects the array to hold plain text value for the password. $user->password would be the hashed value, and it will always return false for that reason.
Changing that to:
dd(auth()->validate(['username'=>'testtest','password'=>'testtest']));
should yield the desired output.
I want to create a token encoded with user role. I have tried with seeing the documentation, But I am not getting a token. what I have tried.
I am using laravel 5.8 and package version "tymon/jwt-auth": "^1.0.0-rc.2"
Thank you
AuthController
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->guard('api')->attempt($credentials)) {
return response()->json(['errors' => 'In-valid username and Password'], 401);
}
$customClaims =[
'role' => auth('api')->user()->getRoleNames()
];
$payload = JWTFactory::make($customClaims);
$token = JWTAuth::encode($payload);
return $this->respondWithToken($token);
}
protected function respondWithToken($token)
{
return response()->json([
'success' => true,
'access_token' => $token,
'token_type' => 'bearer',
]);
}
Based on the documentation, you might need to do attempt() twice, like this:
public function login()
{
$credentials = request(['email', 'password']);
if (!auth()->guard('api')->claims(['role' => 'bar'])->attempt($credentials)) {
return response()->json(['errors' => 'In-valid username and Password'], 401);
}
$token = auth('api')->claims(['role' => auth('api')->user()->getRoleNames()])->attempt($credentials);
return $this->respondWithToken($token);
}
Your User MOdel should like this
class User extends Authenticatable implements JWTSubject
{
use Notifiable, HasRoles;
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
public function login()
{
$credentials = request(['email', 'password']);
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(['errors' => 'In-valid username and Password'], 401);
}
$customClaims =[
'role' => auth('api')->user()->getRoleNames()
];
$payload = JWTFactory::make($customClaims);
$token = JWTAuth::encode($payload);
return $this->respondWithToken($token);
}
Try This
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
class AuthenticateController extends Controller
{
public function login(Request $request)
{
// grab credentials from the request
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (!auth()->guard('api')->claims(['role' => 'bar'])->attempt($credentials))
{
return response()->json(['errors' => 'In-valid username and Password'], 401);
}
$token = auth('api')->claims(['role' => auth('api')->user()->getRoleNames()])->attempt($credentials);
return $this->respondWithToken($token);
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
}
My code is given below.
I am facing problem. When I want check by username and password.
password change every time. so I am unable to give result by email password.
public function login()
{
$data = Input::all();
print_r($data);
$email= $data['email'];
$password= bcrypt($data['password']);
echo $password;
$count = User::where('email', '=',$email);
$count->Where('password', '=', $password);
$count_row=$count->get()->count();
echo $count_row; die;
if($count_row==1)
{
$users = User::where('email', '=',$email);
$users->Where('password', '=', $password);
$users->select(
'id','name','email',
'username','address','zip',
'city','country','phone_number',
'domain','type') ;
$result=$users->get();
$response= response()->json(['success'=>true,'message'=>'success', 'data'=>$result]);
return $response;
}
else
{
$response= response()->json(['success'=>false,'message'=>'Not Login successfull']);
return $response;
}
}
According to the docs, the correct way to verify a password is
Hash::check('plain-text', $hashedPassword)
So you can rewrite your function as
public function login()
{
$email = Input::get('email');
$user = User::where('email', '=', $email)->first();
if (!$user) {
return response()->json(['success'=>false, 'message' => 'Not Login successfull']);
}
if (!Hash::check(Input::get('password'), $user->password)) {
return response()->json(['success'=>false, 'message' => 'Not Login successfull']);
}
return response()->json(['success'=>true,'message'=>'success', 'data' => $user]);
}
Or even simpler
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (!Auth::attempt($credentials)) {
return response()->json(['success'=>false, 'message' => 'Not Login successfull']);
}
$user = User::where('email', '=', $request->get('email'))->first()
return response()->json(['success'=>true,'message'=>'success', 'data' => $user]);
}
New to JWT and i want to simply change my password after that i try to log in it is not working.
My update password function code :
public function resetPassword(ResetPasswordRequest $request, JWTAuth $JWTAuth)
{
$password = Hash::make($request->password);
$user = User::where('email', '=', $request->email)->first();
if(!$user) {
return response()->json([
'message' => "Credential do not match",
'status_code' => 403,
]);
}
if($user) {
$user->password = $password;
$user->save();
}
return response()->json(['message' => 'Your password has been changed successfully','status_code' => 204]);
}
This function working fine after i try to log in it is return $token null.
My login controller code :
public function login(LoginRequest $request, JWTAuth $JWTAuth)
{
$credentials = $request->only(['email', 'password']);
try {
$token = Auth::guard()->attempt($credentials);
if(!$token) {
return response()->json([
'message' => "Email and password do not match",
'status_code' => 403,
]);
}
$user = Auth::user();
$user->last_login = Carbon::now();
$user->save();
$user = Auth::user();
$user->UserDeviceData()->firstOrCreate([
'device_id' => $request->device_id
]);
} catch (JWTException $e) {
return response()->json([
'message' => "Internal server error",
'status_code' => 500,
]);
}
return (new UserTransformer)->transform($user);
}
On user model :
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
What is the problem ? It is a right way to do a change password ?
While resetting your password, you are hashing your password two times one in resetPassword function and second in setPasswordAttributeso you need to replace
this
$password = Hash::make($request->password);
with this
$password = $request->password;
in your resetPassword function
I have been searching for solutions and changing my code back and forth but nothing worked for me and I honestly have given up hope to fix it by myself.
It stays on the same page and does not Redirect::to('test2'), but stays in the same page and when I remove the else { return Redirect::to('login'), it gives me a blank page.
Any help would be extremely appreciated.
This is my user model file:
protected $fillable=['email', 'password'];
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
protected $primaryKey = 'id';
public static $rules = array(
'email' => 'required|email',
'password' => 'required',
);
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getReminderEmail()
{
return $this->email;
}
This is my routing functions:
Route::get('/login', function(){
return View::make('login');
});
Route::post('/login', function(){
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$userData = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($userData)) {
return Redirect::to('test2');
echo 'SUCCESS!';
} else {
return Redirect::to('login');
}
}
I have been struggling around with the hash at beginning.
1. If the length of your password column isn't 60 then it wouldn't allow you to login.
2. Before logging via Auth::attempt() instead try to fetch the data of the user using his username
and then compare the password using Hash::check()
try something this
Route::post('/login', function(){
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$email=Input::get('email');
$user=User::where('email','=',$email)->first();
$bool=Hash::check('your password for the email',$user->password);
if(bool)
{
if (Auth::attempt(Input::only('email','password')))
{
return Redirect::to('test2');
echo 'SUCCESS!';
}else{
return Redirect::to('login');
}
}else{
return echo 'password didn't matche';
}
}