I am writing a custom registration / authorization module for joomla and I'm wondering how with default joomla methods I could change user password? At the moment I have:
private function UpdateUser(){
$user = JFactory::getUser($this->user_data['username']);
$user->set('password', $this->user_data['password']);
$user->set('password2', $this->user_data['password']);
// $user->bind();
$user->save();
}
but the password is not updated.
P.S.
$this->user_data includes other staff about user, but i need update only password.
Solved.
private function UpdateUser($username, $password){
$user = JFactory::getUser($this->GetIdByUserName($username));
$password = array('password' => $password, 'password2' => $password);
if(!$user->bind($password)){
die('Could not bind data. Error: '.$user->getError());
}
if(!$user->save()){
die('Could not save user. Error: '.$user->getError());
}
}
private function GetIdByUserName($username){
$query = $this->db->getQuery(true);
$query->select('id');
$query->from('#__users');
$query->where('username=' . $this->db->Quote($username));
$this->db->setQuery($query);
if(isset($this->db->loadObject()->id) && !empty($this->db->loadObject()->id))
return $this->db->loadObject()->id;
else
die('No id');
}
Related
I have many attributes for the users' table. Admin needs to register a new user. My question is how to log in only with email and password?. my code now when user login user will get this error and this users database table . I only want to insert email and password when login in.
Controller\Auth\AuthController.php
public function login(Request $request)
{
if (!\Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
return redirect()->back();
} else {
return view('layouts.admin');
}
}
Http\UserController.php
public function store(Request $request)
{
$user = new User();
$user->Id_staff = $request['Id_staff'];
$user->name = $request['name'];
$user->noIc = $request['noIc'];
$user->email = $request['email'];
$user->password = bcrypt($request['password']);
$user->pusat_tangungjawab = $request['pusat_tangungjawab'];
$user->jawatan = $request['jawatan'];
$user->user_group = $request['user_group'];
$user->user_level = $request['user_level'];
$user->phone_no = $request['phone_no'];
$user->save();
return redirect()->route('users.index');
}
If you create a migration for users table, maybe the reason for that error because you didn't set nullable for Id_staff. So if you create a user and didn't post a value of Id_staff you will get that error. Some solutions is set a default value by random or set nullable in your migration, for example:
$table->string('Id_staff')->nullable();
I want to get Auth ID from user who has logged in and then use the Auth ID to store on other table
User_detail Controller
this is my store function
$data = new ModelUser();
$user= new user();
$data->fill(Auth::user());
$data->id_user = Auth::get('id');
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
and this is function Login
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
$data = user::where('email',$email)->first();
if($data) //check email apakah ada atau tidak
{
if(Hash::check($password,$data->password))
{
Session::put('id',$data->id);
Session::put('full_name',$data->full_name);
Session::put('email',$data->email);
Session::put('login',TRUE);
return redirect('userdt');
}
else
{
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
}
}
this is the routes files
Route::get('/index','UserController#show')->name('surevey.index');
Route::get('/logout','UserController#Logout')->name('user.logout');
Route::post('/registerpost','UserController#RegisterPost')->name('user.register');
Route::post('/loginpost','UserController#LoginPost')->name('user.login');
//reward routes
Route::get('/reward','RewardController#index')->name('reward.list');
//profile
Route::put('/editprofile/edit/{id}','UserController#edit')->name('profile.edit');
Route::post('/editprofile/update','UserController#update')->name('profile.update');
Route::get('/userdt',['middleware'=>'auth','uses'=>'UserController#userdetail'])->name('userdt.show');
Route::post('/userdt/store','UserController#store')->name('userdt.store');
//Survei
Route::get('/createsurvey','SurveyController#show')->name('survey.create');
Route::get('/surveylist','SurveyController#index')->name('survey.list');
Auth::routes();
ModelUser
protected $fillable = [
'id_user',
'jenis_kelamin',
'no_tlp',
'jurusan',
'wilayah'
];
protected $table ='user_detail';
public function user()
{
return $this->belongsTo(user::class);
}
and I get error like this
Argument 1 passed to Illuminate\Database\Eloquent\Model::fill() must
be of the type array, null given, called in
E:\Laravel\surevey\app\Http\Controllers\UserController.php on line 110
You don't need to use $data->fill(Auth::user()); as you have only single user_id field need to set.
Also you can get the current logged in user's id using. \Auth::user()->id
So your code would be as follow:
$data = new ModelUser();
$data->id_user = \Auth::user()->id;
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
Note: Make sure you have included auth middleware with your route.
Like:
Route::get('profile', ['middleware' => 'auth', function() {
// Only authenticated users may enter...
}]);
And you have followed the authuntication process carefully.
https://laravel.com/docs/5.2/authentication
Edited:
Your loging should be changed as:
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('userdt');
}
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
If your reverse one-to-one relationship in the User Model looks like this:
public function detail()
{
return $this->hasOne(ModelUser::class);
}
And you are sure a user is logged in, you could simply do this
$data = Auth::user()->detail()->save($request->all());
return redirect()->route('surveylist');
Laravel's ORM takes care of the rest.
should be Auth::id() or Auth::user()->id but seems like your Auth::user() is returning a null.make sure you sessions, routes are set up properly.
use Auth::attempt()to login user
I have a Google+ login on my app with Laravel Socialite. When the login is done I have a callback to connect the user (I create her in database if necessary).
But I want to restrain the connection to only the company (email like "example#company.com", so only the email with "company.com").
Can I do it with Laravel Socialite ? I can make the verification manually in my callback but if Socialite can do it, it's better.
Thank you
My callback :
public function handleProviderCallback($provider){
$user = Socialite::driver($provider)->user();
if ($user) {
$local_user = User::whereEmail($user->getEmail())->first();
// If we don't have a user create a new user
if (!$local_user) {
$fragment = explode(' ', $user->getName());
$local_user = User::create([
'first_name' => isset($fragment[0]) ? $fragment[0] : '',
'last_name' => isset($fragment[1]) ? $fragment[1] : '',
'email' => $user->getEmail(),
'last_seen' => Carbon::now(),
'password' => ''
]);
$local_user->roles()->attach(Role::whereName('User')->first());
}
auth()->login($local_user);
}
return redirect($this->redirectTo);
}
You have a step by step guide for domain restriction.
In controller you need to specifiy these actions:
public function handleProviderCallback()
{
try {
$user = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect('/login');
}
// only allow people with #company.com to login
if(explode("#", $user->email)[1] !== 'company.com'){
return redirect()->to('/');
}
// check if they're an existing user
$existingUser = User::where('email', $user->email)->first();
if($existingUser){
// log them in
auth()->login($existingUser, true);
} else {
// create a new user
$newUser = new User;
$newUser->name = $user->name;
$newUser->email = $user->email;
$newUser->google_id = $user->id;
$newUser->avatar = $user->avatar;
$newUser->avatar_original = $user->avatar_original;
$newUser->save();
auth()->login($newUser, true);
}
return redirect()->to('/home');
}
No, you can’t do it in Socialite itself because Socialite is just a mechanism of retrieving tokens from OAuth-compliant servers.
If you only want to accept users with a particular email suffix, then that’s business logic so something you should handle in your callback:
public function handleProviderCallback()
{
$user = Socialite::driver('google')->user();
if (Str::endsWith($user->getEmail(), '#example.com')) {
// Look up user and authenticate them
}
abort(400, 'User does not belong to organization');
}
Update password is not working
private function hash_password($password)
{
return password_hash($password, PASSWORD_BCRYPT);
}
private function verify_password_hash($password, $hash)
{
return password_verify($password, $hash);
}
I have used same code to add user after adding user I can do login to the account.
But when I change the password after updating password login failed
Here is reset password code
public function resetPassword($id) {
$password = $this->input->post('password');
$newdata = array(
'password' => $this->hash_password($password),
);
$this->admin_model->changePassword($id,$newdata);
$result ="Password changed";
echo $result;
die;
}
You can't login because the inputted passwords hash is not equal to the passwords hash saved in the database.
Try reading this Hope it will help you.
So I have this login method:
public function login(){
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]|xss_clean');
$this->form_validation->set_rules('password','Username','trim|required|min_length[4]|xss_clean');
if($this->form_validation->run()== FALSE) {
//Loading View
$this->load->view('admin/layouts/login');
$username = $this->input->post('username');
$password = $this->input->post('password');
//Validate Username & Password
$user_id = $this->Authenticate_model->login($username, $password);
if($user_id){
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => true
);
//Set session userdata
$this->session->set_userdata($user_data);
} else {
//Set message
$this->session->set_flashdata('pass_login', 'You are now logged in');
redirect('admin/dashboard');
}
}
}
And then i use this simple method to logout:
public function logout(){
//Unset User Data
$this->session->unset_userdata('user_id');
$this->session->unset_userdata('username');
$this->session->unset_userdata('logged_in');
$this->session->sess_destroy();
redirect('admin/authenticate/login');
}
So basically I'm unsetting all my sessions userdata and then redirecting back to login controller. And what happens is, when i redirect back to login page, I automatically login again, like if my session data was still valid and present. Why it's happening?
You could try
unset($this->session->userdata('user_id'));
unset($this->session->userdata('logged_in'));
unset($this->session->userdata('username'));
Or Just Have
$this->session->sess_destroy();
Make sure your session library auto loaded and have configured your settings depending on version of codeigniter
maybe you place "redirect if session == true" code at __construct, there is my problem :v