I can't find this website and I can't figure out what is wrong with my code.
I am trying to get true for var_dump(Auth::attempt()), but it is always false.
This is my controllers method:
public function vartotojoPrisijungimoForma(){
$view = View::make('vartotojai.vartotojoPrisijungimoForma',
array('title'=>'Vartotojo Prisijungimas'));
var_dump(Auth::attempt(array('vardas'=>'aaaaa','pw'=>'aaaaa')));
return $view;
}
In my database the username is stored as vardas and password as pw
My auth.php file looks like this:
<?php
return array(
'driver' => 'eloquent',
'model' => 'Vartotojai',
'table' => 'vartotojai',
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
And the model file which is Vartotojai.php, looks like this:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Vartotojai extends ModeliuBaze implements UserInterface, RemindableInterface{
protected $table = 'vartotojai';
public $timestamps = false;
protected static $rules = array(
'vardas'=>'required|unique:vartotojai|min:4|regex:/[a-zA-Z]$/',
'pw'=>'required|alpha_num|between:4,8|confirmed',
'pw_confirmation'=>'required|alpha_num|between:4,8'
);
protected static $messages = array(
'required' => ':attribute laukelis tuscias!',
'min'=> ':attribute laukelyje galimas minimalus(:min) simboliu kiekis!',
'between' => ':attribute laukelis gali buti nuo :min - :max simboliu intervale!',
'vardas.regex'=> ':attribute turi atitikti siuos simbolius (a-zA-Z)',
'unique'=> 'Jau vartotojas su tokiu vardu uzregistruotas!',
'alpha_num'=>':attribute laukelyje galima rasyti tik skaicius ir raides!',
'confirmed'=>'Nesutampa slaptazodziai!'
);
protected $hidden = array('password');
public function getAuthIdentifier(){
return $this->getKey();
}
public function getAuthPassword(){
return $this->password;
}
public function getRememberToken(){
return $this->remember_token;
}
public function setRememberToken($value){
$this->remember_token = $value;
}
public function getRememberTokenName(){
return 'remember_token';
}
public function getReminderEmail(){
return $this->email;
}
}
I tried to check Hash:
public function vartotojoPrisijungimoForma(){
$view = View::make('vartotojai.vartotojoPrisijungimoForma',
array('title'=>'Vartotojo Prisijungimas'));
$pw = Vartotojai::find('5');
var_dump(Auth::attempt(array('vardas'=>'aaaaa','pw'=>'aaaaa')));
var_dump(Hash::check('aaaaa',$pw->pw));
return $view;
}
And hash check shows true.
You either need to change your password field from 'pw' to 'password' in your database. Laravel validates the credentials with 'password'.
OR
You could change this function to:
public function getAuthPassword(){
return $this->pw;
}
Then your attempt function should be:
var_dump(Auth::attempt(array('vardas'=>'aaaaa','password'=>'aaaaa')));
Related
Basically I need to have a e-mail verification system. For clarity, I will post only needed chunks of code that have impact whatsoever. When user registers, a random 40 string token is generated and sent to them, that code is appended to the route like this:
Route::get('/user/verify/{token}', 'RegisterController#verifyUser');
So when user clicks on that link supposedly route should call this:
RegisterController:
public function verifyUser($token){
$verifyUser = new VerifyUser();
$verifyUser->token = $token;
$verifyUser->getByToken();
$user = new User();
$user->id = $verifyUser->user_id;
$user->get();
if(isset($verifyUser)){
if(!$user->verified){
$user->updateVerifiedStatus();
$status = "Uspešno ste verifikovali e-mail adresu. Sada se možete ulogovati";
} else{
$status = "Već ste se verifikovali.";
}
} else{
return redirect('/')->with('error', "Vaš e-mail ne postoji");
}
return redirect('/')->with('status', $status);
}
verify_user is table which has an id of the user, and the token field, and if user is not registered, there will be no instance of that user in the table, therefore -> if(isset($verifyUser)),
also, user table has an 'verified' field, which is a boolean and stores true and false values, therefore -> if(!$user->verified).
And here are models which are used in the above mentioned controller
VerifyUser:
class VerifyUser
{
public $user_id;
public $token;
public $created_at;
public $updated_at;
public function getByToken()
{
$result =
DB::table('verify_users')
->select('*')
->where('token', $this->token)
->first();
return $result;
}
public function create()
{
$result =
DB::table('verify_users')
->insert([
'user_id' => $this->user_id,
'token' => $this->token,
]);
return $result;
}
}
User
class User
{
public function get()
{
$result =
DB::table('users')
->select('*')
->where('id', $this->id)
->first();
return $result;
}
public function updateVerifiedStatus()
{
$data = [
'verified' => true,
];
$result =
DB::table('users')
->where('id', $this->id)
->update($data);
return $result;
}
}
So, when I click the link, everything passess, I get the success status, which tells me that $user->updateVerifiedStatus() funct is returned succesfully. But, when I check the table, the field is still false, and is not updated. Any ideas?
In a Symfony REST API project and we are implementing a validation for the params passed to the end points.
I'm trying to using forms for this purpose but they don't seem to work as expected.
Given this end point as example:
GET /users/
which accepts a companyId as param
we want that this param is required and integer.
The controller
public function getUsersAction(Request $request)
{
$user = new User();
$form = $this->createForm(new UserType(), $user, array(
'method' => 'GET'
));
$form->handleRequest();
if ( ! $form->isValid()) {
// Send a 400
die('form is not valid');
} else {
die('form is valid');
}
}
The form type
class UserType extends FormType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('companyId', 'integer');
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefaults(array(
'data_class' => 'ApiBundle\Entity\User',
'csrf_protection' => false
));
}
/**
* #return string
*/
public function getName()
{
return ''; // if this is not empty, the form is not submitted at all
}
}
The validation.yml
ApiBundle\Entity\User:
properties:
companyId:
- Type:
type: integer
- NotBlank: ~
- NotNull: ~
The config.yml
framework:
validation: { enabled: true, enable_annotations: false }
The Problem
$form->isValid() in the controller is always true
Please replace with
$form->handleRequest();
to
$form->handleRequest($request);
I hope it will work.
class Retailjob extends CFormModel {
public function getReatilProducts() {
$condition=false;
$user = Yii::app()->db->createCommand()
->select('tbl_retailjob.retailjobmaster_id, tbl_retailjob.joborderflag, tbl_retailjoborder.retailjob_id, tbl_retailjoborder.retailjobsub_id, tbl_retailjoborder.filename,tbl_retailpostpressjoborder.retailpostpressjo_id,tbl_retailpostpressjoborder.retailjobsub_id,tbl_retailpostpressjoborder.retailpostpresssub_id')
->from('tbl_retailjob')
->join('tbl_retailjoborder', 'tbl_retailjob.retailjobmaster_id=tbl_retailjoborder.retailjobmaster_id')
->join('tbl_retailpostpressjoborder', 'tbl_retailjob.retailjobmaster_id=tbl_retailpostpressjoborder.retailjobmaster_id')
->where('tbl_retailjob.retailjobmaster_id=:id', array(':id' => 7))
->queryAll();
return $user;
}
}
this is my model file
what i want to achieve is if $condition is truethen the where condition should be avoide and if it is false it should be included
can i achieve it like this
public function getReatilProducts() {
$condition=true;
$user = Yii::app()->db->createCommand()
->select('tbl_retailjob.retailjobmaster_id, tbl_retailjob.joborderflag, tbl_retailjoborder.retailjob_id, tbl_retailjoborder.retailjobsub_id, tbl_retailjoborder.filename,tbl_retailpostpressjoborder.retailpostpressjo_id,tbl_retailpostpressjoborder.retailjobsub_id,tbl_retailpostpressjoborder.retailpostpresssub_id')
->from('tbl_retailjob')
->join('tbl_retailjoborder', 'tbl_retailjob.retailjobmaster_id=tbl_retailjoborder.retailjobmaster_id')
->join('tbl_retailpostpressjoborder', 'tbl_retailjob.retailjobmaster_id=tbl_retailpostpressjoborder.retailjobmaster_id')
if ($condition !=true) {
->where('tbl_retailjob.retailjobmaster_id=:id', array(':id' => 7))
}
->queryAll();
return $user;
}
}
Try this:
public function getReatilProducts() {
$condition=true;
$command = Yii::app()->db->createCommand()
->select('tbl_retailjob.retailjobmaster_id, tbl_retailjob.joborderflag, tbl_retailjoborder.retailjob_id, tbl_retailjoborder.retailjobsub_id, tbl_retailjoborder.filename,tbl_retailpostpressjoborder.retailpostpressjo_id,tbl_retailpostpressjoborder.retailjobsub_id,tbl_retailpostpressjoborder.retailpostpresssub_id')
->from('tbl_retailjob')
->join('tbl_retailjoborder', 'tbl_retailjob.retailjobmaster_id=tbl_retailjoborder.retailjobmaster_id')
->join('tbl_retailpostpressjoborder', 'tbl_retailjob.retailjobmaster_id=tbl_retailpostpressjoborder.retailjobmaster_id');
if ($condition !=true) {
$command->where('tbl_retailjob.retailjobmaster_id=:id', array(':id' => 7));
}
$user = $command->queryAll();
return $user;
}
I need to override both authentication (for when user's trying to logging in) and also the function is being used to check if the user is logged in in the header of the application (the function that check the sessions and cookie to check if the user is logged in) but i don't know where are these methods? and also i don't know how to find where are these methods!
** The reason of ovveride is to also check a Flag, if the flag is FLASE don't authenticate the user, or even if the user is also authenticated on page change (header reload) log-out the user if the flag changed to FLASE**
It would be appreciated if you also helping me to find adequate references that can help me in similar situations beside yii/wiki and google i tried them :)
Regards,
For custom authentication extend CUserIdentity class:
app/components/UserIdentity.php
<?php
class UserIdentity extends CUserIdentity
{
const ERROR_USER_NOT_APPOVED=200;
private $_id;
/**
* Authenticates a user.
*
* #return boolean whether authentication succeeds.
*/
public function authenticate()
{
$criteria = new CDbCriteria;
$criteria->condition = 'LOWER(email.email)=LOWER(:email)';
$criteria->params = array(':email' => $this->username);
$member = Member::model()
->with('email')
->together()
->find($criteria);
if ($member === null) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
} elseif (!hash::check($this->password, $member->pass_hash)) {
$this->errorCode = self::ERROR_PASSWORD_INVALID;
} elseif (! $member->is_approved) {
$this->errorCode = self::ERROR_USER_NOT_APPOVED;
} else {
$this->_id = $member->id;
$this->username = $member->full_name;
$this->setState('email', $member->email->email);
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
/**
* #return integer the ID of the user record
*/
public function getId()
{
return $this->_id;
}
}
then create custom form (app/models/MainLoginForm.php):
<?php
/**
* MainLoginForm class.
* MainLoginForm is the data structure for keeping
* user login form data.
*/
class MainLoginForm extends CFormModel
{
public $email;
public $password;
public $rememberMe;
/**
* Declares the validation rules.
* The rules state that email and password are required,
* and password needs to be authenticated.
*/
public function rules()
{
return array(
array('email', 'filter', 'filter' => 'trim'),
array('email', 'required',
'message' => Yii::t('auth', 'Email address is required.')),
array('email', 'email',
'message' => Yii::t('auth', 'Enter a valid Email address.')),
array('password', 'required',
'message' => Yii::t('auth', 'Password is required.')),
// password needs to be authenticated
array('password', 'authenticate'),
array('rememberMe', 'safe'),
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'email' => Yii::t('auth', 'Email Address'),
'password' => Yii::t('auth', 'Password'),
'rememberMe' => Yii::t('auth', 'Remember me.'),
);
}
/**
* Authenticates the password.
* This is the 'authenticate' validator as declared in rules().
*/
public function authenticate($attribute, $params)
{
// we only want to authenticate when no input errors
if (! $this->hasErrors()) {
$identity = new UserIdentity($this->email, $this->password);
$identity->authenticate();
switch ($identity->errorCode) {
case UserIdentity::ERROR_NONE:
$duration = ($this->rememberMe)
? 3600*24*14 // 14 days
: 0; // login till the user closes the browser
Yii::app()->user->login($identity, $duration);
break;
default:
// UserIdentity::ERROR_USERNAME_INVALID
// UserIdentity::ERROR_PASSWORD_INVALID
// UserIdentity::ERROR_MEMBER_NOT_APPOVED
$this->addError('', Yii::t('auth',
'Incorrect username/password combination.'));
break;
}
}
}
}
and finally update your login method (actionLogin):
$form = new MainLoginForm;
if (isset($_POST['MainLoginForm'])) {
$form->attributes = $_POST['MainLoginForm'];
$valid = $form->validate();
if ($valid) {
// redirect
}
}
For auto logout you can extend CController:
app/components/MainBaseController.php
<?php
class MainBaseController extends CController
{
public $settings = array();
public function init()
{
parent::init();
// set global settings
// $this->settings = ...
if (YOUR_FLAG_VALIDATION AND !Yii::app()->user->isGuest) {
Yii::app()->user->logout();
}
}
}
and then use custom base controll:
class YourController extends MainBaseController
{
....
}
I have problem in CGrid while on sorting a relational data using relational model in `` page.
Briefly my scenario:
I have a user model: Entities=> id,username
And a profile Model: Entities=> id, firstname,lastname, user_id,etc..
I want to list profile model and username from user model in CGrid, so that sorting and searching perms well. In my case sorting username is done by user_id not by username. I want to search it by username,so i do the following,
My Controller Action:
$model = new Profile('search');
$model -> unsetAttributes();// clear any default values
if (isset($_GET['Profile']))
$model -> attributes = $_GET['Profile'];
$this -> render('MyPage', array('model' => $model ));
My Model Relation:
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name the relations automatically generated below.
return array(
'user' => array(self::BELONGS_TO, 'user', 'user_id'),);
}
Model Rules:
array( 'xxx,yyy,user_name', 'safe', 'on'=>'search' ),
And model search function
if(!empty($this->user_id)){
$criteria->with='user';
$criteria->order = ::app()->request->getParam('sort');// 'username ASC'
}
$criteria -> compare('user.username', $this->user_id, true);
My
$this->widget('zii.widgets.grid.CGrid', array(
'id'=>'profile-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
array('name'=>'user_id',
'header'=>User::model()->getAttributeLabel('username'),
'value' =>'$data->getRelated(\'user\')->username',
'type'=>'raw',
'htmlOptions'=>array('style'=>'text-align: center'),),
---------------
During sorting,sorting works perfectly but sorting is done on the basis of user_id not by username. Anything that i am missing to do so. Please suggest.
Reference:Here (I also tried as by declaring a public variable as suggesting in the link but bot workingg.)
Edit: After Issue Fixed.
Thanks for this link too.
Well, the wiki page you found is really a good start...
Here is an alternative way for doing this :
In your Profile model :
// private username attribute, will be used on search
private $_username;
public function rules()
{
return array(
// .....
array('username', 'safe', 'on'=>'search'),
// .....
);
}
public function getUsername()
{
// return private attribute on search
if ($this->scenario=='search')
return $this->_username;
// else return username
if (isset($this->user_id)) && is_object($this->user))
return $this->user->username;
}
public function setUsername($value)
{
// set private attribute for search
$this->_username = $value;
}
public function search()
{
// .....
$criteria->with = 'user';
$criteria->compare('user.username', $this->username, true);
// .....
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'attributes'=>array(
'username'=>array('asc'=>'user.username', 'desc'=>'user.username DESC'),
'*',
),
),
));
}
And in your view you should simply try :
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'profile-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
// .....
'username',
// .....
),
);