I'm currently developing a mobile apps for my web based system. I'm using laravel as my API .
Currently, I want to do where when User A login, it will only shown User A info.
How can I achieve that ?
This is my AuthController where it generate my tokens.
public function login(Request $request)
{
try {
$validateUser = Validator::make($request->all(),
[
'username' => 'required',
'password' => 'required'
]);
if($validateUser->fails()){
return response()->json([
'status' => false,
'message' => 'validation error',
'errors' => $validateUser->errors()
], 401);
}
$user = UserRegister::where('username', $request->username)->first();
if(!$user || !Hash::check($request['password'], $user->password)) {
return response([
'message' => 'Username & Password does not match'
], 401);
}
return response()->json([
'status' => true,
'message' => 'User Logged In Successfully',
'user' => $user,
'token' => $user->createToken("remember_token")->plainTextToken
], 200);
} catch (\Throwable $th) {
return response()->json([
'status' => false,
'message' => $th->getMessage()
], 500);
}
}
This is my api routes
Route::post('/login', [AuthController::class, 'login']);
// Homepage routes
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::post('/logout', [AuthController::class, 'logout']);
Route::get('/technician', [HomepageController::class, 'technician']);
});
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
and this is my HomepageController where I tried to retrieve user A data only but it does not work.
public function technician()
{
$technician=JobRegister::where('job_assign', auth()->user()->name);
return response()->json($technician);
}
This is my query for web based system.
$query = "SELECT * FROM job_register WHERE job_assign ='{$_SESSION['username']}'"
i want to make user A can only look at their job details that been assign.
do you have any idea how to do it ? your help is much appreciated. thank you.
try this
$username=Auth()->user()->userName //this will return you username of logged in user
$query = "SELECT * FROM job_register WHERE job_assign ='$username'"
don't forget to use auth namespace top of in your controller like this
use Auth;
Related
i have a log in form in my front end (vue) when users log in, in vue i can get back data of logged in user perfectly fine through
axios.get('http://127.0.0.1:8000/api/user').then((response)=>{
this.userData = response.data;
However in my backend when i try to bring back the logged in user though
if ($request->user('sanctum')) {
return "auth";
} else {
return "guest";
}
it returns guest i dont know why!!!!
vue code:
async login(){
axios.post('http://127.0.0.1:8000/api/login', this.form).then((response) =>{
localStorage.setItem('token', response.data);
axios.defaults.headers.common['Authorization'] = `Bearer ${response.data.token}`;
this.$router.push('/');
} )
.catch ((error) =>{
console.log(error.response.data.errors);
})
},
laravel auth controller :
public function loginn(Request $request){
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
return $user->createToken("token")->plainTextToken;
return response()->json([
'token' => $token,
'type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
api.php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/signup', [authcontroller::class, 'signupp']);
Route::post('/login', [authcontroller::class, 'loginn'])->name('login');;
Route::post('/logout',[authcontroller::class, 'logout'])->middleware('auth:sanctum');
I haved this problem.
This problem is for .env in backend laravel and get csrf front
remembering that the localhost address must be either localhost or 127.0.0.1 amd get csrf before
axios.get('/sanctum/csrf-cookie').then(response => {
// Login...
});
.env
SESSION_DOMAIN=127.0.0.1
SACTUM_STATEFUL_DOMAINS=127.0.01:PORT
When the user created a new account I added it's API token and returned it to the user. But I'm having trouble wanting to return the API token to the user when they view their account information.
GET /account: Returns API Token in response.
This is my code file User.php:
public function index()
{
$users = User::where('id', auth()->user()->id)->get();
return response([
'data' => UserResource::collection($users),
'message' => 'Retrieve successfully'
], 200);
}
// POST
public function store(Request $request)
{
$data = $request->all();
$validator = Validator::make($data, [
'name' => 'required|max:255|string',
'email' => 'required|email|unique:users,email',
'password' => 'required|string',
]);
if ($validator->fails()) {
return response(['error' => $validator->errors(), 'Validation Error'], 400);
}
$users = User::create($data);
$token = $users->createToken('accessToken')->plainTextToken;
return response([
'data' => new UserResource($users),
'api_token' => $token,
'message' => 'Created successfully'
], 201);
}
This is my code file api.php (route):
Route::group(['prefix' => 'v1' ], function () {
// Account
Route::post('/account', [UserController::class, 'store']);
// Protected route
Route::group(['middleware' => ['auth:sanctum']], function () {
// Account
Route::get('/account', [UserController::class, 'index']);
});
});
Use $request->bearerToken() to get bearer token.
public function index()
{
$users = User::where('id', auth()->user()->id)->get();
return response([
'data' => UserResource::collection($users),
'api_token' => $request->bearerToken(),
'message' => 'Retrieve successfully'
], 200);
}
I made a UserController which generats an accessToken when a user registered succesfully on a page.
class UserController extends Controller
{
/**
* Login Method: in here we call Auth::attempt with the credentials the user supplied.
* If authentication is successful, we create access tokens and return them to the user.
* This access token is what the user would always send along with all API calls to have access to the APIs.
* Register Method: like the login method, we validated the user information,
* created an account for the user and generated an access token for the user.
*/
public function login()
{
$credentials = [
'email' => request('email'),
'password' => request('password')
];
if (Auth::attempt($credentials)) {
$success['token'] = Auth::user()->createToken('MyApp')->accessToken;
return response()->json(['success' => $success]);
}
$status = 401;
$response = ['error' => 'Unauthorized'];
return response()->json($response, $status);
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
return response()->json(['success' => $success]);
}
public function getDetails()
{
return response()->json(['success' => Auth::user()]);
}
}
My problem is that I want to remove the token when the user logs out but I dont know how to remove the access token from the user.
logout function in my UserController
public function logout()
{
Auth::user()->tokens->each(function($token, $key) {
$token->delete();
});
return response()->json([
'message' => 'Logged out successfully!',
'status_code' => 200
], 200);
}
When I test it with postman with the GET route: http://127.0.0.1:8000/api/logout. Am I missing something?
UPDATE
Here s my api.php file:
Route::resource('categories', 'App\Http\Controllers\CategoryController');
Route::post('register', 'App\Http\Controllers\UserController#register');
Route::post('login', 'App\Http\Controllers\UserController#login');
/**
* We can group the routes we need auth for
* under common middleware. It secures our routes
*/
Route::group(['middleware' => 'auth:api'], function(){
Route::get('logout', 'App\Http\Controllers\UserController#logout');
});
I am testing it in postman using the route: http://127.0.0.1:8000/api/logout and passing the Bearer token, which I get from the login request, as a value.
It should be POST Request instead of GET request, because your deleting/making change to the database.
The route should look like this:
Route::POST('logout', 'App\Http\Controllers\UserController#logout')->middleware('auth:api');
And the logout method in in UserController should be.
public function logout()
{
auth()->user()->tokens->each(function ($token, $key) {
$token->delete();
});
return response()->json([
'message' => 'Logged out successfully!',
'status_code' => 200
], 200);
}
In your logout function, it should expire the token, not delete it
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([], Response::HTTP_NO_CONTENT);
}
OR if you wanna expire all his tokens:
use Illuminate\Support\Facades\Auth;
public function logout(Request $request)
{
$userTokens = Auth::user()->tokens();
foreach($userTokens as $token)
{
$token->revoke();
}
}
As the title says CreateFreshApiToken doesnt create any cookies. So I cant use it to auth a logged in user for other requests related to the user.
I tried to set a cookie on the response and it works perfectly fine. So this has to do something with CreateFreshApiToken not working.
AuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
class AuthController extends Controller
{
public function signup(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string'
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$user->save();
return response()->json([
'message' => 'Successfully created user!'
], 201);
}
public function signin(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
$token->save();
return response()->json([
'message' => 'Successfully signed in!'
]);
}
public function signout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully signed out!'
]);
}
public function user(Request $request)
{
return response()->json($request->user());
}
public function test()
{
return response()->json([
'message' => 'test'
]);
}
public function test2(Request $request)
{
return response()->json([
'laravel_token' => $request->cookie('laravel_token')
]);
}
}
Kernel.php
protected $middlewareGroups = [
'web' => [
//...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
'api' => [
'throttle:60,1',
'bindings',
\Barryvdh\Cors\HandleCors::class,
],
];
api.php
Route::group([
'prefix' => 'auth'
], function () {
Route::post('signin', 'AuthController#signin');
Route::post('signup', 'AuthController#signup');
Route::get('test', 'AuthController#test');
Route::get('test2', 'AuthController#test2');
Route::group([
'middleware' => ['auth:api']
], function() {
Route::get('signout', 'AuthController#signout');
Route::get('user', 'AuthController#user');
});
});
And this is my angular code:
test() {
return this.http.get('http://homestead.test/api/auth/test', {withCredentials: true})
.subscribe(response => {
console.log(response);
});
}
test2() {
return this.http.get('http://homestead.test/api/auth/test2', {withCredentials: true})
.subscribe(response => {
console.log(response);
});
}
I've also setup cors with https://github.com/barryvdh/laravel-cors successfully with 'supportsCredentials' enabled. I am also sending a useless GET request to see if any laravel_token is set in the cookie but no success.
CreateFreshApiToken is part of the web middleware group, so in order for it to set cookies you need your login page to be a web route (instead of an api route).
I resolved this part of the problem by replicating CreateFreshApiToken::handler in my login controller:
$response = response()->json([], 200);
// ADDÂ THISÂ LINE:
$response->cookie(\Laravel\Passport\Passport::cookie(),$request->session()->token();
return $response;
I have managed to create jwtauth to connect my mobile app to octobercms backend
from this reference
but the last_login field is always empty, I believe this is not set by default.
this is authenticated function that I have
use Tymon\JWTAuth\JWTAuth;
public function __construct(JWTAuth $auth)
{
$this->auth = $auth;
}
public function authenticate(Request $request)
{
try {
if (! $token = $this->auth->attempt($request->only('email', 'password'))) {
return response()->json([
'errors' => [
'root' => 'Could not sign you in with those details.',
],
], 401);
}
} catch (JWTException $e) {
return response()->json([
'errors' => [
'root' => 'Failed.',
],
], $e->getStatusCode());
}
return response()->json([
'data' => $request->user(),
'meta' => [
'token' => $token,
],
]);
}
it's called by this route.php from jwtauth folder
Route::group(['prefix' => 'api'], function () {
Route::post('auth/login','Autumn\JWTAuth\Http\Controllers\AuthController#authenticate');
Route::post('auth/register', 'Autumn\JWTAuth\Http\Controllers\AuthController#register');
Route::post('auth/logout', 'Autumn\JWTAuth\Http\Controllers\AuthController#logout');
Route::group(['middleware' => 'jwt.auth'], function () {
Route::get('auth/me', 'Autumn\JWTAuth\Http\Controllers\AuthController#user');
});
how do we set user last_login timestamp?
I hope my question is clear to understand.
added plugin.php where i extended user plugin as requested by #HardikSatasiya since i got exception implementing his suggestion
use System\Classes\PluginBase;
use Rainlab\User\Controllers\Users as UsersController;
use Rainlab\User\Models\User as UserModels;
use Event;
class Plugin extends PluginBase
{
public function registerComponents()
{
}
public function registerSettings()
{
}
public function boot()
{
UserModels::extend(function($model){
$model->bindEvent('model.beforeSave',function() use ($model) {
$users = \BackendAuth::getUser();
$model->backend_users_id = $users->id;
//above line result exception when calling method as #HardikSatasiya suggested
if(!empty($model->avatar)){
$model->image_path = $model->avatar->getPath();
}
if(!empty($model->groups)){
$model->membership = $model->groups[0]['name'];
}
});
$model->addJsonable('users_detail','membership');
});
UsersController::extendFormFields(function($form,$model,$context){
$form->addTabFields([
'users_detail[0][gender]' => [
'label' => 'Jenis Kelamin',
'span' => 'left',
'tab' => 'User Profile',
'type' => 'radio',
'options' => [
'Pria' => 'Pria',
'Wanita' => 'Wanita'
]
],
'users_detail[0][ttl]' => [
'label' => 'Tempat/Tanggal Lahir',
'type' => 'text',
'span' => 'left',
'tab' => 'User Profile'
],
]);
});
}
i add additional fields to user table by this separate plugin..
Ok, may be because internal hooks are not called when this plugin externally logsin user.
May be we need to call it manually, this code snippet can do it, just put given code after successful login.
// this will fire hooks and update `last_login`
// get authenticated user from the jwt authmanager
$user = $this->auth->authenticate($token);
$user->afterLogin();
Added in your code below.
public function authenticate(Request $request)
{
try {
if (! $token = $this->auth->attempt($request->only('email', 'password'))) {
return response()->json([
'errors' => [
'root' => 'Could not sign you in with those details.',
],
], 401);
}
} catch (JWTException $e) {
return response()->json([
'errors' => [
'root' => 'Failed.',
],
], $e->getStatusCode());
}
// this will fire hooks and update `last_login`
// get authenticated user from the jwt authmanager
$user = $this->auth->authenticate($token);
$user->afterLogin();
// ^ this code
return response()->json([
'data' => $request->user(),
'meta' => [
'token' => $token,
],
]);
}
this snippet will update last_login as expected. i did not test it but it will work as it should.
if any doubt or problem please comment.