I am confused how to retrieve authentication details like username and password as my guzzle api is receiving only success message and code at the time of login. I am not able to make session. Please explain how I can get authentication details in dashboard view like Auth:user();
This is my controller:
<?php
public function getGuzzleRequest(Request $request)
{
$inputData = [];
$inputData = $request->all();
$client = new Client([
'allow_redirects'=>true,
]);
$URI = 'http://ahlocal.test/api/login';
$body['username']=$inputData['username'];
$body['password']=$inputData['password'];
$response = $client->request('POST', $URI,[
'form_params' => $body,
]);
$response =$response->getBody()->getContents();
if(statuscode=='200')
{
return redirect('dashboard');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}
?>
Not sure I understood you correctly, but try this option:
$client = new Client([ 'allow_redirects'=>true, ]);
$URI = 'http://ahlocal.test/api/login';
$response = $client->request('POST', $URI, [ 'auth' => [$inputData['username'], $inputData['password']]]);
$body = $response->getBody()->getContents();
if($response->getStatusCode() == 200) {
return redirect('dashboard');
} else {
return back()->with('error', 'Wrong Login Details');
}
Related
I have a Laravel 8 project. I want to change magic auth error message. And I did updated my code like this.
'This code has already been used' I replaced this message with this in the context of the code 'You will get a link in your email inbox every time you need to log in or register. Keep in mind that each link can only be used once.'
OLD AuthController.php
public function magicauth(Request $request)
{
$auth = app('firebase.auth');
$email = $request->email;
$oobCode = $request->oobCode;
$exits = User::where('email', $email)->first();
if(!is_null($exits))
{
if(is_null($exits->firebaseUserId))
{
$fUser = $auth->createUser([
'email' => $exits->email,
'emailVerified' => true,
'displayName' => $exits->name,
'password' => ($exits->email . $exits->id),
]);
$firebaseID = $fUser->uid;
$exits->update([
'firebaseUserId' => $firebaseID
]);
}
}
try
{
$result = $auth->signInWithEmailAndOobCode($email, $oobCode);
$firebaseID = $result->firebaseUserId();
$user = User::where('firebaseUserId', $firebaseID)->first();
if(is_null($user))
{
return view('auth.messages', ['message' => 'User not found']);
}
if($user->role_id != 3)
{
return view('auth.messages', ['message' => 'User is not creator']);
}
Auth::login($user);
return redirect()->route('home');
} catch (\Exception $e) {
return view('auth.messages', ['message' => 'This code has already been used.']);
}
return redirect()->route('login');
}
NEW AuthController.php
public function magicauth(Request $request)
{
$auth = app('firebase.auth');
$email = $request->email;
$oobCode = $request->oobCode;
$exits = User::where('email', $email)->first();
if(!is_null($exits))
{
if(is_null($exits->firebaseUserId))
{
$fUser = $auth->createUser([
'email' => $exits->email,
'emailVerified' => true,
'displayName' => $exits->name,
'password' => ($exits->email . $exits->id),
]);
$firebaseID = $fUser->uid;
$exits->update([
'firebaseUserId' => $firebaseID
]);
}
}
try
{
$result = $auth->signInWithEmailAndOobCode($email, $oobCode);
$firebaseID = $result->firebaseUserId();
$user = User::where('firebaseUserId', $firebaseID)->first();
if(is_null($user))
{
return view('auth.messages', ['message' => 'User not found']);
}
if($user->role_id != 3)
{
return view('auth.messages', ['message' => 'User is not creator']);
}
Auth::login($user);
return redirect()->route('home');
} catch (\Exception $e) {
return view('auth.messages', ['message' => 'You will get a link in your email inbox every time you need to log in or register. Keep in mind that each link can only be used once.']);
}
return redirect()->route('login');
}
But when I try now, I see that the message has not changed. How can I fix this?
Please follow below steps:
If you haven't done it yet, delete or rename the old AuthController class, use only new one, with new message.
Make sure routes going to the methods in the new controller
Run composer dump-autoload.
If the problem still persist I'd check whether some kind of cache mechanism is enabled in php, like opcache.
when I make request for forget user password api
POST /api/forget-password
Route::post('forget-password', [UserApiController::class, 'forgetPassword']);
Sample Request
{
"email": "example#gmail.com"
}
Expected response
{ "message": "success"}
Actual response what i getting now is
{"email": "example#gmail.com"}{"message": "success"}
Controller
public function forgetPassword(Request $request)
{
$user = User::firstWhere('email', $request->email);
if ($user) {
$auto_pwd = Str::random(8);
$hashed_random_password = Hash::make($auto_pwd);
$user->update([
'password' => $hashed_random_password,
]);
$this->sendUserCreationEmail($user, $auto_pwd);
return $this->respondCreateMessageOnly('success');
} else {
return $this->respondErrorToken('Enter Correct Email');
}
}
public function respondCreateMessageOnly($message)
{
return response()->json([
// 'code' => Response::HTTP_OK,
'message' => $message,
], 200);
}
here is the controller of that route
Laravel version - Laravel Framework 8.8.0
I created a new project in Laravel that consumes all data from an API. For private data like a user profile, I need an access token to get the data.
Once I have an access token, how do I set the token as Auth::id() in Laravel? Or perhaps I can store the user profile as Auth::user() so that I can use #auth in a frontend blade file?
class CustomAuthController extends Controller
{
public function index()
{
return view('login');
}
public function store(Request $request)
{
$request->validate([
'phone' => 'required|numeric'
]);
$data = [
'phone' => $request->phone
];
$codeSent = GeneralFunction::WebRequestPublicApi('first-login', $data, null, null, null, true);
if($codeSent->status == "success")
{
return redirect('verify');
} else {
$errors = new MessageBag();
$errors->add("phone", "Invalid phone number");
return view('login')->withErrors($errors);
}
}
public function showVerify()
{
return view('verify');
}
public function verify(Request $request)
{
try {
$request->validate([
'verify' => 'required|size:6'
]);
$data = [
'token_code' => $request->verify,
'source' => 'web'
];
$token = GeneralFunction::WebRequestPublicApi('verify-login', $data, null, null, null, true);
if($token->status === "success")
{
$userData = GeneralFunction::WebRequestPublicApi('membership', null, 'GET', null, null, true, $token->results->access_token);
if($userData->status !== "error")
{
$user = (array) $userData->results[0];
$request->session()->put('token', $token->results->access_token);
Auth::attempt($user, false, false);
return redirect('/');
}
} else {
$errors = new MessageBag();
$errors->add("verify", "Invalid Token");
return view('verify')->withErrors($errors);
}
} catch (Exception $e) {
$errors = new MessageBag();
$errors->add("verify", $e->getMessage());
return view('verify')->withErrors($errors);
}
}
}
I tried using Auth::attempt, Auth::login(), and the other method, but all of these required a user table. My project does not have a database.
You can do something like following.
In the controller
if($auth_ok)
{
session(['user' => ['key' => 'value', 'key2' => 'value2'] ]); // set session data
return view('frontend');
}
In the view
$user = session('user', false);
#if(!$user) // if not logged in
do something
#else // logged in successfully
Welcome my user
#endif
Hope this helps.
i guess the best thing you need to do is to use sqlite and once you got login from your api create a new user from it or find if there is existing already and Auth::login($newUser);
I created a custom login and custom middleware and
When I try to die dump anywhere it logouts the user what seems to be the problem?
Login Controller:
public function login(Request $request){
// flash::success('Succesfully login')->important();
$client = new Client();
try {
$res = $client->request('POST', 'http://api.fstbx.com/api/user/login', [
'headers' => [
'Accept' => 'application/json',
'Client-Key' => 'p947KVCgE7PyXLdZpfqOSIg4OwIla2BWdSPzdoqf'
],
'form_params' => [
'username' => $request->get('username'),
'password' => $request->get('password')
]
]);
} catch (\Exception $e) {
Flash::error('Invalid login credentials.');
return redirect('/login');
}
$info = json_decode((string) $res->getBody(), true);
$request->session()->put('authUser',$info['user']);
$request->session()->put('authToken',$info['access_token']);
$request->session()->put('authRole',['1','2']);
$role = [];
$role = ['1','2'];
$user = User::createAuth($info['user'],$info['access_token'],$role);
return redirect('/');
}
Custom Middleware
public function handle($request, Closure $next)
{
if(!empty(session('authUser'))){
// $user = $request->session()->get('authUser');
$user = session('authUser');
// $token = $request->session()->get('authToken');
$token = session('authToken');
// $role = $request->session()->get('authRole');
$role = session('authRole');
User::createAuth($user,$token,$role);
return $next($request);
}
return redirect('/login');
}
User Model
public static function createAuth($userData, $userToken,$userRole)
{
$user = new User();
$user->name = $userData['name'];
$user->email = $userData['email'];
$user->avatar = array_rand(User::get_avatar());
$user->token = $userToken;
$user->roles = $userRole;
Auth::login($user);
return $user;
}
adding this code on my custom middleware solved my problem
$request->session()->regenerate();
I am using jwt-auth for my Laravel 5.7 app. Currently, I'm allowing the client to enter email and password as user credentials.
However, I also want to let the client to enter their username in place of their email. So they have 2 choices: email or username.
How can I do that in my code?
My UserController#authenticate
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
try {
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json([
'status' => 401,
'message' => 'invalid_credentials',
], 401);
}
} catch(JWTException $e) {
return response()->json([
'status' => 500,
'message' => 'token_creation_failed',
], 500);
}
return response()->json(compact('token'));
}
Thanks in advance
In your AuthController, add this to the login method;
public function login()
{
$loginField = request()->input('login');
$credentials = null;
if ($loginField !== null) {
$loginType = filter_var($loginField, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
request()->merge([ $loginType => $loginField ]);
$credentials = request([ $loginType, 'password' ]);
} else {
return $this->response->errorBadRequest('What do you think you\'re doing?');
}
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
This is how I handled mine where user can choose either email or phone to login.
public function login(Request $request)
{
//validate incoming request
$this->validate($request, [
'email_phone' => 'required|string',
'password' => 'required|string',
]);
try {
$login_type = filter_var( $request->email_phone, FILTER_VALIDATE_EMAIL ) ? 'email' : 'phone';
// return $login_type;
$credentials = [$login_type => $request->email_phone, 'password'=>$request->password];
if (! $token = Auth::attempt($credentials)) {
return response()->json($this->customResponse("failed", "Unauthorized"), 401);
}
return $this->respondWithToken($token);
} catch(JWTException $e) {
return response()->json($this->customResponse("failed", "An error occured, please contact support.", $user), 500);
}
}