Sentinel for laravel 5 - Cannot Logout - session persists - laravel-5.1

Laravel 5.1
Sentinel 2
Here is my logout() in controller:
public function logout()
{
$user = Sentinel::getUser();
Sentinel::logout($user, true);
return redirect('/shopadmin/login');
}
Here is how I login:
public function login(Request $request)
{
if (Sentinel::guest()):
$email = $request->get('email');
$pass = $request->get('password');
$credentials = [
'email' => $email,
'password' => $pass,
];
// $role = Sentinel::findRoleByName('admin');
$user = Sentinel::findById(1);
$user = Sentinel::findUserById(1);
if($user = Sentinel::authenticateAndRemember($user, $credentials)):
return redirect('/shopadmin');
else:
return view('backend.login');
endif;
else:
return redirect('/shopadmin');
endif;
}
And I also have this in my __contruct
public function __construct()
{
$this->layout = view('layouts.backend');
$user = Sentinel::check();
view()->share('user',$user);
}
No middleware
My problem is after logout runs, user should get redirected to login page, but instead it forwards me to the dashboard and Sentinel::getUser(); still shows active user.
with following:
**#persistableKey: "user_id"
#persistableRelationship: "persistences"**
Is there a different way to log out? I cannon flush entire session because I am keeping some non-user variables.
Technically, logout() should destroy all cookies and sessions related to user? correct? Then why in the Functional-Uniformly-Coded-Kernel my user is still logged in?!
Thanks for help!

Related

ZF2 optionally change user password in form

i want to have a form, where a logged in user can change his user data. Optionally he can insert a new password. I tried to remove the inputfilter of the 'password' and 'passwordVerification' fields, if the posted password is empty, but i don't know how to handle the save in my service, that the password gets not overwritten...
Controller action
public function indexAction() {
$identity = $this->authentication()->getIdentity();
$userService = $this->userService;
$form = $this->userForm;
$form->bind($identity);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->get('password')->getValue() == '') {
$validationGroup = $form->getValidationGroup();
$passwordKey = array_search('password', $validationGroup);
$passwordVerificationKey = array_search('passwordVerification', $validationGroup);
unset($validationGroup[$passwordKey]);
unset($validationGroup[$passwordVerificationKey]);
$form->setValidationGroup($validationGroup);
$form->getInputFilter()->remove('password');
$form->getInputFilter()->remove('passwordVerification');
}
if ($form->isValid()) {
$userService->saveUser($form->getData());
$this->flashMessenger()->addSuccessMessage('Data has been saved successfully');
return $this->redirect()->toRoute('admin/account');
}
}
return array(
'userForm' => $form
);
}
User service
public function saveUser(User $user) {
if ($password = $user->getPassword()) {
$user->setPassword($this->authenticationService->getAdapter()->getBcrypt()->create($password));
}
$this->userRepository->save($user);
}
when i'm doing this i use a use an unmapped password property (e.g. passwordForm) in my user entity which is used in the form so the original password is not overridden. if the passwordForm field is filled you can override the original password with that value

Routing After Login zf2

Hi everyone I'm new with Zend Framework 2 , for ruthentification on my project i used this module (( http://samsonasik.wordpress.com/2013/05/29/zend-framework-2-working-with-authenticationservice-and-db-session-save-handler/#comment-5393 )) and i add the field "Role" on data base.
I want to ask how can i make a specific route for any member of user, for example if the user’s Admin when he connect he will be redirected automatically to route “Admin” and if the user’s “visitor” he will be redirected to route “visitor” ???
Thx
/** this function called by indexAction to reduce complexity of function */
protected function authenticate($form, $viewModel)
{
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$dataform = $form->getData();
$this->authService->getAdapter()
->setIdentity($dataform['username'])
->setCredential($dataform['password']);
$result = $this->authService->authenticate();
if ($result->isValid()) {
//authentication success
$resultRow = $this->authService->getAdapter()->getResultRowObject();
$this->authService->getStorage()->write(
array('id' => $resultRow->id,
'username' => $dataform['username'],
'ip_address' => $this->getRequest()->getServer('REMOTE_ADDR'),
'user_agent' => $request->getServer('HTTP_USER_AGENT'))
);
// your userid -> select the role
$role = $this->getRoleUser($resultRow->id);
return $this->redirect()->toRoute('success', array('action' => 'index', 'role'=>$role));
} else {
$viewModel->setVariable('error', 'Login Error');
}
}
}
}
Then into your success page, just perform some actions using the param role
Don't forget to create a function $role = $this->getRoleUser($resultRow->id); to get the role of the user.
To implement roles function
check before this documentation to how to configure and create models/database: http://framework.zend.com/manual/2.1/en/user-guide/database-and-models.html
protected function getRoleUser($userid){
$table = $this->getServiceLocator()->get('User\Model\UserTable');
return $table->find($userid)->current()->role;
}

asp.net mvc after logout when login from other user previous users detail is showing

I have a web application, when the first user logs in and open his profile and logout. when second user login on same computer after logout first user, and open profile, it showing first user profile. second user has to refresh page.
how to prevent this, I have used
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult profile()
{
usertb user = db.usertbs.SingleOrDefault(a => a.EMail == userid);
return View(user );
}
please help me solve it
Does it work if you remove the OutputCache attribute from the action method?
//[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult profile()
{
usertb user = db.usertbs.SingleOrDefault(a => a.EMail == userid);
return View(user );
}
If so, you should be able to resolve this with 2 steps. First, put this in your Global.asax file:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
return "User".Equals(custom, StringComparison.OrdinalIgnoreCase)
? User.Identity.Name
: base.GetVaryByCustomString(context, custom);
}
After that, you can use the following OutputCache attribute on your action:
[OutputCache(NoStore = true, Duration = 60, VaryByCustom = "User")]
public ActionResult profile()
{
usertb user = db.usertbs.SingleOrDefault(a => a.EMail == userid);
return View(user );
}
All you need is set the location of your OutputCache to Client, this will cache the personalize data on the browser and every user will gets a cache of his own.
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*", Location=OutputCacheLocation.Client)]
public ActionResult profile()
{
usertb user = db.usertbs.SingleOrDefault(a => a.EMail == userid);
return View(user );
}
See this:
Improving Performance with Output Caching (C#)

Authenticating User via Ajax: User.Identity.IsAuthenticated in ajax method, but False elsewhere

I'm using Facebook to preautheticate users, so when they visit a page, an ajax function is called to login the user, and the server will also check to see if the user is already authenticated to the site. These users have entries in the user database on the server.
The server side code is below, which is called by ajax. After that, is a second method I use to get more information on the user that is stored in the database.
When I call User.Identity.IsAuthticaed in the second method, in the same Controller, the User object is still null. The User object contains all the information in FBReg below.
Edit:
After further troubleshooting I found that the ActionResult that calls getUserInfo() has the User object populated. So I'm not sure why getUserInfo() has a null User. I guess I can just pass the object then, but I'm still just curious why this happens.
[HttpPost]
public String FBReg(FBInfo userinfo)
{
..
..
..
if (!User.Identity.IsAuthenticated)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(userinfo.id, "FBPassword"))
{
FormsAuthentication.SetAuthCookie(userinfo.id, true);
var result = (from u in db.users where (u.username == userinfo.id) select u).FirstOrDefault();
result.LastLoginDate = DateTime.Now;
db.SaveChanges();
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
..
..
..
return "";
}
public UserRepository getUserInfo()
{
bool isauth = false;
try
{
if (User.Identity.IsAuthenticated) // User is always null even after FBReg has User as Authnticated with all the correct information
{
isauth = User.Identity.IsAuthenticated;
}
}
catch { }
// get user info from database to display on page
..
..
..
return userInfo;
}

allow users to change their own password, email and Profile

I'm creating my own blog engine to learn Symfony, and I have a question :
I can add and edit users thanks to the sfGuardUser module, but how can I allow users to edit only their reccord ?
Users should have access to a page allowing them to edit their email, name, password, and Profile.
Any ideas ?
In the action where the profile is updated you retrieve the users object via the getId() method and apply the changes on the returning object.
$user = sfGuardUserPeer::retrieveByPK(
$this->getUser()->getGuardUser()->getId()
);
I found the following code, will try it tonight.
class sfGuardUserActions extends autoSfGuardUserActions {
public function executeEdit(sfWebRequest $request) {
$this->checkPerm($request);
parent::executeEdit($request);
}
public function checkPerm(sfWebRequest $request) {
$id = $request->getParameter('id');
$user = sfContext::getInstance()->getUser();
$user_id = $user->getGuardUser()->getId();
if ($id != $user_id && !($user->hasCredential('admin'))) {
$this->redirect('sfGuardAuth/secure');
}
} }
from http://oldforum.symfony-project.org/index.php/m/96776/

Resources