I want to pass some parameters to an after middleware after the controller has finished running, this is in order to invalidate any password reset tokens if a new one is generated.
My code is:
Controller
public function resetPasswordRequest(Request $request)
{
$user = User::where('email', $request->email)->first();
if (!$user) {
throw ValidationException::withMessages([
'message' => 'invalid_email',
]);
}
$reset_request = Password_reset::create([
'user_email' => $request['email'],
'reset_token' => Helper::makeRandomString(8, true),
]);
$reset_token = $reset_request['reset_token'];
$user_email = $request['email'];
/*
Helper::sendEmail('pass_reset', $user_email = $request['email'], $reset_token);
*/
return response(array('message' => 'success', 'email' => $user_email, 'reset_token' => $reset_token, 'type' => 'reset'), status:200);
}
//Middleware
public function handle(Request $request, Closure $next)
{
$user_data = $next($request);
error_log($user_data);
$user_email = $user_data['email'];
$type = $user_data['reset'];
$tokens = null;
if ($type == 'reset') {
$tokens = Password_reset::where('user_email', '=', $user_email)->where('used', false)->get();
} else if ($type == 'confirmation') {
$tokens = EmailConfirm::where('user_email', '=', $user_email)->where('used', false)->get();
error_log('fffff');
}
error_log('gggg');
//Might not be optimum, need consultation
foreach ($tokens as $column) {
$column['used'] = true;
$column->save();
}
return $next($request);
}
The problem comes with the fact that I do not seem to be able to find a way to pass this data, if I try to access it via the content method the result will be an array of chars.
Any tips on this or another solution I can use?
You don't need middleware because resetting a password is almost never a protected resource.
How can you log in and go to a guarded resource if you forgot your password?
Middleware is to guard routes and its corresponding controllers.
In this case, there is a user, that is not logged in and wants to reset the password of its account.
Just process the request in the controller.
Related
I'm trying to make login with google using laravel socialite and I have a problem.
Route that initiates login:
Route::get('/auth/login/google', 'AuthController#google');
Method in controller that initiates login:
public function google()
{
return Socialite::driver('google')->redirect();
}
Callback route:
Route::get('/auth/login/google/redirect', 'AuthController#googleRedirect');
Callback method in controller:
public function googleRedirect()
{
$googleUser = Socialite::driver('google')->user();
$email = $googleUser->getEmail();
$user = new User();
$user = $user->firstOrCreate(['email' => $email], ['email' => $email, 'password' =>
bcrypt(str_shuffle('abcdefgh45678')), 'email_verified' => 1]);
Auth::login($user, true);
}
And I'm getting ERR_EMPTY_RESPONSE every time I'm trying to redirect user after login.
Funny thing is that I can dump data with dd(Auth::user()->id) and I'm getting user's ID, but when I try to redirect user to the home page using return redirect('/') I'm getting empty response error and if I manually go to home page my user is not authenticated.
#Matej Petric blow code is working for me.
public function handleProviderCallback($provider) {
$user = Socialite::driver('google')->stateless()->user();
$authUser = $this->findOrCreateUser($user);
if ($authUser) {
Auth::login($authUser, true);
return redirect('/');
} else {
return redirect('/login')->withErrors(['msg', 'The Message']);
}
}
public function findOrCreateUser($user) {
$authUser = User::where('email', $user->email)->first();
if ($authUser) {
return $authUser;
}
$userN = User::create([
'name' => $user->name,
'email' => $user->email,
'password' => bcrypt(generateRandom()),
]);
return $userN;
}
I'm new to Lumen. How can I implement login?
I've tried this code but I got an error. And I found out in the documentation that Lumen does not support session. So Auth::attempt() is not available.
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'password' => 'required|string'
]);
$credentials = $request->only('email', 'password');
if( !Auth::attempt($credentials) ) {
return response()->json([
'message' => 'Unauthorized'
], 401);
}
return response()->json(['message' => 'Successfully login'], 200);
}
How can I authenticate user using login method? Since Auth::attempt() is not working are there any alternatives? Thanks!
Take email and password and check in the database manually.
$email = $request->input('email');
$password = $request->input('password');
$result = DB::table('users')->where('email', $email)->first();
if (!is_null($result)) {
if($password == $result->password) {
return response(200);
}
}
Checking in table users, in columns email and password.
Ok so what i'm trying todo, do not let login if user has not confirmed his account by email. My login code looks like that:
public function postLogin()
{
$credentials = [
'confirmed' => 0,
'email' => Input::get('email'),
'password' => Input::get('password')
];
$user = Sentinel::authenticate($credentials, false); // Login the user (if possible)
if ($user and $user->banned) {
Sentinel::logout();
$user = null;
}
if ($user) {
return $this->afterLoginActions();
} else {
$this->alertFlash(trans('app.access_denied'));
return Redirect::to('auth/login');
}
}
But i can still login without any errors. Any help? Thanks guys!
Edited: working, but now i dont get flash message if my details are incorect.
Code:
public function postLogin()
{
$credentials = [
'email' => Input::get('email'),
'password' => Input::get('password'),
'confirmed' => 1
];
$user = Sentinel::authenticate($credentials, false); // Login the user (if possible)
if ($user and $user->banned) {
Sentinel::logout();
$this->alertFlash(trans('app.banned'));
$user = null;
}
if ($user->confirmed==1) {
return $this->afterLoginActions();
}
else if ($user->confirmed==0) {
Sentinel::logout();
$this->alertFlash(trans('app.not_active'));
return Redirect::to('auth/login');
} else {
$this->alertFlash(trans('app.access_denied'));
return Redirect::to('auth/login');
}
}
Do you have a column in your table storing the information if this user passed the email confirmation? If you have one, this is what I do it with typical Laravel postLogin method.
public function postLogin(Request $request)
{
$credentialas = (your credential here);
// only check credentials
if ($this->guard()->once($credentials)) {
$currentStatus = $this->guard()->user()->status;
if (intval($currentStatus) === (NOT_CONFIRMED)) {
$this->guard()->logout();
return $this->sendSuspendedResponse($request);
} else {
$this->guard()->login($this->guard()->user());
return $this->sendLoginResponse($request);
}
}
}
I'm using Socialite to get user information from facebook. All is going well but my redirect isn't working
Sub-routes
I read that it's not possible to do a redirect from a submethod, or
any method that's not in your routes.
But how else can i redirect the user after I logged them in?
My URL looks like this after the successfull facebook handshake
http://tmdb.app/auth/login/facebook?code=AQBTKNZIxbfdBruAJBqZ8xx9Qnz...
Code
class SocialController extends Controller {
public function login(Authenticate $authenticate, Request $request)
{
return $authenticate->execute($request->has('code'), $this);
}
public function userHasLoggedIn($data)
{
$user = User::where('provider_id', $data->id)->first();
if( !$user )
{
$user = User::create([
'name' => $data->name,
'email' => $data->email,
'provider' => 'facebook',
'provider_id' => $data->id
]);
}
// NOT WORKING!
return redirect('test');
}
}
Your login function should be handling the redirect.
I'm guessing execute returns $data if the user is sucessfully logged in and false if not.
class SocialController extends Controller {
public function login(Authenticate $authenticate, Request $request)
{
if($data = $authenticate->execute($request->has('code'), $this))
{
$user = User::where('provider_id', $data->id)->first();
// maybe delegate the user creation to another class/service?
if( !$user )
{
$user = User::create([
'name' => $data->name,
'email' => $data->email,
'provider' => 'facebook',
'provider_id' => $data->id
]);
}
return redirect('test');
}
return redirect('fail_view');
}
}
You can do it using PHP header function in Laravel sub method. I try it and works properly. Hope it can help you.
// You can using the following code
$url= url("about-laravel");
header("Location:" . $url);
exit;
// Or using the following code to redirect and keep set flash message
$result= $this->yourMethod(); // return redirect($this->route)->with('flash_message', 'I\'m Flash Message'); for TRUE or NULL for false
if( $result ){
return $result;
}
Hi help me,
login code
public function store()
{
$credentials = array(
'u_email' => Input::get('email'),
'password' => Input::get('password'));
if (Auth::attempt($credentials) ) {
$user = Auth::user()->toArray();
$userrole = with(new User)->get_user_role($user['u_id']);
$userobj['u_id'] = $user['u_id'];
$userobj['u_shortcode'] = $user['u_shortcode'];
$userobj['utype'] = $user['utype'];
$userobj['u_title'] = $user['u_title'];
$userobj['u_fname'] = $user['u_fname'];
$userobj['u_lname'] = $user['u_lname'];
$userobj['u_email'] = $user['u_email'];
$userobj['u_role'] = $userrole;
$userobj['id'] = Session::getId();
Session::put('admin', $userobj);
$value = Session::get('admin');
return Response::json([
'user' => $userobj ],
202
);
}else{
return Response::json([
'flash2' => 'Authentication failed'],
202
);
}
}
and my second controller is:
public function get_sessionobj()
{
var_dump(Session::all());
$value = Session::get('admin');
print_r($value);
exit();
}
when i am calling second controller after login then session data not printed. in login controller Session::get('admin') function returning data. and i am using file driver for session storage. I have seen my session file there was some data like this:
a:5:{s:6:"_token";s:40:"XrUgs7QLPlXvjvyzFaTdmDpqGL0aSZRzkJS0il9f";s:38:"login_82e5d2c56bdd0811318f0cf078b78bfc";s:1:"1";s:5:"admin";a:9:{s:4:"u_id";s:1:"1";s:11:"u_shortcode";s:5:"u1001";s:5:"utype";s:1:"1";s:7:"u_title";s:3:"Mr.";s:7:"u_fname";s:6:"Aristo";s:7:"u_lname";s:5:"Singh";s:7:"u_email";s:24:"chandan.singh#jetwave.in";s:6:"u_role";a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}s:2:"id";s:40:"cd074f7f61fcc88b3d92c482e57e8a12dc888958";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1410525787;s:1:"c";i:1410525787;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
Call a function get_sessionobj() in store function
Example:
public function store(){
$this->get_sessionobj();
}