Only email and password for login - laravel

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();

Related

How To Get Auth ID form user table and grab it for store to other table on database

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

Laravel Socialite Google login only with one domain

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');
}

How to attach variable to reset password link view in laravel?

I am using laravel 5.2 where I need to sent an OTP code to reset password, though email is being sent with built in subject and limited message done by make:auth command but how to customize? I have tried to follow the link unfortunately I am unable to understand how i can use this to solve.
I customized the api like this
public function sendResetLinkEmail(Request $request)
{
$this->validateSendResetLinkEmail($request);
$broker = $this->getBroker();
$email = $request->input('email');
$userid = DB::table('users')->where('email','=',$email)->value('id');
$uniqueotp = "DIYA".uniqid();
$curr_timestamp = strtotime(date("Y-m-d H:i:s"));
$date = strtotime("+7 day", $curr_timestamp);
$expiry_otp = date('Y-m-d H:i:s',$date);
$ip_address = $request->ip();
DB::table('otp_users')->insert([
'user_id' => $userid,
'status' => 0,
'otp_code' => $uniqueotp,
'ipaddress'=>$ip_address,
'expires_at'=>$expiry_otp
]);
$response = Password::broker($broker)->sendResetLink(
$this->getSendResetLinkEmailCredentials($request),
$this->resetEmailBuilder()
);
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->getSendResetLinkEmailSuccessResponse($request,$response);
case Password::INVALID_USER:
default:
return $this->getSendResetLinkEmailFailureResponse($response);
}
}
Any idea how I can achieve?
My required email message like this:
Hello, Tamaghna Banerjee Click here to reset your password:
Your OTP is: B16445512121
Reset Your Password through http://localhost/diya/public/password/reset/83baba9f61fc851b9d80b515415ec86c43b03b56b068e1888256db7a7831ba83?email=tamaghnabanerjee%40live.com

Creating edit function in the same controller laravel

So I have a create function in my controller as shown below and my routes is as such, my question is is there a way for me to put a condition to different create and edit in the same function as both have quite similar coding. Can someone enlighten me pls?
class ManageAccountsController extends Controller
{
public function index() {
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function update()
{
// process the form here
// create the validation rules ------------------------
$rules = array(
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the user table
'password' => 'required|min:8|alpha_num',
'password_confirm' => 'required|same:password', // required and has to match the password field
'mobile' => 'required',
'role_id' => 'required'
);
// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make(Input::all(), $rules);
// check if the validator failed -----------------------
if ($validator->fails()) {
// redirect our user back to the form with the errors from the validator
$input = Input::except('password', 'password_confirm');
$input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.
return redirect()
->back()
->withInput($input)
->withErrors($validator);
} else {
// validation successful ---------------------------
// user has passed all tests!
// let user enter the database
// create the data for our user
$user = new User;
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->mobile = Input::get('mobile');
$user->role_id = Input::get('role_id');
// save our user
$user->save();
// redirect ----------------------------------------
// redirect our user back to the form so they can do it all over again
Session::flash('flash_message', 'User successfully added!');
return redirect()->back();
}
}
}
routes.php
Route::get('manage_accounts', 'ManageAccountsController#index');
Route::post('manage_accounts', 'ManageAccountsController#update');
UPDATE OR CREATE
Try the updateOrCreate() in Eloquent to create or update a record matching the attributes.
Read API docs udateOrCreate()
Your code will be like:
Model::updateOrCreate( ['id' => $id], ['firstField' => 'value', 'secondField' => 'value'] );
Note: first parameter is the match to be found and second the data's to be saved.
Hope this is helpful.
Why don't you try moving some of this code out of your controller. If you were to use Repositories, then you would be able to encapsulate some of your logic in order to use it for both functions.
Also you can handle all this validation without writing all the extra code into your controller - see http://laravel.com/docs/5.0/validation#form-request-validation.
This may all seem a bit overkill at first, but once you get the hang of it, your code will be much more manageable and extendable.
(for more on these I would thoroughly recommend Jeffery Way's Laracasts https://laracasts.com/ - this helped me a lot when I was learning Laravel)
// routes.php
// http://laravel.com/docs/5.0/controllers#restful-resource-controllers
Route::resource('manage_accounts', 'ManageAccountsController');
// ManageAccountsController.php
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class ManageAccountsController extends Controller
{
public $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function index() {
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function store(StoreUserRequest $request)
{
// validation already handled using this: http://laravel.com/docs/5.0/validation#form-request-validation
$this->userRepository->upsert($request)
Session::flash('flash_message', 'User successfully added!');
return redirect()->back();
}
public function update(StoreUserRequest $request, $id)
{
// validation already handled using this: http://laravel.com/docs/5.0/validation#form-request-validation
$this->userRepository->upsert($request, $id)
Session::flash('flash_message', 'User successfully updated!');
return redirect()->back();
}
}
// UserRepository.php
class UserRepository {
public function upsert($data, $id = null)
{
// You will also need something like this
if(isset($data['id']))
{
$user = $this->user->find($data['id']);
}
else {
$user = new User;
}
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->mobile = $data['mobile'];
$user->role_id = $data['role_id'];
// save our user
$user->save();
return $user;
}
}
}
Please use the code here as a guide (I have written this in a hurry and it will certainly contain errors). Have a quick read up on repositories and I think it should all make sense.
The basic premise here is to separate out code that you want to re-use rather than squashing it all into the same function.
Hope this helps!

How to change user's password in joomla?

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');
}

Resources