I am unable to understand why this error appears. I have created a function for user to give its credentials and log in.
Route of the function is
Route::any('login','UserController#authenticate');
public function authenticate(Request $request) {
if($request->isMethod('post')) {
$email = $request->input('email');
$password = $request->input('password');
if(Auth::attempt(array('email' => $email, 'password' => $password), true)) {
return redirect()->intended('publicPages.home_startup')->withErrors('Congratulations! You are logged in');
} else {
return redirect()->intended('publicPages.login')->withErrors('Sorry! Login Failed');
}
}
}
You will probably need this line of code in the top.
use Illuminate\Http\Request;
If you have it, you can upload the project to a repository to help better?
Try the above answer or this, both are the same
public function authenticate(Illuminate\Http\Request $request) {
if($request->isMethod('post')) {
$email = $request->input('email');
$password = $request->input('password');
if(Auth::attempt(array('email' => $email, 'password' => $password), true)) {
return redirect()->intended('publicPages.home_startup')->withErrors('Congratulations! You are logged in');
} else {
return redirect()->intended('publicPages.login')->withErrors('Sorry! Login Failed');
}
}
}
Related
I'm working on an api in Laravel and want to edit the login procedure a bit.
Users log in with a username and a password but as a third parameter I want to add an app_id.
This is because usernames can be double in the database when the app_id is different. This is my current login code. It's using JWT as a driver.
$credentials = request(['username', 'password']);
if(!$token = auth()->attempt($credentials)) {
return response()->json([
'error' => ['code' => 1],
'status' => 'error',
], 401);
}
How can I accomplish this?
Kind regards,
Kevin Walter
Edit: My entire AuthController
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('jwt.verify', ['except' => ['login', 'refresh']]);
}
/**
* Login to get JWT credentials
*/
public function login() {
//TODO: LOCKOUT AFTER X AMOUNT OF TRIES
if(!$token = auth()->attempt($this->credentials())) {
return response()->json([
'error' => ['code' => 1],
'status' => 'error',
], 401);
}
return $this->me(true, $token);
}
public function checkPin() {
$username = request('username');
$pincode = request('pincode');
$user = auth()->user();
if($user && $user->username && $user->pincode && $username == $user->username && $pincode == $user->pincode) {
return $this->outputJson(0, 'auth', 'checkPin',[
"firebase_key" => $this->create_custom_token($user->uid, true),
"pin_ok" => 1,
]);
} else {
return $this->outputJson(0, 'auth', 'checkPin', ["pin_ok" => 0]);
}
}
public function me($withToken = false, $token = "") {
$user = auth()->user();
$output = $user;
$output->groups = $user->groups;
$output->categories = $user->categories;
$output->hasPin = $user->hasPin();
$headers = array();
if($withToken) {
$headers["X-TOKEN-RETURN"] = $token;
}
return $this->outputJson('0', 'auth', 'me', $output, $headers);
}
public function logout() {
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
}
It was just as simple as merging the app_id in the credentials. This is the working example!
//Add app ID into the mix of credentials
protected function credentials()
{
return array_merge(request(['username', 'password']), ['app_id' => \request()->header('X-APP-ID')]);
}
/**
* Login to get JWT credentials
*/
public function login() {
//TODO: LOCKOUT AFTER X AMOUNT OF TRIES
if(!$token = auth()->attempt($this->credentials())) {
return response()->json([
'error' => ['code' => 1],
'status' => 'error',
], 401);
}
return $this->me(true, $token);
}
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)]);
}
}
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';
}
}
I'm learning both Laravel and UnitTesting at the moment, so this may be a stupid question.
I'm getting stuck on how to best test the controller function below:
UserController:
public function store()
{
$input = Input::all();
$user = new User($input);
if( ! $user->save()){
return Redirect::back()->withInput()->withErrors($user->getErrors());
}
return Redirect::to('/user');
}
here's the test as I have it so far:
/**
* #dataProvider providerTestUserStoreAddsUsersCorrectly
*/
public function testUserStoreAddsUsersCorrectly($first_name, $last_name, $email, $password)
{
$response = $this->call('POST', 'user', array('first_name'=>$first_name, 'last_name'=>$last_name, 'email'=>$email, 'password'=>$password));
}
public function providerTestUserStoreAddsUsersCorrectly(){
return array(
array("FirstName", "LastName", "Email#add.com", "pass1234")
);
}
This is actually working and adding the user to the db correctly, but I'm not sure how to test the output / what assertions to use as the response should be to add the user to the db and to redirect to the /user page.
How do I finish this test?
If you need to check success status then you can simply send status code from your controller
and check status in test
public function store()
{
$input = Input::all();
$user = new User($input);
if( !$user->save() ){
return array("status"=>'failed');
}
return array("status"=>'success');
}
public function testUserStoreAddsUsersCorrectly($first_name, $last_name, $email, $password)
{
$requested_arr = [
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'password' => $password
];
$response = $this->call('POST', 'user', $requested_arr);
$data = json_decode($response ->getContent(), true);
if ($data['status']) {
$this->assertTrue(true);
} else {
$this->assertTrue(false);
}
}