I have created my API for logging users into my application, but then it responds with the else part as the response
{"error":true,"message":"Check your username or password"}
below is my controller
public function getLogin()
{
$user = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if (Auth::attempt($user))
{
$user = User::find(Auth::user()->id);
$role = $user->roles;
if ($role[0]->name == 'Customer')
{
return Response::json(['error' => false, 'message' => 'Customer Logged in successfully', "user"=>$user]);
}
else
{
return Response::json(['error'=>true, 'message'=>'Check your login details']);
}
}
else
{
return Response::json(['error' => true, 'message' => 'Check your username or password']);
}
}
Related
if($data)
{
$pass = $data['password'];
$authenticatePassword = password_verify($password, $pass);
if($authenticatePassword)
{
$ses_data = [
'id' => $data['id'],
'name' => $data['name'],
'email' => $data['email'],
'isLoggedIn' => TRUE
];
$session->set($ses_data);
return redirect()->to('/profile');
I want to make it so the admin can log in and direct it to his page.
do this in your admin controller
function index()
{
if($data)
{
$username= $this->input->post('username');
$password= $this->input->post('password');
$row= $this->admins->adminLogin($username, $password);
if(count($row)==1)
{
foreach($row as $val)
{
$data= array('USERID' =>$val->id,
'USERNAME' => $val->username,
'logged_in' => true,
'id' => $val->id,
);
$this->session->set_userdata($data);
}
redirect('admin/dashboard');
}
else
{
$this->session->set_flashdata('message','<div class="alert alert-danger">Invalid Username and Password.</div>');
}
}
$this->load->view('admin/index');
}
I want to get the errors from the server in the client, show them on the page when there's some troubles during login or registration, I think it's ok in the backend, but I don't know why they're not returning.
How to get that error messages from the validator in Vue?
I'm using: vuex, vue-router
My vuex file for login and register
actions: {
async login({ dispatch }, credentials) {
await axios.post('http://127.0.0.1:8000/api/login', credentials)
.then( res => {
if (res.data.success) {
// controllo se il token è buono
return dispatch('attempt', res.data.token)
}
})
.catch( err => {
console.log( err )
})
},
async attempt({ commit, state }, token) {
// blocco in caso ci fosse o meno il token
// se c'è il token
if (token) {
commit('SET_TOKEN', token)
}
// se non c'è
if(!state.token) {
return
}
// /blocco in caso ci fosse o meno il token
// provo a gettare l'user
try {
await axios.get('http://127.0.0.1:8000/api/user')
.then(res => {
commit('SET_USER', res.data)
})
} catch (e) {
commit('SET_TOKEN', null)
commit('SET_USER', null)
}
},
async register({ }, credentials) {
await axios.post('http://127.0.0.1:8000/api/register', credentials)
.then( () => {
})
.catch(err => {
console.log(err)
})
},
logoutAction({ commit }) {
return axios.post('http://127.0.0.1:8000/api/logout')
.then( () => {
commit('SET_TOKEN', null)
commit('SET_USER', null)
})
},
}
My controller
public function register(Request $request) {
$fields = $request->validate(
[
'name' => 'required|string',
'email' => 'required|string|unique:users,email',
'password' => 'required|string|confirmed'
]
);
$user = User::create([
'name' => ucwords($fields['name']),
'email' => $fields['email'],
'password' => bcrypt($fields['password']),
]);
$token = $user->createToken('token')->plainTextToken;
return response()->json(
[
'success' => true,
'user' => $user,
'token' => $token,
'message' => 'Registered successfully'
], 201);
}
public function login(Request $request) {
$fields = $request->all();
$validator = Validator::make($fields, [
'email' => 'required',
'password' => 'required'
]);
$user = User::where('email', $fields['email'])->first();
if($validator->fails()) {
return response()->json([
'message' => 'You must fill in all the fields!',
'errors' => $validator->errors()
], 401);
}
if(!$user || !Hash::check($fields['password'], $user->password)) {
return response()->json([
'message' => 'Invalid credentials.',
], 401);
}
$token = $user->createToken('token')->plainTextToken;
return response()->json(
[
'success' => true,
'user' => $user,
'token' => $token,
'message' => 'Logged in'
], 201);
}
public function logout(Request $request) {
auth()->user()->tokens()->delete();
return response()->json(
[
'message' => 'Logged out.'
]
);
}
Also I want to stop the user if the registration has empty fields, forcing him to stay in the register route, but with these settings down here the user will be redirected to the login page even if no registration fields are been typed in, as soon as I press enter or click 'register'.
p.s.: the 'home' route in which I'm pushing in the user is the page with the login form. So I want that the user will be redirect there only if the register form has been fulfilled.
submitRegistration() {
this.register(this.form)
.then(() => {
this.$router.push({name:'home'})
})
.catch((err) => {
// Ignore the vuex err regarding navigating to the page they are already on.
if (
err.name !== "NavigationDuplicated" &&
!err.message.includes(
"Avoided redundant navigation to current location"
)
) {
// But print any other errors to the console
console.log(err);
}
});
},
I have successfully coded the registration function and its working but I don't know how to send email confirmation link after registration successful. Because I am using JWT Auth for for login and sign up from flutter app with Laravel API.
My login code is:
public function loginapi(Request $request)
{
$input = $request->only('email', 'password');
$email = $request->email;
$jwt_token = null;
if (!$jwt_token = JWTAuth::attempt($input)) {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
]);
}
// get the user
$user = getuserbyemail($email);
$user_ver_status = $user->email_verified_at;
$verified;
if($user_ver_status != null || $user_ver_status != ''){
$verified = true;
}
else{
$verified = false;
}
return response()->json([
'success' => true,
'varified' => $verified,
'token' => $jwt_token,
'users' => $user
]);
}
My Registration Code is:
public function registerapi(Request $request)
{
$sponsor = $request->sponsor;
$username = $request->username;
$email = $request->email;
//$phone = $request->phone;
$password = $request->password;
$getemail = getuserbyemail($email);
$getusern = getuserbyusername($username);
//$getphone = getuserbyphone($phone);
$getSponsor = getuserbySponsor($sponsor);
if($getSponsor == null ||$getSponsor == ''){
return response()->json([
'success' => false,
'message' => 'Sponsor user dose not found...!',
], 401);
}
else if($getemail != null){
return response()->json([
'success' => false,
'message' => 'Email is already existed...!',
], 401);
}
else if($getusern != null){
return response()->json([
'success' => false,
'message' => 'Username is already existed...!',
], 401);
}
else{
$insertuser = insertUser($getSponsor->id, $username, $email, $password);
if($insertuser == "true"){
return response()->json([
'success' => true,
'message' => 'Your account has been registerd successfully...!',
]);
}
else if($insertuser == "false"){
return response()->json([
'success' => false,
'message' => 'There is an error while regestring your account...!',
]);
}
else{
return response()->json([
'success' => false,
'message' => 'There is an UnKnown error while regestring your account...!',
]);
}
}
}
This is my insertUser() Function:
function insertUser(string $sponsor, string $username, string $email, string $password){
$time_now = date("Y-m-d H:i:s");
$updated_at = $time_now;
$created_at = $time_now;
$sponsor_id = $sponsor;
$user_name = $username;
$user_email = $email;
//$user_phone = $phone;
$user_password = $password;
$createUser = User::create([
'sponsor_id' => $sponsor,
'user_name' => $user_name,
'email' => $user_email,
'phone' => null,
'earning' => 0,
'balance' => 0,
'city' => null,
'country' => null,
'image' => null,
'status' => 1,
'password' => Hash::make($user_password),
]);
if($createUser){
return "true";
}
else{
return "false";
}
}
It is registering successful but not sending the verification link on email. How can I achieve that?
Update the question:
I am using Laravel 8 version
I am creating an API for my application using JWT. It is for different table not for users table. How can I authenticate login user with another table for exapmle students table and create jwt token.
For the User table user authentication function which is working, & its is as below:
$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' => 204,
]);
}
$user = Auth::user();
if($user->status == "Inactive") {
return response()->json([
'message' => "User ID is disabled",
'status_code' => 403,
]);
}
$user->last_login = Carbon::now();
$user->save();
$user = Auth::user();
$user->UserDeviceData()->firstOrCreate([
'device_id' => $request->device_id,
'device_type' => $request->device_type ? $request->device_type : "ios",
]);
return (new UserTransformer)->transform($user,[
'request_type' => 'login',
'token' => $token
]);
} catch (JWTException $e) {
return response()->json([
'message' => "Internal server error",
'status_code' => 500,
]);
}
And here is the OTP verification function and its code look like :
public function verify(Request $request)
{
try
{
$token = config('app.TWILIO_AUTH_TOKEN');
$twilio_sid = config('app.TWILIO_SID');
$twilio_verify_sid = config('app.TWILIO_VERIFY_SID');
$twilio = new Client($twilio_sid, $token);
$phoneNumber = $request->get('phone_number');
$verification = $twilio->verify->v2->services($twilio_verify_sid)->verificationChecks->create($request->get('verification_code'), array('to' => $request->get('phone_number')));
if ($verification->valid) {
// Updating table student table that the number is verified & want to return JWT token for authenticate user
return response()->json([
"status_code" => 200,
"message" => "Phone number verified."
]);
}
return response()->json([
"status_code" => 200,
"message" => "Verification failed."
]);
}catch (Exception $e){
return response()->json([
'response' => [
'code' => 401,
'message' => "Unable to verify OTP.Please try again.",
],
]);
}
}
How can I authenticate the verified user which is on another table.
I have field status in my users table and O want to check if status is 0 then user should not login and if 1 user should be able to login.
Here is my login code (controller is lengthy, please avoid some irrelevant code):
public function fdLogin(Request $request)
{
$credentials = $request->only('email', 'password');
$rules = [
'email' => 'required|email',
'password' => 'required',
];
$validator = Validator::make($credentials, $rules);
if ($validator->fails()) {
return response()->json([
'status' => false,
'message' => __('messages.validation_errors'),
'errors' => $validator->messages()
]);
}
$token = "";
try {
// if Request has latitude and longitude
$latFrom = $longFrom = $givenSpeciality = "";
$locationTag = false;
if ($request->has('lat') && $request->has('long') && $request->has('specialityKey') && !empty($request->lat) && !empty($request->long) && !empty($request->specialityKey)) {
$latFrom = $request->lat;
$longFrom = $request->long;
$givenSpeciality = $request->specialityKey;
$locationTag = true;
}
if (!Auth::attempt($credentials)) {
return response()->json(array('status' => false, 'message' => 'Invalid username or password', 'errors' => array('Invalid username or password')));
}
$speciality = DB::table('specialities')
->join('user_facility', 'specialities.id', 'user_facility.speciality_id')
->where('user_facility.user_id', Auth::user()->id)
->select('specialities.name', 'specialities.id')->first();
$types = [];
if (!empty($speciality)) {
$types = $speciality;
}
$customClaims = ['exp' => Carbon::now()->addYear()->timestamp, 'specialityType' => $types];
if (!$token = JWTAuth::claims($customClaims)->attempt($credentials)) {
return response()->json([
'status' => false,
'message' => 'We can`t find an account with this credentials.'
], 401);
}
} catch (JWTException $e) {
// Something went wrong with JWT Auth.
return response()->json([
'status' => false,
'message' => 'Failed to login, please try again.'
], 500);
}
$withInFacility['logged_in_facility'] = array();
$currentUser = Auth::user();
$user_id = $currentUser->id;
if ($locationTag) {
$userWithFacilities = $currentUser->load('facilities.facilityLocation', 'facilities.speciality.avaliableSpeciality');
$locations = array();
if (isset($userWithFacilities['facilities']) && count($userWithFacilities['facilities'])) {
foreach ($userWithFacilities['facilities'] as $facility) {
$faci = $facility->toArray();
if (!empty($faci['facility_location']) && $faci['facility_location'] > 0) {
$demo = $faci['facility_location'];
}
if (isset($faci['speciality']) && count($faci['speciality']) > 0) {
$speciality = $faci['speciality'];
if (isset($speciality['avaliable_speciality']) && count($speciality['avaliable_speciality']) > 0) {
$avaliable_speciality = $speciality['avaliable_speciality'];
$demo['avaliable'] = $avaliable_speciality['specialty_key'];
}
}
$locations[] = $demo;
}
if (count($locations)) {
foreach ($locations as $location) {
$distance = self::distance($latFrom, $longFrom, $location['lat'], $location['long']);
// if distance is less than 100 meter ''ll eligible to login else Log him out
if ($distance < config('constants.facility_radius')) {
if ($location['avaliable'] == $givenSpeciality) {
$withInFacility['logged_in_facility'] = $location;
$withInFacility['logged_in_facility']['radius'] = config('constants.facility_radius');
}
}
}
// if distance is less than 100 meter ''ll eligible to login else Log him out
if (empty($withInFacility['logged_in_facility'])) {
JWTAuth::setToken($token)->invalidate();
return response()->json(['status' => false, 'message' => 'Your are not in facility OR Your speciality did not matched with facility', 'errors' => '']);
}
} else {
return response(['status' => false, 'message' => 'Your Facility did not have any location , please ask for administrator', 'data' => null]);
}
} else {
return response(['status' => false, 'message' => 'You did not have any facility , please ask for administrator', 'data' => null]);
}
}
$currentUser->basicInfo = $this->userBasicInfo->where('user_id', $user_id)->first();
$is_super_admin = DB::table('users')->select('users.is_super_admin')->where('id', $user_id)->first();
$specialitiesAndRoles = DB::table('user_facility')
->leftjoin('roles', 'user_facility.role_id', 'roles.id')
->leftjoin('specialities', 'user_facility.speciality_id', '=', 'specialities.id')
->leftjoin('available_specialties', 'specialities.available_specialties_id', '=', 'available_specialties.id')
->where('user_facility.user_id', $user_id)
->select('user_facility.facility_id', 'user_facility.speciality_id', 'user_facility.is_facility_supervisor', 'user_facility.priv_key', 'user_facility.role_id', 'specialities.name', 'available_specialties.id', 'available_specialties.specialty_key')
->get();
$superadmin = $is_super_admin->is_super_admin;
$specialities = (object)$specialitiesAndRoles;
$sp = $specialitiesAndRoles->toArray();
$specialty_key = "";
if (!empty($sp)) {
$specialty_key = $sp[0]->specialty_key;
}
$fac_privs = array();
if (!empty($sp)) {
foreach ($sp as $s) {
$s = (array)$s;
$s['priv_list'] = Helpers::get_checked_privs($s);
$fac_privs[] = $s;
}
}
if (count($withInFacility['logged_in_facility'])) {
$withInFacilityObj = (object)$withInFacility['logged_in_facility'];
} else {
$withInFacilityObj = NULL;
}
$response = ['is_super_admin' => $superadmin, 'facilities' => $fac_privs, 'logged_in_facility' => $withInFacilityObj];
if ($superadmin == 1) {
$response['priv_ist'] = Helpers::get_priv_list();
}
$speciality = $this->speciality;
if ($speciality) {
$user = DB::table('verify_users')->where('user_id', $user_id)->first();
DB::table('verify_users')->insert([
'token' => $token,
'user_id' => $user_id,
]);
if ($specialty_key == 'medical_doctor') {
$md_db = DB::connection('doctorDB');
$user = $md_db->table('auth_token')->where('user_id', $user_id)->first();
if ($user) {
$md_db->table('auth_token')->where('id', $user->id)->update([
'token' => $token,
'isValid' => 1,
]);
} else {
$md_db->table('auth_token')->insert([
'token' => $token,
'isValid' => 1,
'user_id' => $user_id
]);
}
}
}
$user_data = $this->GetUserInfo();
unset($currentUser['facilities']);
return response()->json([
'status' => true,
'message' => 'Login successfully',
'data' => [
'token' => $token,
'userData' => $currentUser,
'userInfo' => $user_data,
'privileges' => $response,
]
]);
}
This is my whole controller of login I am not using Laravel built-in authentication, I have created my own login based on my project requirement, and I want to implement this functionality.
I don't know why you are not checking when you get the user info. I am not sure what is your purpose but may be this code will help you.
$currentUser = Auth::user();
if($currentUser->status == 0){
Auth::logout();
return response()->json([
'status' => false,
'message' => 'Failed to login, Access forbidden.',
], 403);
}