How to check if user password is null or not in the database and passing that information to Vue app? - laravel

The objective here is not to know the actual password of an user, but to know if the user has a password set or not in the database. I can distinguish the users who have passwords set, i.e. password != null, versus users who don't have passwords set, i.e. password == null, inside my Laravel controller, but when I try to pass the user list to my Vue app using an axios.get request, all passwords come up as 'undefined' even though there are users with hashed passwords in the database. The following is a sample of my Vue code:
axios.get('/admin/user')
.then(function (response) {
self.users = response.data;
for(var i=0; i<self.users.length; i++) {
console.log(self.users[i].password) // outputs 'undefined' for all user passwords instead of the hashed database passwords
}
})
.catch(function (error) {
// handle error
console.log(error);
});
and /admin/user from above is defined in my routes directory in web.php as:
Route::get('/admin/user', 'UserController#get');
and for the purpose of this example, my UserController#get function is defined as:
public function get()
{
$user = User::get();
return response($user, 200);
}
Any advice on how to distinguish users who have passwords set and not set would be appreciated.

As #matiaslauriti mentioned in the comment, User model deletes password field during serialization. As such you should avoid sending out passwords from your server even if they're hashed. In your particular usecase there is no need to send passwords out. You can simply check if the password is set in the backend and attach this info to the response object.
public function get()
{
$user = User::get();
if (empty($user->password)) {
$user->isPasswordSet = false;
} else {
$user->isPasswordSet = true;
return response($user, 200);
}

Related

Test Passport's Authorization code grant authentication flow

Any idea on how i can test my authentication routes in authorization code grant:
- GET: '/oauth/authorize/?' . $query
- POST: 'oauth/token'
The problem is that according to the docs you need to provide a redirect_uri field in your query and i don't know how you suppose to have one in tests and then get the response from your laravel app.
i don't want to test this api with my frontend app.(if possible)
i haven't showed any code bc i just need a general idea of the testing process of such APIs that are working with clients and redirect_uris
on google i found tests around password grant authentication which doesn't need a redirect_uri field
this is what i tryed and it failed.
test:
$user = User::orderBy('id', 'asc')->first();
$token = $user->createToken('personal_access');
Passport::actingAs($user, [], 'api');
(new AuthController)->logout();
if (($user = Auth::user()->toArray()) !== null) {
dd(1, $user);
} else {
dd(0);
}
Auth::user() returns the $user
AuthController:
public function logout(): Response
{
$tokenId = $this->getTokenId();
$tokenRepository = app(TokenRepository::class);
$tokenRepository->revokeAccessToken($tokenId);
$refreshTokenRepository = app(RefreshTokenRepository::class);
$refreshTokenRepository->revokeRefreshTokensByAccessTokenId($tokenId);
Artisan::call('passport:purge');
return response('Successfully loged you out.', 200);
}
private function getTokenId(): int
{
return (new CheckAuthentication)->getAuthenticated()->token()->id;
}
$tokenId is always zero.

Call cloud code without logged in user Parse Server JS SDK

Is it possible to call a cloud function that returns objects without having a current user? The iOS and Android SDKs support anonymous users but I'm asking specifically for JavaScript.
I'd like to allow it so that anyone who visits my web app can read objects without having to sign in. I'm using Back4App.
Yes. You can call a cloud code function no matter the user is logged in or not. Inside the cloud function you can check the user property of the request object to check if the user is either logged in or not. In the case that your user is not logged in and you want to query a class which requires user permission, you can use the useMasterKey option.
Parse.Cloud.define('myFunction', async req => {
const { user, isMaster } = req;
if (isMater) {
// the cloud code function was called using master key
} else if (user) {
// the cloud code function was called by an authenticated user
} else {
// the cloud code function was called without passing master key nor session token - not authenticated user
}
const obj = new Parse.Object('MyClass');
await obj.save(null, { useMasterKey: true }); // No matter if the user is authenticated or not, it bypasses all required permissions - you need to know what you are doing since anyone can fire this function
const query = new Parse.Query('MyClass');
return query.find({ useMasterKey: true }) // No matter if the user is authenticated or not, it bypasses all required permissions - you need to know what you are doing since anyone can fire this function
});

How can disable the password filed ? ( laravel )

I've system don't required the password input just one input
when I login , so I created this:
public function do_login()
{
if (auth()->attempt(['user_id' => request('user_id')])) {
return redirect('home');
} else {
session()->flash('erorr', trans('Your Id Incorrect'));
return redirect('/')->withInput();
}
} //ends of do_login
and this is the error appears to me >
image
You can't use Auth's attempt without a password.
Since you're letting anyone in with just the ID, all you need is:
auth()->loginUsingId(request('user_id'))
You may want to look up the ID in your database first, or loginUsingId should throw an exception you can try/catch for.
If user_id doesn't correspond to the id column of your users table, you may need a slightly different approach:
$user = User::where('user_id', request('user_id'))->first();
auth()->login($user);

How to send original users password to his mail (before bcryption)

In my system users can't register. Admin adding all users in the admin panel and telling them your password is "xxx". Right now i need to send mail to users. Which contains users email and users password. System is working great. But there is one exception. In the mail, passwords is bcrypted. How can i solve? I don't any clue. I am using observers. In the model:
public static function boot()
{
parent::boot();
self::created(function () {
$customer = Customer::latest()->get()->first();
Mail::send('emails.user_login_informations', ['customer' => $customer], function($message) use($customer) {
$message->to($customer->email, $customer->name, $customer->password)
->subject('Login Information');
});
});
}
ps: this is working. In my mail:
Your email: xxx#example.com
Your Password: $2y$10$/GW5XNH9KGU.Nz05PZHFJuKb2ldhwYhS8oMX9e7HJIuFNJ
But this looks like:
Your email: xxx#example.com
Your Password: 123
You can create a temporary password field and delete it upon user activation. I needed this for a real world example. For instance:
Event::listen('rainlab.user.activate', function($user) {
$user->temp_password = null;
$user->save();
});
User::saving(function ($user) {
$password = post('User.password');
if ($password && ! $user->attributes['is_activated']) {
$user->temp_password = $password;
}
});
As mentioned above though, this includes a big security risk.
You hash user passwords to increase the security. The Hashing functionality is a one way hashing, so it can't be reversed.
A better way would be to create a password reset token und send it to the user. So the user can set a new password with the email address / token combination. To increase this method you could let the token expire after 30 minutes or so.

Laravel - How to check value with another encrypted in DB

I am developing a sales system where every user has an account. To authenticate users I store passwords with bcrypt and use the Laravel Auth library as follows:
$data = $request->only('user', 'password');
if (\Auth::attempt($data)){
#redirect dashboard
}
In the Point Of Sale screen, user can add special products that require a PIN (The PIN is the password of some users with privileges).
When i call a button click to save the sale, in my Request class i add this validation (i only need to check if there are some special products, and if, check the PIN that have to match in the DB), i use this code:
$allowed_pin = true;
foreach (Request::get('products') as $product) {
if($product["special_perm"] === "1"){
$pin = $product["pin"];
$user = User::where('password', '=', bcrypt($pin))->first();
if ($user) {
$allowed_pin = true;
} else {
$allowed_pin = false;
}
}
}
The problem is when i compare password in Request class, if i use dd() it show me "$2y$10$AasS5/FTWv28PmYuABfqve4Ao6m1U9zxdUE6ZoHJWcfpn19sd4wcG" and real password hashed in database is "$2y$10$DmefHppecIjuanjRbcj82OPyjhi.L0/4YGd62LYCvkDTGjXxL25fG"
and they not matching.
Does Auth class use some internal encryption different to bcrypt?
To compare the plain text password with the encrypted one, use Hash::check('plain-text', $hashedPassword)
Check out the Laravel docs: https://laravel.com/docs/5.4/hashing

Resources