CodeIgniter Validation in Library does not accept callback - php

my problem is the following: I am writing a login library.
This library has a function _validation() and this uses the validation library to validate the data.
With using normal validation methods it works just fine, but using a callback function just does not work. It is not called.
I call it like this.
$this->CI->form_validation->set_rules('user', 'Username', 'required|callback__check_user');
The functions name is _check_user and it uses the username _check_user($user).
The function itself works fine and I can also call it in the class ($this->_check_user('username')) with a working result.
I am guessing, there might be a problem because I am not workin in a controller so I have a CI instance $this->CI instead of just the original instance $this->
Does anyone have a clue how to fix this?
Thanks in advance.

Hey, I figured out a way that works for me. By just extending the Form_validation library in MY_Form_validation.php you can create custom validation methods. I think it is a clean way and it works perfectly fine. I build the below validation method to check for existing usernames and passwords. $value is something like table_name.fieldname.
I have not message set so that it will use the _exist messages from the lang files.
/**
* Exist
*
* checks if the entry exists in the database
* returns a boolean
*
* #access private
* #param string
* #param field
* #return boolean
*/
function _exist($str, $value)
{
list($table, $column) = explode('.', $value, 2);
$query = $this->CI->db->query("SELECT COUNT(*) AS count FROM $table WHERE $column = '$str'");
$row = $query->row();
return ($row->count > 0) ? TRUE : FALSE;
}
Thanks for your help though.

The form validation callback will only fire on a method inside the current controller.
Just do this in the controller you're using the callback:
function _check_user($user)
{
$this->load->model('login');
$result = $this->login->_check_user($user);
return $result;
}

Related

Return validator messages in custom Rule

A problem that we probably didn't know about when switching to PHP 8+:
Very often, in the rules we created earlier, we returned a message like this:
public function message(): array
{
return [$this->validator->errors()->messages()];
}
When using PHP 7.4 - this isn't a problem, but not for PHP 8+
Since looking "deeper" into how the laravel framework forms messages, we get an error in the replaceAttributePlaceholder method of the FormatsMessages class:
/**
* Replace the : attribute placeholder in the given message.
*
* #param string $message
* #param string $value
* #return string
*/
protected function replaceAttributePlaceholder($message, $value)
{
return str_replace(
[':attribute', ':ATTRIBUTE', ':Attribute'],
[$value, Str::upper($value), Str::ucfirst($value)],
$message
);
}
And indeed, if we open any editor and run the same code, but for two different versions, we'll get:
If you return the message like this:
public function message(): array
{
return $this->validator->errors()->messages();
}
We will avoid the error, but accordingly, the format of the message will be different - this doesn't suit me, and the format of the message should remain the same.
Does anyone have any ideas on how to save the format and fix the error?

Get current user information in Apigility Resource

I just started with Apigility and oAuth2, and I was wondering if it is possible to get the currently authenticated "loggedin" user when fetching information from a database.
I currently have the following code:
/**
* Fetch all or a subset of resources
*
* #param array $params
* #return mixed
*/
public function fetchAll($params = array())
{
var_dump($params);
// Using Zend\Db's SQL abstraction
$sql = new \Zend\Db\Sql\Sql($this->db);
//I would like to get the currently logged in user here... but how?
$select = $sql->select('projects')->where(array('userid' => 1));;
// This provides paginated results for the given Select instance
$paged = new \Zend\Paginator\Adapter\DbSelect($select, $this->db);
// which we then pass to our collection
return new ProjectsCollection($paged);
}
I did a lot of searching already but I have no clue how to access the user information or the access token, do I need to parse the request header for this?
I was also looking for it. I didn't found any documentation about that. But the answer is quite simple:
Resource classes inherits ZF\Rest\AbstractResourceListener which already has a method getIdentity.
/**
* Fetch all or a subset of resources
*
* #param array $params
* #return mixed
*/
public function fetchAll($params = array())
{
// if user isn't authenticated return nothing
if(!$this->getIdentity() instanceof ZF\MvcAuth\Identity\AuthenticatedIdentity) {
return [];
}
// this array returyour query here using $userIdns the authentication info
// in this case we need the 'user_id'
$identityArray= $this->getIdentity()->getAuthenticationIdentity();
// note, by default user_id is the email (username column in oauth_users table)
$userId = $identityArray['user_id'];
// fetch all using $userId
}
You can also use getIdentity in RPC services.
I'm using the latest version of apigility.
I found in the end a shorter way to get the userid, just adding it as answer for the sake of completeness.
You can get the identity object like #ViníciusFagundes mentioned $this->getIdentity() and this identity object has the function getRoleId() which returns the identifier of the user.
$user_id = $this->getIdentity()->getRoleId();

Restler+OAuth2 - Identifying the user correctly

I'm working with Restler and the OAuth2 module written by Brent Shaffer. What I want to do is determine the user from the token they send, inside my app classes, not just the OAuth2Server classes.
There are two methods that I can see of doing this. Hopefully this explains what I am trying to do.
Method 1: I don't particularly like this method, but it works.
POST /v1/token
Returns my token including the user_id, for example
{
"access_token":"282090609b3407d981c2bea633a39739595ba426",
"expires_in":3600,
"token_type":"Bearer",
"scope":"basic",
"refresh_token":"b60a4e5f759168df857342380f3550bc120b6f9d",
"user_id": 5
}
Now that the client knows the user_id, it is sent with my request:
GET /v1/dashboard?id=5
My __isAllowed method takes care of checking that the user hasn't altered the id, requesting info that isn't theirs.
public function __isAllowed() {
$token = static::$server->getAccessTokenData(Request::createFromGlobals());
return (($token['user_id'] > 0) && ($token['user_id'] === $_GET['id']) && ($token['group_id'] == self::$group_id));
}
Dashboard class looks like this:
/*
* #version 1
* #access protected
*/
class Dashboard {
/**
* #param int $id Customer ID {#from query}
* #return type
*/
public function index($id) {
$s = Dao\ViewCustomerDaoObject::findId($id);
return array_merge($s->toJSON(), $widgets);
}
}
This is how I would prefer to be calling the API:
GET /v1/dashboard
When I request the above, join the oauth2_token table to my dashboard table. I think this might be a bit of a hack and I don't want this to cause problems down the road.
The info is already available in the OAuth2Server instance, as the OAuth2Server class does determine if the correct token is used and what their user_id is.
Can someone please guide me in the right direction for handling this situation, particularly with Restler?
I actually figured this out myself.
In the OAuth2Server->__isAllowed method, you must set the UserId in the static User class.
public function __isAllowed() {
$token = static::$server->getAccessTokenData(Request::createFromGlobals());
// If the user_id is valid, set static user class.
// *** This is not production code, add more checks here if you use this!
if ($token['user_id'] > 0) {
\Luracast\Restler\User::init();
\Luracast\Restler\User::setUniqueIdentifier($token['user_id']);
return true;
}
return false;
}
Now you can get the currently authenticated user in your class by calling:
\Luracast\Restler\User::getUniqueIdentifier(true)

Laravel 4 - Using Eloquent Models in a custom library class

I made a library class that I am using for some common functions not provided by Laravel. It's been loaded into /config/app.php under the 'aliases' array, so that shouldn't be the problem.
When I call a method from my class ("InfoParse"), my conroller returns a blank page. I think this has to do with the fact that I'm calling a method from the library which uses Eloquent to interface with the database. I tried adding
use Illuminate\Database\Eloquent\Model;
to the top of the file, but that didn't help either.
Is there a specific way I should be setting up my class file so I can use either the DB:: class or Eloquent class?
Below is the function in question:
/**
* Check to see if this student is already recorded in our student table.
* If not, add the entry, then return true.
* #param int $cwid
* #return boolean
*/
public static function checkStudentTableRecords($cwid)
{
if(Student::where('cwid', '=', $cwid)->count() != 0)
{
return TRUE;
}
else
{ ##insert the student into our student table
$studentInfo = self::queryInfoFromCWID($cwid);
$studentEntry = new Student;
$studentEntry->cwid = $cwid;
$studentEntry->fName = $studentInfo['fName'];
$studentEntry->lName = $studentInfo['lName'];
$studentEntry->email = $studentInfo['email'];
$studentEntry->save();
return TRUE;
}
}
(note: the self::queryInfoFromCWID() function is calling a function defined earlier in the class)
After some investigation, it turns out I need to format my Eloquent Model calls like this:
if(\Student::where('cwid', '=', $cwid)->count() != 0)
...
$studentEntry = new \Student;
The backslash is necessary to avoid namespace collision within the Laravel4 application.

fetch php method comments

I want to fetch a method's comments,take below method for example:
/**
* Returns the regex to extract all inputs from a file.
* #param string The class name to search for.
* #return string The regex.
*/
public function method($param)
{
//...
}
the result should be
Returns the regex to extract all inputs from a file.
#param string The class name to search for.
#return string The regex.
the way I find is use a function like file_get_content to get file content -> filter the method I want -> fetch the comment use regexp
it seems a bit complicated , is there any convenient way to archive this?
actually you can get a method's doc comments with getDocComment
$ref=new ReflectionMethod('className', 'methodName');
echo $ref->getDocComment();
If you want to use the comment in PHP for something check out getDocComment in php's reflection api
PHP Doc. Like Java Doc.
For a method dump I use this little function I composed.
It fetches all methods from provided class that are public(and thus of use to you).
I personally use a dump() method to nicely format the outputted array of method names and descriptions, but that's not needed if you wish to use it for something else :-)
function getDocumentation($inspectclass) {
/** Get a list of all methods */
$methods = get_class_methods($inspectclass);
/** Get the class name */
$class =get_class($inspectclass);
$arr = [];
foreach($methods as $method) {
$ref=new ReflectionMethod( $class, $method);
/** No use getting private methods */
if($ref->isPublic()) {
$arr[$method] = $ref->getDocComment();
}
}
/** dump is a formatting function I use, feel free to use your own */
return dump($arr);
}
echo getDocumentation($this);

Categories