SECURE LOGIN SYSTEM – PHP(LARAVEL) – 2
This is the second part of Secure Login System – PHP(Laravel) series If you missed part 1 click here. Let’s complete our registration module in this part. In part 1 we have created Profile model now we will create its table structure below is our SQL and migration to create a profile table
php artisan migrate:make SystemTableProfileCreate
2014_04_03_085059_SystemTableProfileCreate.php
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('profile', function($table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->bigInteger('user_id')->unique();
$table->string('username', 255);
$table->string('email', 255);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('profile');
}
sql
CREATE TABLE IF NOT EXISTS `profile` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`updated_at` datetime NOT NULL,
`created_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
We have already created register view in part 1 now we will handle registration flow. When the user clicks register our form will be posted to storeRegister() of LoginController. In storeRegister we will take a username, email, password, and password_confirmation validate it. If validator passes then we will register a user, user registration code block have two lines commented if you do not want to auto-activate the user uncomment second register method and comment the first one also uncomment code which sends a mail to a user with an activation code. By default, our code registers a user, adds a user to users group If the group is not yet created then it will create two groups first is users and second is an admin.
public function storeRegister() {
// Gather Sanitized Input
$input = array('username' => Input::get('username'), 'email' => Input::get('email'), 'password' => Input::get('password'), 'password_confirmation' => Input::get('password_confirmation'));
// Set Validation Rules
$rules = array('username' => 'required|min:4|max:20|unique:profile,username', 'email' => 'required|min:4|max:32|email', 'password' => 'required|min:6|confirmed', 'password_confirmation' => 'required');
//Run input validation
$v = Validator::make($input, $rules);
if ($v -> fails()) {
return Redirect::to('/register') -> withErrors($v) -> withInput(Input::except(array('password', 'password_confirmation')));
} else {
try {
//Pre activate user
$user = Sentry::register(array('email' => $input['email'], 'password' => $input['password']), true);
//$user = Sentry::register(array('email' => $input['email'], 'password' => $input['password']));
//Get the activation code & prep data for email
$data['activationCode'] = $user -> GetActivationCode();
$data['email'] = $input['email'];
$data['userId'] = $user -> getId();
//send email with link to activate.
/*Mail::send('emails.register_confirm', $data, function($m) use ($data) {
$m -> to($data['email']) -> subject('Thanks for Registration - Support Team');
});*/
//If no groups created then create new groups
try {
$user_group = Sentry::findGroupById(1);
} catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e) {
$this -> createGroup('users');
$this -> createGroup('admin');
$user_group = Sentry::findGroupById(1);
}
$user -> addGroup($user_group);
$user = new Profile();
$user -> user_id = $data['userId'];
$user -> email = $data['email'];
$user -> username = $input['username'];
$user -> save();
//success!
Session::flash('success_msg', 'Thanks for sign up . Please activate your account by clicking activation link in your email');
return Redirect::to('/register');
} catch (Cartalyst\Sentry\Users\LoginRequiredException $e) {
Session::flash('error_msg', 'Username/Email Required.');
return Redirect::to('/register') -> withErrors($v) -> withInput(Input::except(array('password', 'password_confirmation')));
} catch (Cartalyst\Sentry\Users\UserExistsException $e) {
Session::flash('error_msg', 'User Already Exist.');
return Redirect::to('/register') -> withErrors($v) -> withInput(Input::except(array('password', 'password_confirmation')));
}
}
}
We have added one more function to our LoginController which will handle the creation of groups in Sentry
public function createGroup($groupName) {
$input = array('newGroup' => $groupName);
// Set Validation Rules
$rules = array('newGroup' => 'required|min:4');
//Run input validation
$v = Validator::make($input, $rules);
if ($v -> fails()) {
return false;
} else {
try {
$group = Sentry::getGroupProvider() -> create(array('name' => $input['newGroup'], 'permissions' => array('admin' => Input::get('adminPermissions', 0), 'users' => Input::get('userPermissions', 0), ), ));
if ($group) {
return true;
} else {
return false;
}
} catch (Cartalyst\Sentry\Groups\NameRequiredException $e) {
return false;
} catch (Cartalyst\Sentry\Groups\GroupExistsException $e) {
return false;
}
}
}
Email Template is saved in views/emails/register_confirm.blade.php
<meta charset="utf-8" />
<h2>Welcome</h2>
<pre>
<b>Account:</b> {{{ $email }}}
To activate your account, <a href="{{ URL::to('register') }}/{{ $userId }}/activate/{{ urlencode($activationCode) }}">click
here.</a>
Or point your browser to this address:
{{ URL::to('register') }}/{{ $userId }}/activate/{{
urlencode($activationCode) }}
Thank you,
~The Support Team
If you are using email activation then you need to edit mail.php inside app/config set the following fields to make it work
'host' => 'your host here',
'username' => 'username/email',
'password' => 'password',
When the user activates account through email he will be redirected to activation route which will execute registerActivate method and activates a user then redirects to log in with a success message.
LoginController@registerActivate
public function registerActivate($userId, $activationCode) {
try {
// Find the user using the user id
$user = Sentry::findUserById($userId);
// Attempt to activate the user
if ($user -> attemptActivation($activationCode)) {
Session::flash('success_msg', 'User Activation Successfull Please login below.');
return Redirect::to('/login');
} else {
Session::flash('error_msg', 'Unable to activate user Try again later or contact Support Team.');
return Redirect::to('/register');
}
} catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
Session::flash('error_msg', 'User was not found.');
return Redirect::to('/register');
} catch (Cartalyst\Sentry\Users\UserAlreadyActivatedException $e) {
Session::flash('error_msg', 'User is already activated.');
return Redirect::to('/register');
}
}
If we enter a valid email, username, password & password_confirmation we will get a success screen as below
If you try to register already registered user then error will be shown as below
Thanks
KodeInfo
No Comments
Leave a comment Cancel