Sentry2 user model extension - laravel

I'm using Sentry2 package in my laravel 4 application (http://docs.cartalyst.com/sentry-2/).
I create a new User model that extends Sentry2 User Model:
<?php namespace App\Models;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends \Cartalyst\Sentry\Users\Eloquent\User implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
when I execute the follow code I have a exception.
$adminUser = User::create(array(
'email' => 'admin#admin.com',
'password' => "admin",
'first_name' => 'Admin',
'last_name' => 'Admin',
'activated' => 1,
));
Error:
[RuntimeException]
A hasher has not been provided for the user.

If you want to create your object from Eloquent mass alignment you can add the Hasher manually Like that :
$user->setHasher(new Cartalyst\Sentry\Hashing\NativeHasher);
Or to be permanent you can add a "boot" method to your User object like this :
class User extends \Cartalyst\Sentry\Users\Eloquent\User implements UserInterface, RemindableInterface {
// ...
public static function boot()
{
self::$hasher = new Cartalyst\Sentry\Hashing\NativeHasher;
}
// ...
}

I need to update the config file of sentry package:
'users' => array(
/*
|--------------------------------------------------------------------------
| Model
|--------------------------------------------------------------------------
|
| When using the "eloquent" driver, we need to know which
| Eloquent models should be used throughout Sentry.
|
*/
'model' => '\App\Models\User',
/*
|--------------------------------------------------------------------------
| Login Attribute
|--------------------------------------------------------------------------
|
| If you're the "eloquent" driver and extending the base Eloquent model,
| we allow you to globally override the login attribute without even
| subclassing the model, simply by specifying the attribute below.
|
*/
'login_attribute' => 'email',
),
and use Sentry::getUserProvider()->create() method
$adminUser = Sentry::getUserProvider()->create(
array(
'email' => 'admin#admin.com',
'password' => "admin",
'first_name' => 'Admin',
'last_name' => 'Admin',
'activated' => 1,
)
);

what it tell you is you have to hash and salt your password
so
$adminUser = User::create(array(
'email' => 'admin#admin.com',
'password' => Hash::make('admin'),
'first_name' => 'Admin',
'last_name' => 'Admin',
'activated' => 1,
));

I extended the Sentry User Model like you and the same error is returned, then i find an idea in https://github.com/cartalyst/sentry/issues/163 and then tried passing a new instance of NativeHasher; i'm not sure if this is the correct way, but in the first test the user was saved correctly:
$user = new User;
$user->setHasher(new Cartalyst\Sentry\Hashing\NativeHasher);
$user->first_name = "Name";
$user->last_name = "Last";
$user->password = 'admin';
$user->email = "email#gmail.com";
$user->save();

Related

How to read URL parameters in laravel

I am begginer, and trying to create a referral system. following is sample url
http://dev.lea.com/register?ref=mh2HPLpVSn
I try to get referral string. how can i get separately? is there need of middleware for getting cookies? if yes then what will be code of middleware? and how can i get referral reference in RegisterController?
Here is my Register Controller.
<?php
namespace Lea\Http\Controllers\Auth;
use DB;
use Lea\User;
use Lea\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Cookie;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'fname' => 'required|string|max:255',
'lname' => 'required|string|max:255',
'referral' => 'string|max:255',
'username' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
// 'tracking_id' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \Lea\User
*/
protected function create(array $data, Request $request)
{
// printing here referral Link
echo $request()->ref;
// $referred_by = Cookie::get();
// print_r($referred_by);
die;
return User::create([
'fname' => $data['fname'],
'lname' => $data['lname'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'affiliate_id' => str_random(10),
// 'referred_by' => $referred_by,
'identity' => $data['identity'],
'dob' => $data['dob'],
'board_id' => $data['board_id'],
'class_id' => $data['class_id'],
'subject_id' => $data['subject_id'],
'institute' => $data['institute'],
'address' => $data['address'],
'city' => $data['city'],
'std_mobile' => $data['std_mobile'],
'father_name' => $data['father_name'],
'father_mobile' => $data['father_mob'],
'ipadress' => \Request::ip(),
]);
}
}
When you have an URI such as /register?ref=mh2HPLpVSn you can retrieve ref like this:
$request()->ref
in your controller! I believe you can also use $request()->has('ref') to determine if it's present in the URI.
Hope this helps you!!
In laravel 6+ inside controller you can use like
$request->get('ResourcePath')
You can get your parameters using Request access.
Here one example for get your ref code:
public function register(Request $request)
{
$allParams = $request->all();
$refParam = $request->ref;
dd($allParams, $refParam);
...
}
public function showRegister(Request $request) {
var_dump(request->ref)
}
then you can do things like validation and so on, another possiblity is to change the template of your register form and add a hidden field with the refcode from the ref param and handle the whole request in your register method.

Laravel Guzzle conflicts with /register Route::auth()

I'm new to use Laravel. I'm using Laravel 5.2. I've implemented Auth for user register and login. It is work properly. After installed Guzzle via composer and after that implementing sending email, it works like a charm. But after try to submit register user, the data which sent via POST form, not saved in table. How to keep data recorded in table meanwhile sending email still works?
AuthController for handling user registration:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\PencapaianBadge;
use DB;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'username' => 'required|max:10|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
//Ambil id user dengan menhitung jumlah rows
$id = DB::table('users')->count();
/*PencapaianBadge::create([
'id_user' => $id+1,
'id_badge' => 1,
]);*/
$Pencapaian = new PencapaianBadge();
$Pencapaian->id_user = $id+2;
$Pencapaian->id_badge = 1;
$Pencapaian->save();
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role_id' => 2,
'path_image' => 'main/resources/assets/images/user_profiles/default.png',
]);
}
}

multi auth not working in laravel 5.1

I am using Laravel 5.1 and I need multiple login in my project so I am trying Kbwebs\MultiAuth and Sarav\Multiauth for multi auth, both are worked with user model model but unfortunately when I use TenderApplicant model Auth::attempt return false every time.
This is my code:
app.php
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Foundation\Providers\ArtisanServiceProvider::class,
Illuminate\Auth\AuthServiceProvider::class,
Sarav\Multiauth\MultiauthServiceProvider::class,
...
auth.php
return [
'multi' => [
'admin' => [
'driver' => 'eloquent',
'model' => App\User::class,
'table' => 'sa_users',
],
'user' => [
'driver' => 'eloquent',
'model' => App\Models\TenderApplicant::class,
'table' => 'tender_applicant',
],
],
'password' => [
'email' => 'emails.password',
'table' => 'sa_password_resets',
'expire' => 60,
],
];
AuthController.php
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
public function userAuth(Request $request)
{
$this->validate($request, ['email' => 'required','password' => 'required']);
$email = $request->input('email');
$password = $request->input('password');
var_dump(Auth::attempt("user", ['email' => 'awal.ashu#gmail.com', 'password' => '123456']));
}
return false for user but admin worked perfected.
TenderApplicant.php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class TenderApplicant extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'tender_applicant';
protected $primaryKey = 'TE_APP_ID';
const CREATED_AT = 'CREATED_AT';
const UPDATED_AT = 'UPDATED_AT';
protected $fillable = [
'TENDER_ID',
'SCHEDULE_ID',
'PR_DETAIL_ID',
'NID',
'PR_CATEGORY',
'PR_TYPE',
'APPLICANT_NAME',
'EMAIL',
'APPLICANT_PHONE',
'PASSWORD',
'HOLDING_NO',
'IS_TE_SC_BOUGHT',
'TE_SC_AMOUNT',
'TE_SC_DATE',
'SPOUSE_NAME',
'BID_AMOUNT',
'BG_AMOUNT',
'BG_AMOUNT_TEXT',
'BANK_ID',
'B_DRAFT_NO',
'B_DRAFT_DATE',
'B_DRAFT_ATTACHMENT',
'IS_SELECTED',
'IS_ACTIVE',
'CREATED_BY',
'UPDATED_BY'
];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guarded = ['TE_APP_ID'];
/**
* Password need to be all time encrypted.
*
* #param string $password
*/
public function setPasswordAttribute($password)
{
$this->attributes['PASSWORD'] = bcrypt($password);
}
}
By default, Laravel excepts you to keep password field as "password". In case you change(you have kept as PASSWORD), you have to inform Laravel about your password field change.
Please add the following code to your TenderApplicant.php file and check
public function getAuthPassword()
{
return $this->PASSWORD;
}
And then try accessing like the following,
Auth::attempt('admin', ['EMAIL' => 'youremail#gmail.com', 'password' => 'your_password']);
NOTE : You don't have to change your password as PASSWORD in here, because we have defined our method in model.
When you try attempting Auth::attempt(), laravel will run following query
SELECT * FROM "your_auth_table" WHERE email = "given_email" LIMIT 1
Then with the obtained result, laravel will take password field from the obtained result which will be hash.
Then it will call getAuthPassword() method from model and get the password field you have provided. By default it will be "password". Now with php function
password_verify
, laravel will verify your hash password with user given plain text and initiate user session
For more information you can check this blog.
http://blog.sarav.co/laravel-password-management-mechanism/

Route is not found -logout

I am trying to click on logout button, but it returns an error:
NotFoundHttpException in RouteCollection.php line 161:
There's no getLogout in Authcontroller, and it worked before, not sure why now it isn't.
AuthController:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = "dashboard";
protected $loginPath = 'auth/login';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'username' => 'required|max:20|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
]);
}
}
Routes.php:
Route::get('auth/logout', 'Auth\AuthController#getLogout');
view:
Logout
Try
Logout
Or give your route a name
Route::get('auth/logout', ['as' => 'logout', 'uses' => 'Auth\AuthController#getLogout');
and do
Logout

Laravel 5.1 - Store Data in Eloquent: Relationships

I folowing Official Laravel 5.1 User Authentication to create User Login and User Register and it is run well.
But now, I add another table, user_detail table, which contain another data of user like first/last name, gender, etc. This table has one to one relationship with user table. And I already defining relationships like hasOne and belongsTo.
I want to ask, how when I registered a new user, the both user and user_detail table is filled? Although the user_detail tables just filled in the 'id' only, because the user table and user_detail table have same id for primarykey and foreignkey.
For reference here my routes:
...
// Registration routes...
Route::get('auth/register', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
...
AuthController:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\UsersDetail;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller {
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers,
ThrottlesLogins;
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data) {
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data) {
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
protected $redirectPath = '/dashboard';
}
Here is one way of doing it.
$user = new \User($data)->save();
$user_detail = new \UserDetail($detail_data);
$user->user_detail()->associate($user_detail);
Okay, I think #ajameswolf method is to update data. What I need is to create a data in two table which have relation.
I use this method in my AuthController.
protected function create(array $data) {
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$user_detail = UsersDetail::create([
'birthOfDate' => null
]);
$user->save();
$user_detail->save();
return $user;
}

Resources