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

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

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

Eloquent save method not working when the data comes from Vue frontend

I have this code in a Vue Component:
sendUserData(){
axios.post('/api/saveUser', {
data: {
id: this.id,
name: this.name,
email: this.email,
password: this.password
}
},
{
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
}
).then(response => {
if(response.data == 'success'){
this.$emit('userSaveSuccess')
} else {
this.$emit('userSaveError')
}
});
}
and I have this in a Laravel Controller:
public function saveUser($name = '', $email = '', $password = ''){
$id = request('data.id', 0);
$name = request('data.name', $name);
$email = request('data.email', $email);
$password = request('data.pswrd', $password);
Log::info(request());
if($id == 0){
$saveUser = new User;
} else {
$saveUser = User::find($id);
if($name == ''){
$name = $saveUser -> name;
}
if($email == ''){
$email = $saveUser -> email;
}
}
$saveUser -> name = $name;
$saveUser -> email = $email;
if($password != ''){
$saveUser -> password = bcrypt($password);
}
if($saveUser->save()){
return 'success';
} else {
return 'error';
}
}
My problem is, that it's output is success, but in the MySQL DB nothing has changed.
In the Log's I got this:
[2019-09-08 12:32:08] local.INFO: array (
'data' =>
array (
'id' => 2,
'name' => 'AdminTest',
'email' => 'admin#test.com',
),
)
(The original name is Admin -> the Laravel function got the request)
I tested it with Postman, too, and that time the save method worked.
What's the problem?
Edit:
Images
Edit2:
console.log(response) image
Replace your saveUser() method with the following and it will work.
/**
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function saveUser(Request $request){
// validate request data
$validator = \Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'pswrd' => 'required' // add your custom validation rule
]);
// throw an validation error with message
if ($validator->fails())
return response()->json(['message' => 'The given data was invalid.', 'errors' => $validator->errors()], 422);
// best way to get request input values ( laravel docs )
$id = $request->get('id') ?? 0;
$name = $request->name;
$email = $request->email;
$password = $request->psswrd;
// TODO: you can replace the logic with ( updateOrCreate($saveUser) )
if($id == 0){
$saveUser = new User;
} else {
$saveUser = User::find($id);
}
$saveUser -> name = $name;
$saveUser -> email = $email;
if($password != ''){
$saveUser -> password = bcrypt($password);
}
try{
$saveUser->save();
return response()->json(['message' => 'Success.', 'data' => $saveUser], 200);
}catch (\Exception $exception){
return response()->json(['message' => 'Error.', 'data' => $exception->getMessage()], 200);
}
}

Undefined index: password in EloquentUserProvider.php line 126 when JWT auth using mobile number as credential

Here is my User Login Function,
public function userLogin(Request $request){
$login_type = $request->input('login_type');
if(!$login_type){
return response()->json(['status'=>false,'message'=>'Login type is required']);
}
$input = $request->all();
$login_fb_status = $request->input('fb_login_status');
$array = array();
if($login_fb_status){
$facebook_id = $request->input('facebook_id');
if(!$facebook_id){
return response()->json(['status'=>false,'message'=>'facebook id is required']);
}else{
$user_details = User::where('facebook_id',$facebook_id)->first();
if(count($user_details) <= 0){
return response()->json(['status'=>false,'message'=>'Facebook id does not exist']);
}
$user_id = $user_details->id;
}
$credentials = array('user_id'=>$user_id);
//$credentials = $request->only('facebook_id');
$login_fb_status = 1;
}else{
if($login_type == 'phone_no'){
$credentials = $request->only('phone_no');
}else if($login_type == 'email'){
$credentials = $request->only('email', 'password');
}
$login_fb_status = 0;
}
$token = null;
try {
if (!$token = JWTAuth::attempt($credentials,$array,$login_fb_status)) {
return response()->json(['status'=>false,'message'=>'Invalid Credentials'], 422);
}
} catch (JWTAuthException $e) {
return response()->json(['failed_to_create_token'], 500);
}
$user = JWTAuth::toUser($token);
$account_status=$user->user_status;
return response()->json(['status' => true,'account_status'=>$account_status,'logged_user_details' => $user,'token'=>$token]);
// return response()->json(compact('token'));
}
I am getting Error when try to login with mobile as credential(mobile login not required password in my application ) But When i try with email and password it work perfectly, I am using Laravel 5.4 , The same code work perfectly for mobile login in shared hosting, But Not Working in digital ocean

login error message when user is inactive

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

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