Get user id by passing token in Laravel [closed] - laravel

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
How can i get user id by passing token in Laravel?
I wanna to get the user token from request then send user avatar to him.

Try This
$userid = Auth::guard('api')->user()->id;
echo $userid;

You can add this in your controller
$user = Auth::user();
if ($user)
{
return $user->avatar;
}
You can use Auth to get the authenticated user.

You can use Crypt Facade for encrypting and decrypting user id and pass it for your case.
I recommend checking API token authentication, if you don't want to use it then in very simple and native way you can do something like this:
Create a token with user id encrypted in it.
Pass the token to input form, keep it as hidden form value.
On receiving the request with token, decrypt the token, extract id and fetch result and send.
Some Security recommendation:
[Depends on use case] while encrypting and decrypting, along with
user_id also append date time value like timestamp. So that you can perform token expiration verification.
// Controller
public function index() {
return view('/top/index.php', [$token => $this->getToken()]);
}
private function getToken() {
$id = '100001'; //get from db or wherever u need
// this just example
return Crypt::encrypt( $id. ':' . time();
}
then in the Form/blade
<form>
....
<input hidden value = "{{ $token }}" name='token'>
....
<input type submit>
</form>
On receiving post request
// controller
public function postIndex(Request $request) {
$userId = $this->extractIdFromToken($request->input('token'));
...
...
}
private function extractIdFromToken($token) {
if ($token === null) {
throw new \Exception('Missing token');
}
$tokenValue = explode(':', Crypt::decrypt($token));
// do verification of time needed else go to next
return $tokenValue[0] ?? null;
}

Related

How to make login as other user in API using laravel passport?

I am using laravel passport for API authentication. and I want to log in as different users with different roles from superadmin. So how can I achieve this? Please give your suggestions.
public function masqueradeNotary($profileId)
{
$userId = decodeC($profileId);
$notaryUser = $this->adminService->getUser($userId);
if($userId){
//logout from current login user
$user = auth()->user()->token();
$user->revoke();
//login as notary user
$userRoles = $notaryUser->roles()->get();
// $scopes = [];
// if ($userRoles) {
// $scopes = Arr::pluck($userRoles,'code');
// }
if(Auth::login($notaryUser)){
\Log::info("auth user");
\Log::info(auth()->user());
// $token = $user->createToken($user->email . '-' . now(), $scopes);
}
}
}
Welcome to stackoverflow.
Well, you should look at spatie's package, it might make your life easier.
You can apply roles on the registration if you create two different registration functions. In the front-end, you have to somehow make the user decide and pass that value (a checkbox would be ideal).
I got the solution. there is no need to check auth login just log out the current user and revoke the access token and create a token for the user directly.
$token = $user->createToken($user->email . '-' . now(), $scopes);

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.

Pin Verification In Laravel

I'm a beginner. I have a pin field in my user database. I want users to verify the pin before they can access there profile. how can I do this any logic?
in livewire components
public function verify (){
$user = User::select('id')->where('pin',$pin)->first();
Auth::loginUsingId($user->id);
return redirect()->intended('/user');
}
in my livewire blade I will call the verify method in the form will this work
laravel login using pincode :check the following code example may be you get the hint how to implement that, in this example code pin authentication is done using JWT and then user is allowed to access to those specific routes.
$user = User::find($uid);
try {
if (!$token = JWTAuth::fromUser($user)) {
return $this->onUnauthorized();
}
} catch (JWTException $e) {
return $this->onJwtGenerationError();
}
For somereason if you dont want to use the above JWT method you can use this one. i'm sharing the code for an example from by program which may help you
$user = User::select('id')->where('pin',$pin)->first();
Auth::loginUsingId($user->id);
return redirect()->intended('/user');

How can I add ask username and password feature to only one of my laravel routes?

I have created a few forms in laravel. I want to restrict access to one of them only to a specific user.
I want to create a user and password myself.
This is my routes excerpt. This is the route I want to protect from access
Route::get('/tabledata_id_title', 'KedivimController#appearanceiddata');
This is my controller excerpt:
public function appearanceiddata()
{
//$magic = DB::table('prog_title')->select('pr_id', 'pr_title')->get();
$magic = DB::table('prog_title')->select('pr_id', 'pr_title')-> where('pr_index', '=', 1)->get();
return view ('takealook', ['magical' => $magic]);
}
This is a short fix for your problem.
public function appearanceiddata()
{
if (!Auth::guard('web')->check()) //check if someone is logged in
{
//redirect to login page.
}
else {
/*Check if the logged in user is your desired user.
Maybe try matching the logged in id with your desired id.
If you find that a user is logged in but they are not your desired user
then you may redirect them in some other place or show them a message. */
}
//$magic = DB::table('prog_title')->select('pr_id', 'pr_title')->get();
$magic = DB::table('prog_title')->select('pr_id', 'pr_title')-> where('pr_index', '=', 1)->get();
return view ('takealook', ['magical' => $magic]);
}
However, this practice is ok if you have one or two restricted field. But if you have more than that then you should read about middleware.

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