login error message when user is inactive - laravel

I have Laravel code that of login auth page, the problem is that when I login the inactive user, I should get error message that your user is not activated.
My code
public function postLogin(Request $request)
{
$credentials = $request->only(['username', 'password']);
$validator = Validator::make($credentials, [
'username' => 'required', 'password' => 'required',
]);
// If the user is activated then value will be 1 and not activated user will 0
// <--- THIS LINE
if(!$credentials['active'] = 1)
{
return Redirect::back()->withInput()->withErrors($validator);
return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
}
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
}
if (Auth::guard('admin')->attempt($credentials)) {
admin_toastr(trans('admin::lang.login_successful'));
return redirect()->intended(config('admin.prefix'));
}
return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
}

You haven't used the correct operator in your if statement. change
if(!$credentials['active'] = 1)
{
return Redirect::back()->withInput()->withErrors($validator);
return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
}
to
if(!$credentials['active'] == 1)
{
return Redirect::back()->withInput()->withErrors($validator);
return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
}
OR
if($credentials['active'] != 1)
{
return Redirect::back()->withInput()->withErrors($validator);
return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
}

Related

Not receiving the response of 400 using axios

This code is from my controller,
public function login(Request $request)
{
$credentials = [
'email' => $request->email,
'password' => $request->password
];
if (Auth::attempt($credentials)) {
$user = Auth::user();
$success['token'] = $request->user()->createToken('myApp')->plainTextToken;
$success['name'] = $user->name;
$response = [
'success' => true,
'data' => $success,
'message' => 'User login successful',
];
return response()->json($response, 200);
} else {
$response = [
'success' => false,
'message' => 'User login failed',
];
return response()->json($response, 400);
}
}
This is my axios method,
const login = async () => {
await axios.post("/api/login", form).then((response) => {
if (response.data.success) {
console.log(response.data.message);
} else {
console.log(response.data.message);
}
});
};
Here in the controller if the condition is false I don't receive any response.If I remove the 400 from return response()->json($response, 400); It gives me a response with 200 code. I don't want it to happen since this is an error. Appreciate it if somebody can point me to the error. Thanks
you need a .catch() here like this:
const login = async () => {
await axios.post("/api/login", form)
.then((response) => {
// Handle API success logic here
if (response.data.success) {
console.log(response.data.message);
} else {
console.log(response.data.message);
}
})
.catch(({message}) => {
// Error response will always take you here
console.log(message)
})
};
UPDATE
from your controller send the response as 200 for both cases:
if($auth){
$response = [
'success' => true,
'message' => 'User login success',
];
return response()->json($response, 200);
} else {
$response = [
'success' => false,
'message' => 'User login failed',
];
return response()->json($response, 200);
}
and then make a call as:
const login = async () => {
await axios.post("/api/login", form)
.then((response) => {
// Handle API success logic here
if (response.data.success) {
console.log(response.data.message);
} else {
console.log(response.data.message);
}
})
}
UPDATE #2
in your else part of controller:
else {
$response = [
'success' => false,
'message' => 'User login failed',
];
return response($response["message"], 400);
}

Flutter + Laravel : can't register new user on server

I have flutter app with this register request :
var url = 'xxxxxxx/api/v1/';
// register-----------------
registerToApp(password, username, email, context) async {
var newurl = Uri.parse(url + 'register');
var data = {
'password': password,
'username': username,
'email': email,
};
if (username == '' || password == '' || email == '') {
showSnackBar(context, 'Username and Password and Email must be fill');
} else {
try {
var response = await http.post(newurl, body: data);
var result = jsonDecode(response.body);
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
final SharedPreferences prefs = await _prefs;
prefs.setString('username', result['username']);
prefs.setString('token', result['token']);
showSnackBar(context, result['status']);
return result;
} catch (e) {
print(e);
}
}
}
when I tested it on local server it success but after I upload the same api to server I get this error on VsCode :
<script>document.cookie = "humans_21909=1"; document.location.reload(true)
I tested the api on postman on localhost it is succes too on server I get error 409 conflict.
the api created by Lumen :
public function register(Request $request)
{
$id=CreateRandomId::get_id('users');
$password = password_hash($request->password, PASSWORD_DEFAULT);
$users_count= User::where('username',$request->username)->get();
$email_count= User::where('email',$request->email)->get();
$credentials = request(['username', 'password']);
if(count($users_count)>0){
$data = [
'status' => 'username found',
];
}
else {
if (count($email_count)>0){
$data = [
'status' => 'email is found',
];
}
else {
$user = User::create(
[
'id'=>$id,
'username'=>$request->username,
'password'=>$password,
'email'=>$request->email,
'role'=>'user'
]);
if($user){
$credentials = request(['username', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
else{
$data = [
'username'=>$request->username,
'password'=>$password,
'email'=>$request->email,
'status' => 'success',
'token' => $token
];}
}
else{
$data = [
'status' => 'failed',
];
}
}
}
return $data;
}
I copied same controller and router to server ,but don't work, what can I do ?
the route is :
$router->group(['prefix'=>'/api/v1'],function () use ($router) {
$router->get('/',function (){
return "welcome";
});
$router->group(['prefix'=>'/'],function () use ($router) {
$router->post('/register','AuthController#register');
$router->post('/login','AuthController#login');

Signin with facebook

In my code I check the account status from users table if it is 1 then shows the detail of user. By default the value of account status is 1. When i run the code that condition doesn't work. Here is my code. Please Help. Thanks in advance.
public function signInFacebook(SignInFacebookUser $request)
{
if($profile_picture = $request->hasFile('profile_picture')) {
$profile_picture = time().'.'.$request->profile_picture->getClientOriginalExtension();
$request->profile_picture->move(public_path('Storage/ProfileImages'), $profile_picture);
$profile_picture = 'Storage/ProfileImages/'.$profile_picture;
} else {
$profile_picture = NULL;
}
try {
$user = User::updateOrCreate([
'facebook_id' => $request->input('facebook_id'),
],
[
'name' => $request->input('name'),
'surname' => $request->input('surname'),
'date_of_birth' => $request->input('date_of_birth'),
'email' => $request->input('email'),
'city' => $request->input('city'),
'university' => $request->input('university'),
'profile_picture' => $profile_picture,
]);
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
return response()->json(['message' => 'Duplicate Entry']);
}
}
$token = JWTAuth::fromUser($user);
if($user->account_status == 1) {
$userDetail = $user->where('id', $user->id)->first();
return response()->json(['token' => $token, 'user' => $userDetail], 200);
}
else {
return response()->json(['message' => 'you are not active on app, contact to support team'], 200);
}
}
Here is the changing I done in my code and it works.
public function signInFacebook(SignInFacebookUser $request)
{
if($profile_picture = $request->hasFile('profile_picture')) {
$profile_picture = time().'.'.$request->profile_picture->getClientOriginalExtension();
$request->profile_picture->move(public_path('Storage/ProfileImages'), $profile_picture);
$profile_picture = 'Storage/ProfileImages/'.$profile_picture;
} else {
$profile_picture = NULL;
}
try {
$user = User::updateOrCreate([
'facebook_id' => $request->input('facebook_id'),
],
[
'name' => $request->input('name'),
'surname' => $request->input('surname'),
'date_of_birth' => $request->input('date_of_birth'),
'email' => $request->input('email'),
'city' => $request->input('city'),
'university' => $request->input('university'),
'profile_picture' => $profile_picture,
]);
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
return response()->json(['message' => 'Duplicate Entry']);
}
}
if(!$user) {
return response()->json(['message' => 'failed to signin with facebook'], 200);
}
$userDetail = $user->where('id', $user->id)->first();
if ($userDetail->account_status == 1) {
$token = JWTAuth::fromUser($user);
return response()->json(['token' => $token, 'user' => $userDetail], 200);
} else {
return response()->json(['message' => 'you are not active on app, contact to support team'], 200);
}
}

ErrorException in Encrypter.php line 106: unserialize(): Error at offset 0 of 82 bytes

any some body can help me to fix that error.
this my error :
enter image description here
here his my code
public function dologin() {
$input = Input::all();
$rules = [
'username' => 'required',
'password' => 'required|min:6',
];
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
Alert()->info('Username dan password tidak boleh kosong Panjang Password minimal 6 huruf', 'Info')->persistent('OK');
return redirect()->route('auth.login');
} else {
$user = CoreUser::where('username', $input['username'])->orWhere('user_email', $input['username'])->first();
if ($user) {
if($user->user_active != 1){
Alert()->error('Username sudah tidak aktif', 'Info')->persistent('OK');
return redirect()->route('auth.login')->withErrors("User tidak aktif");
}
if (Hash::check($input['password'], $user->password)) {
$session = [
'username' => $user->username,
'password' => $input['password']
];
$remember = true;
if (Auth::attempt($session, true)) {
return redirect()->intended('/');
} else {
// no action
dd("failed attempt");
}
} else {
//dd("hash check failed");
// no action
}
}
Alert()->error('Username dan password tidak sesuai', 'Gagal')->persistent('OK');
return redirect()->route('auth.login')->withErrors("Invalid Username or Password");
}
}

This webpage has a redirect loop in Laravel 4

I'm busy with a tutorial and I ended up getting an error that says
This webpage has a redirect loop
I know that the problem is here in my routes.php
Route::group(["before" => "guest"], function(){
$resources = Resource::where("secure", false)->get();
foreach($resources as $resource){
Route::any($resource->pattern, [
"as" => $resource->name,
"uses" => $resource->target
]);
}
});
Route::group(["before" => "auth"], function(){
$resources = Resource::where("secure", true)->get();
foreach($resources as $resource){
Route::any($resource->pattern, [
"as" => $resource->name,
"uses" => $resource->target
]);
}
});
UserController
class UserController extends \BaseController {
public function login()
{
if($this->isPostRequest())
{
$validator = $this->getLoginValidator();
if($validator->passes())
{
$credentials = $this->getLoginCredentials();
if(Auth::attempt($credentials)){
return Redirect::route("user/profile");
}
return Redirect::back()->withErrors([
"password" => ["Credentials invalid."]
]);
}else{
return Redirect::back()
->withInput()
->withErrors($validator);
}
}
return View::make("user/login");
}
protected function isPostRequest()
{
return Input::server("REQUEST_METHOD") == "POST";
}
protected function getLoginValidator()
{
return Validator::make(Input::all(), [
"username" => "required",
"password" => "required"
]);
}
protected function getLoginCredentials()
{
return [
"username" => Input::get("username"),
"password" => Input::get("password")
];
}
public function profile()
{
return View::make("user/profile");
}
public function request()
{
if($this->isPostRequest()){
$response = $this->getPasswordRemindResponse();
if($this->isInvalidUser($response)){
return Redirect::back()
->withInput()
->with("error", Lang::get($response));
}
return Redirect::back()
->with("status", Lang::get($response));
}
return View::make("user/request");
}
protected function getPasswordRemindResponse()
{
return Password::remind(Input::only("email"));
}
protected function isInvalidUser($response)
{
return $response === Password::INVALID_USER;
}
public function reset($token)
{
if($this->isPostRequest()){
$credentials = Input::only(
"email",
"password",
"password_confirmation"
) + compact("token");
$response = $this->resetPassword($credentials);
if($response === Password::PASSWORD_RESET){
return Redirect::route("user/profile");
}
return Redirect::back()
->withInput()
->with("error", Lang::get($response));
}
return View::make("user/reset", compact("token"));
}
protected function resetPassword($credentials)
{
return Password::reset($credentials, function($user, $pass){
$user->password = Hash::make($pass);
$user->save();
});
}
public function logout()
{
Auth::logout();
return Redirect::route("user/login");
}
}
GroupController
class GroupController extends \BaseController {
public function indexAction()
{
return View::make("group/index", [
"groups" => Group::all()
]);
}
public function addAction()
{
$form = new GroupForm();
if($form->isPosted()){
if($form->isValidForAdd()){
Group::create([
"name" => Input::get("name")
]);
return Redirect::route("group/index");
}
return Redirect::route("group/add")->withInput([
"name" => Input::get("name"),
"errors" => $form->getErrors()
]);
}
return View::make("group/add", [
"form" => $form
]);
}
public function editAction()
{
$form = new GroupForm();
$group = Group::findOrFail(Input::get("id"));
$url = URL::full();
if($form->isPosted()){
if($form->isValidForEdit()){
$group->name = Input::get("name");
$group->save();
$group->users()->sync(Input::get("user_id", []));
$group->resources()->sync(Input::get("resource_id", []));
return Redirect::route("group/index");
}
return Redirect::to($url)->withInput([
"name" => Input::get("name"),
"errors" => $form->getErrors(),
"url" => $url
]);
}
return View::make("group/edit", [
"form" => $form,
"group" => $group,
"users" => User::all(),
"resources" => Resource::where("secure", true)->get()
]);
}
public function deleteAction()
{
$form = new GroupForm();
if($form->isValidForDelete()){
$group = Group::findOrFail(Input::get("id"));
$group->delete();
}
return Redirect::route("group/index");
}
}
but I'm not sure how to go about fixing it especially since I was following a tutorial.

Resources