Add a third parameter to a login request using JWT - laravel

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

Related

delete_cookie('name') not working codeigniter 4

I am trying to delete the cookie i create when user logs in but somehow delete_cookie() function is not deleting the cookie i made. I checked the documentation and everything but i cannot get it to work
Here is my code
public function __construct()
{
helper('cookie');
}
public function login() {
$data = [];
$session = session();
$model = new AdminModel();
$username = $this->request->getPost('username');
$password = $this->request->getPost('password');
$remember = $this->request->getPost('agree');
$rules = [
'username' => 'required',
'password' => 'required',
];
if(!$this->validate($rules)) {
$data['validation'] = $this->validator;
} else {
$admin = $model->where('username', $username)->where('password', $password)->first();
if($admin) {
$session->set('uid', $admin['id']);
if($remember) {
set_cookie([
'name' => 'id',
'value' => $admin['id'],
'expire' => '3600',
'httponly' => false
]);
}
} else {
$session->setFlashdata('msg', 'Incorrect Username or Password');
return redirect()->to('admin/login');
}
}
return view('admin/login', $data);
}
public function logout() {
$session = session();
$session->destroy();
delete_cookie('id');
return redirect()->to('admin/login')->withCookies();
}
Edit:
I fixed it. I had to redirect with withCookies();
use this Library
use Config\Services;
Services::response()->deleteCookie('id');
refer this link
https://codeigniter.com/user_guide/libraries/cookies.html

Laravel couldn't verify created user for login

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.

Laravel, JWT authentication is successful but check return false

I use this class for multiple projects and I never had any problems,
Today impossible to check user after JWT authentication
public function check()
{
return response()->json( Auth::guard()->check());
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if ($token = Auth::guard()->attempt($credentials)) {
return $this->respondWithToken($token);
}
return response()->json(['message' => __('commons.response.error.login')], 401);
}
protected function respondWithToken(string $token)
{
return response()->json([
'check' => Auth::guard()->check(),
'access_token' => $token,
'token_type' => 'bearer',
'auth' => true,
'me' => Auth::guard()->user(),
'message' => __('commons.response.success.login', ['user' => Auth::guard()->user()->name]),
]);
}
The login function returns the user and check return true
After that, check() return false
any idea ?
Thank you
Edit
I find it, it was a front end issue, the request token cannot be found
axios.defaults.headers.common['Authorization'] = `Bearer ` + localStorage.token;
I miss the line
localStorage.setItem('token', r.data.access_token);
Done

Laravel passport create token doesnt work on plesk server

I use passport in my laravel project to authenticate users by api. API work correctly on my local host. But after i deploy it on Plesk server token doesnt create. Always show Server Error.
public function login(Request $request) {
$validator = Validator::make($request->all(),[
'email' => 'required',
'password' => 'required',
]);
if($validator->fails()) {
return response()->json(["validation errors" => $validator->errors()]);
}
$email = $request->email;
$password = $request->password;
error_log($password);
$user = DB::table("users")->where([["email", "=", $email]])->first();
if(is_null($user)) {
return response()->json(["success" => false, "message" => "User doesn't exist"]);
}
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$token = $user->createToken('token')->accessToken;
$success['success'] = true;
$success['user'] = $user;
$success['message'] = "Success! you are logged in successfully";
$success['token'] = $token;
return response()->json(['success' => $success ], 200);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
$token = $user->createToken('token')->accessToken;
This line throw error
Problem was in my AuthServiceProvider
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
'Medicare\Model' => 'Medicare\Policies\ModelPolicy',
];
public function boot()
{
$this->registerPolicies();
Passport::routes();
//
}
}
After i commented 'Medicare\Model' => 'Medicare\Policies\ModelPolicy' everything works fine.

how to create a token in laravel tymons/jwt-auth

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

Resources