When i want change password user and user table got relationship i made detch, next i can change password but how use attach to add again thats same role what user got?
Route::post('profil/changepassword', function() {
$User = User::find(Auth::user()->id);
//$User->roles()->$rola;
$User->roles()->detach();
if(Hash::check(Input::get('passwordold'), $User['password']) && Input::get('password') == Input::get('password_confirmation')){
$User->password = bcrypt(Input::get('password'));
$User->save();
$User->roles()->attach(1);
return back()->with('success','Hasło zostało zmienione');
}
else{
return back()->with('error','Hasło nie zostało zmienione');
}
});
I made something like that and when user change password it will get role User. When Moderator change password thats same get User role not moderator like got befor. So i ask how i can figure it becouse i will use detach in other funcion and i really dont know how make it.
Related
I have a two different login forms for user and admin. What I want is the user should only login in their own form otherwise it should be an error, and just the same for the admin form.
I only have 1 table for both user and admin in my database. They only differ in user_type which is obviously "admin" and "user"
What I am doing is when the user tried to login in admin login form it shows an info that says 'sorry, you are not an admin in this site'. But that means that the user is still logged in.
What I want is when the tries to login in admin form I don't want it to access the system at all.
Here my code so far:
public function validateLoginResort(Request $requests){
$username = $requests->username;
$password = $requests->password;
$attempt = Auth::attempt([
'email' => $requests->username,
'password' => $requests->password,
]);
if(Auth::check()){
if(Auth::user()->type_user == 'admin'){
return redirect('home');
}
else{
Auth::logout();
return redirect('login');
}
}else{
return "Invalid input";
}
}
I tried using Auth::logout if the user is not an admin but I dont think it is safe and right at all.
I think there is still a better way to do this, can you guys give a suggestion on how to implement this correctly? Thank you
You could check user type first, and then login user if he/she is admin.
Suppose your user table name is "users" and corresponding eloquent model is "User", then you could do this:
$user = User::where('email', $request->get('email'))->first();
if (!$user || !\Hash::check($request['password'], $user->password)) {
return 'Invalid user credential';
}
if ($user->type_user !== 'admin') {
return 'Only admin allowed';
}
\Auth::login($user); // This is the key point.
return redirect('home');
You're struggling in creating custom code in laravel how the thing works. I suggest you use the laravel package located here: https://github.com/spatie/laravel-permission it allows you to manage user permissions and roles in a database
Thanks,
I want to create a simple check if a user exists in my database just after he is logged on (LDAP Authentication). If he doesn't exist, a record should be created in the db.
Is there any standard CakePHP 3.x -way of doing such things?
Or I can just create a function in my "users" Controller which checks if a user exists in the db and call it in the end of login() function (if user session has been successfully created)?
public function login(){
if ($this->request->is('post')){
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$this->createStudent($user);
return $this->redirect($this->Auth->redirectUrl());
}
// user is not identified
$this->Flash->error('Your username or password is not correct');
}
}
public function createStudent($user){
$studExists = $this->Students->find('isExists', ['uid' => $user['uid']]);
if (!$studExists) {
$student = $this->Students->newEntity();
$data = ['id' => $user['uid']];
$student = $this->Students->patchEntity($student, $data);
if ($this->Students->save($student)) {
$this->Flash->success(__('It is your first logon. You have been added to our database!'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('You could not be saved in our database. Please, try again.'));
}
}
}
Thank you in advance.
What you have shown works but a better way would using an event from your LDAP authenticate class to notify that a new user record needs to be created in your app. Your table's createStudent() can be set as a listener callback for that event. Also your LDAP authenticate class should also only return info if a matching record is found in your datbase table, which I don't think is the case currently.
You can refer to this HybridAuthAuthenticate which does similar. The readme of the plugin shows how to setup listener for the event.
I have a page where i can modify user details (username,first name,avatar...).
I have an element in my navbar with informations about the currently logged in user. The thing is I can't figure out how to refresh the session immediately after data is modified.
in UsersController:
public function edit($id = null)
{
if (!$id) {
throw new NotFoundException(__('Invalid user'));
}
$user = $this->Users->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
//REFRESH SESSION ????\\
$this->request->session()->write('Auth.User', $user);
//\\
$this->Flash->success(__('User has been updated.'));
return $this->redirect(['action' => 'edit/' . $id]);
}
$this->Flash->error(__('Unable to update User details.'));
}
$this->set(compact('user'));
}
Just update it the same way as you're setting it when loggin in, ie using AuthComponent::setUser().
Also you may want to do that only in case the user that has been edited, is actually the user that is currently logged in. And you want to set the data in the same format as the Auth component does, that is (for now), as an array, and, for security purposes, without the password.
A simple example that assumes a single column primary key named id, and a password column named password
if ($this->Auth->user('id') === $user->id) {
$data = $user->toArray();
unset($data['password']);
$this->Auth->setUser($data);
}
See also
Cookbook > Controllers > Components > Authentication > Identifying Users and Logging Them In
Cookbook > Controllers > Components > Authentication > Manually Logging Users In
I implement socialite together with manual registration where register using facebook is a user's option. but i noticed that if the user registered first with the manual registration and logout then came back and register using facebook it produce an error
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry"
here is my current UserRepository
namespace App\Repositories;
use App\User;
class UserRepository{
public function findByUsernameOrCreate($userData)
{
return User::firstOrCreate([
'first_name' => $userData->first_name,
'last_name' => $userData->last_name,
'email' => $userData->email
]);
}
}
I recently had this issue. I was testing a pre registered user's ability to login with facebook and have their avatar and email updated when they did.
Assuming you can check for existing (non facebook) user by their email address.
$user = User::where('email', $userData->email)->first();
if ($user){
// Update existing user with facebook data.
$user->email = $userData->email;
// Any other fields you want to update.
$user->avatar = $userData->avatar;
$user->save();
return $user;
}
Then your original function here.
Mark is right, however the data will be updated each time the user connect with Facebook. Here's some improvements :
$authUser = User::where('email', $existingUser->email)->first();
if ($authUser){
// Check and update if Facebook data doesn't exists
if(!($authUser->facebook_id)){
$authUser->facebook_id = $existingUser->id;
$authUser->avatar = $existingUser->avatar;
$authUser->save();
}
return $authUser;
}
// following by your function here...
There does not appear to be any solution on Google searches for this. When logging into an account with Auth in Laravel, it updates the updated_at field for the user. I wish for it to not do this, and only update the updated_at for when the user details actually change.
How could I achieve this in Laravel 4?
UPDATE
I realise why it is updating the timestamp. This is because on user login, I update a field. Which obviously in turn updates the timestamp.
The question should be, how could I stop this update of a field updating the field?
Sample code:
public function postLogin()
{
$email = Input::get('email');
$password = Input::get('password');
if(Auth::attempt(array('email' => $email, 'password' => $password))){
$user = User::find(Auth::user() -> id);
$user -> online = 1;
$user -> timestamps = false;
$user -> save();
return Redirect::intended('/');
}else{
return Redirect::route('home') -> with('global', 'Failed to login');
}
}
public function getLogout(){
$user = User::find(Auth::user() -> id);
$user -> online = 0;
$user -> timestamps = false;
$user -> save();
Auth::logout();
return Redirect::route('home');
}
This is the updated code with the suggestion. This is still updating 'updated_at'.
I suspect it is Auth::logout() updating this but cannot find any documents relating to this.
Set this in your log in method, it will disable the time-stamps from updating.
$user = User::find(Auth::user() -> id);
$user->online = 1;
// disable the timestamps before saving
$user->timestamps = false;
$user->save();
Edit:
As Jarek Tkaczyk pointed out; the users state doesn't really belong in the User model. It also has a serious flaw, what if the users doesn't log out but instead his session expires?
You should instead use the sessions to figure out if a user is online (logged in and active), this is easy to do if you store the sessions in a database. http://laravel.com/docs/4.2/session#database-sessions
If you do not want to update created_at and updated_at columns while inserting and updating the record, set the $timestamps property on your model to false.
Like this:-
class User extends Eloquent {
protected $table = 'users';
public $timestamps = false;
}