not getting user id from from Auth::instance->get_user()-id in Kohana - kohana-3

I am using auth module of kohana. I did register and login and its working fine. But when i do Auth::instance()->get_user()->id i get NULL
While login i do it with Auth::instance()->login($validator['email'], $validator['password']) and then redirect user to home page.
But when in one of the controller i do Auth::instance()->get_user()->id i get NULL
What would be the cause. Is that i have to first set something???

Try Auth::instance()->get_user()->pk().
pk() is for primary key.
Works in KO3.

My Mistake
In the _login function of modules/auth/classes/kohana/auth/orm.php
In that i was doing the following
$user = ORM::factory('user');
$user->where('email', ' = ', $email)
->and_where('password', ' = ', $password)
->find();
// TODO remember to be done
if ($user !== null) {
$this->complete_login($user);
return true;
} else {
return false;
}
In above i was checking $user is null or not but if the email and password not match the user instance will be created with NULL values for all the columns.
So now i am checking $user->id !== NULL and it is working fine.

Try this:
if ($user->loaded()) {
$this->complete_login($user);
return true;
} else {
return false;
}
See ORM::__call() if you want to know what happends (since ORM::loaded() does not exist)

Related

Unban command JDA 4.1.1_101, can't make it work and I don't know why

i'm coding a Discord bot with JDA 4.1.1_101. I created the "ban" command, but i can't make the unban command work. I can't really understand why... Thank you for your help.
if (args[0].equalsIgnoreCase(Main.prefix + "unban")) {
if(event.getGuild().getSelfMember().hasPermission(Permission.BAN_MEMBERS)) {
if (args.length > 0 && args.length < 3) {
try {
event.getMessage().delete().queue();
User member = event.getMessage().getMentionedMembers().get(0).getUser();
String id = member.getId();
event.getGuild().unban(id).queue();
EmbedBuilder ban = new EmbedBuilder();
ban.setColor(Color.GREEN);
ban.setTitle("UnBan");
ban.setDescription("UnBan Report");
ban.addField("Staffer: ", event.getMessage().getAuthor().getName(), true);
ban.addField("Unban: ", member.getName(), true);
logs.sendMessage(ban.build()).queue();
} catch (IndexOutOfBoundsException exx) {
EmbedBuilder error = new EmbedBuilder();
error.setColor(0xff3923);
error.setTitle("Error: User");
error.setDescription("Invalid user.");
event.getChannel().sendMessage(error.build()).queue(message -> {
message.delete().queueAfter(5, TimeUnit.SECONDS);
});
}
} else {
EmbedBuilder error = new EmbedBuilder();
error.setColor(0xff3923);
error.setTitle("Error: Wrong usage.");
error.setDescription("Use: .unban [#user].");
event.getChannel().sendMessage(error.build()).queue(message -> {
message.delete().queueAfter(5, TimeUnit.SECONDS);
});
}
}
}
The problem is, that you are trying to retrieve the user from the mention in the message.
Since the user isn't part of the guild anymore, it seems like this doesn't work.
In order to work around this issue, you have to retrieve the ID manually.
A mention is always in the format <#userid> or <!#userid>.
To get the ID you could just split the message and replace the unnecessary parts, e.g. String id = event.getMessage().getContentRaw().split("<")[1].split(">")[0].replace("!", "").replace("#", "");
I'm sure there are better and smoother ways for doing this. ;)
A better way of retrieving the ID would be using a regex such as <#!?(\d+)> as mentioned by Minn.
In order to get the name of the user, you just need the ID via event.getJDA().getUserById(id).getName().
It's important to mention that you can't properly mention a user who isn't on the server (which is the case when they are banned).
(Addition: I tried using .getMentionedUsers() with the same result as OP.)

Best way to delete a user related model record

This is how i am deleting a record,can you please suggest me what is the best approach to delete a record.
public function delete_post($id) {
//Check if id is numeric and exists
if( (is_numeric($id)) && (!empty($id)) )
{
$post = Post::find($id);
// check if this id belongs to user (User has author)
if(Auth::id() == $post->user_id){
Post::with('likes')->whereId($id)->delete();
}else{
Session::flash('error', 'You can't delete this.
}
}else{
Session::flash('error', 'Problem with your input');
}
}
You should put your delete into a transactions
More in here:
Laravel Transactions!

Check if a given user is in the security group of a given path

I have a simple job which I don't know how to accomplish, and as deeper I search it I got lost deeper.
I need to write a method which returns the FileSystemAccessRule of a given user(I am given his samAccountName, objectGUID) over a given folder path.
I've done adding or removing FileSystemAccessRule's to a path before like this:
var fSecurity = Directory.GetAccessControl(physicalPath);
fSecurity.AddAccessRule(new FileSystemAccessRule(samAccountName, FileSystemRights.FullControl, AccessControlType.Allow));
fSecurity.RemoveAccessRule(new FileSystemAccessRule(samAccountName, FileSystemRights.FullControl, AccessControlType.Allow));
Directory.SetAccessControl(physicalPath, fSecurity);
Checking if the given user has some certain the access rights over a path a similiar job? Or should go to another way? Something like DirectoryEntry or LDAP or Active Directory or so?
What I want is a method which maybe looks like this:
FileSystemAccessRule[] GetAccessRulesOfTheUserOverPath(string samAccountName, string folderPath)
{
/// how?
}
Thanks to some answers on SO I've come up with an answer. Although it is not the exact answer to my question, it fulfills my need. On this question's answers I found the solution. This solution tells me if the given FileSystemRights is bound to the current windows user on acl(AuthorizationRuleCollection) of given folder.
Almost all answers in the question I've referred to are giving the result, In my opinion the most accurate one is #Olivier Jacot-Descombes's answer since it calculates the allow rules, deny rules, and inherited rules precedences over each other.
So what I did is this:
WindowsIdentity _currentUser;
WindowsPrincipal _currentPrincipal;
using ( new Impersonator(userName, passwordOfTheUser) )
{
_currentUser = WindowsIdentity.GetCurrent();
_currentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
}
if ( !Directory.Exists(path) ) throw new Exception("Directory does not exist");
var di = new DirectoryInfo(path);
var directoryACLs = di.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
///rw_accessRules list consists of the rules for ReadWrite permissons.
bool auth_RW = rw_accessRules.All(aR => HasFileOrDirectoryAccess(_currentUser, _currentPrincipal, aR, directoryACLs));
And here is the ``HasFileOrDirectoryAccess` method:
bool HasFileOrDirectoryAccess ( WindowsIdentity _currentUser, WindowsPrincipal _currentPrincipal, FileSystemRights right, AuthorizationRuleCollection acl )
{
bool allow = false;
bool inheritedAllow = false;
bool inheritedDeny = false;
foreach ( FileSystemAccessRule currentRule in acl )
{
// If the current rule applies to the current user.
if ( _currentUser.User.Equals(currentRule.IdentityReference) || _currentPrincipal.IsInRole((SecurityIdentifier)currentRule.IdentityReference) )
{
if ( currentRule.AccessControlType.Equals(AccessControlType.Deny) )
{
if ( ( currentRule.FileSystemRights & right ) == right )
{
if ( currentRule.IsInherited )
{
inheritedDeny = true;
}
else
{ // Non inherited "deny" takes overall precedence.
return false;
}
}
}
else if ( currentRule.AccessControlType.Equals(AccessControlType.Allow) )
{
if ( ( currentRule.FileSystemRights & right ) == right )
{
if ( currentRule.IsInherited )
{
inheritedAllow = true;
}
else
{
allow = true;
}
}
}
}
}
if ( allow )
{ // Non inherited "allow" takes precedence over inherited rules.
return true;
}
return inheritedAllow && !inheritedDeny;
}
I first impersonate for the given user, get his principal and identity, then check if he has the authority of the given rule set.
This one works for my case, but you'll notice that we need password of the user that we want check the permissions of. If there is any way to do this without the password, it will be great.

Kohana auth model

I'm new to kohana 3.2 and i couldnt find any answer regrading the auth module.
this is my code and forsome reason ever since i changed the user model to extend model_auth_user
the validation isnt being done prooperly. The password field can be inserted empty and no excpetion will be caught and same if the password_confirm and password fields are different:
public function action_new()
{
if ($_POST){
try
{
$user = ORM::factory('user')
->values(array(
'username' => $_POST['username'],
'email' => $_POST['email'],
'password' => $_POST['password'],
'password_confirm' => $_POST['password_confirm']));
$user->save();
$user->add('roles', ORM::factory('role', array('name' => 'login')));
$this->request->redirect('user/index');
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors();
}
}
$view = View::factory('user/new')
->bind('errors',$errors); //pass the info to the view
$this->response->body($view); //show the view
}
thanks
You can override run_filter() method to force Kohana ignore password filtering in case of empty value. For example, put this code to your User_Model:
protected function run_filter($field, $value)
{
if ($field === "password" AND $value === "")
return "";
parent::run_filter($field, $value);
}
Try code sample from Model_Auth_User::create_user();
$user->save(Model_User::get_password_validation($_POST)->rule('password', 'not_empty'));
This validation execute before filters(hashing password). After hashing - blank password becomes not empty string.

login to modx from external/other server revolution 2.2.5

I am pissed off with this problem from 2 days.
I am using MODx Revolution 2.2.5 (traditional) and want to login to modx from external server just to fetch some user details.
1) I know that runprocessor method works only if i am logged in to manager (unfortunately, that's the only way i know to login user in) So i tried IFRAME method to avoid (cross scripting) it worked perfectly but i am not able to read the data from IFRAME using javascript because of same issue, cross domain access policy.
When i try to post data using some other method like CURL, Ajax using
header("Access-Control-Allow-Origin: *");
I am able to login (I see $response->response['success'] == 1) but cant access any data and it says
Fatal error: Call to a member function get() on a non-object
Below is the snippet code i am using
if(isset($_POST) && count($_POST)){
$c = array(
'username' => $_POST['username'],
'password' => $_POST['password']
);
$response = $modx->runProcessor('security/login',$c);
if($response->response['success'] == 1){
$user['id'] = $modx->user->get('id');
$profile = $modx->user->getOne('Profile');
$user['fullname'] = $profile->get('fullname');
$user['email'] = $profile->get('email');
echo json_encode($user);
}else{
echo json_encode($response->response);
}
}
2) I can use login snippet but it doesnt return output what i expect. We have ready site and we are already using login plugin so i cant even modify login plugin to respond with expected data
How can i login to modx using api or any other method ??
You are really attacking this problem completely wrong in my opinion. If you want to access a server/webpage from another, you don't iFrame and do it the way you are. That is hacking, and this hole will most likely be fixed in a future version.
What you SHOULD do is connecting to the database and just gather the information from the user-table.
No hacking, no "tricks", won't stop working and much safer.
Well, I sorted out this today, Below is the complete come that worked perfectly.
Pay attention to
header("Access-Control-Allow-Origin: http://www.xyz.com");
Using above CORS specification you can allow 2 servers to communication.
header("Access-Control-Allow-Origin: http://www.xyz.com");
if(isset($_POST['username']) && isset($_POST['password'])){
// get username and password from POST array
$username = $modx->sanitizeString($_POST['username']);
$password = $modx->sanitizeString($_POST['password']);
if(trim($username) != "" and trim($password) != ""){
// Load lexicons to show proper error messages
if (!isset($modx->lexicon) || !is_object($modx->lexicon)) {
$modx->getService('lexicon','modLexicon');
}
$modx->lexicon->load('login');
$loginContext= isset ($scriptProperties['login_context']) ? $scriptProperties['login_context'] :
$modx->context->get('key');
$addContexts= isset ($scriptProperties['add_contexts']) && !empty($scriptProperties['add_contexts']) ? explode(',', $scriptProperties['add_contexts']) : array();
$mgrEvents = ($loginContext == 'mgr');
$givenPassword = $password;
/** #var $user modUser */
$user= $modx->getObjectGraph('modUser', '{"Profile":{},"UserSettings":{}}', array ('modUser.username' => $username));
if (!$user) {
$ru = $modx->invokeEvent("OnUserNotFound", array(
'user' => &$user,
'username' => $username,
'password' => $password,
'attributes' => array(
'loginContext' => $loginContext,
)
));
if (!empty($ru)) {
foreach ($ru as $obj) {
if (is_object($obj) && $obj instanceof modUser) {
$user = $obj;
break;
}
}
}
if (!is_object($user) || !($user instanceof modUser)) {
//echo "cant locate account";
echo $modx->toJSON($modx->error->failure($modx->lexicon('login_cannot_locate_account')));
exit;
}
}
if (!$user->get('active')) {
//echo "inactivated accout";
echo $modx->toJSON($modx->error->failure($modx->lexicon('login_user_inactive')));
exit;
}
if (!$user->passwordMatches($givenPassword)) {
if (!array_key_exists('login_failed', $_SESSION)) {
$_SESSION['login_failed'] = 0;
}
if ($_SESSION['login_failed'] == 0) {
$flc = ((integer) $user->Profile->get('failedlogincount')) + 1;
$user->Profile->set('failedlogincount', $flc);
$user->Profile->save();
$_SESSION['login_failed']++;
} else {
$_SESSION['login_failed'] = 0;
}
//echo "wrong username pass";
echo $modx->toJSON($modx->error->failure($modx->lexicon('login_username_password_incorrect')));
exit;
}
$fullname = $user->Profile->get('fullname');
echo '{"success":true,"message":"Welcome '.$fullname.'!"}';
}else{
echo '{"success":false,"message":"Please enter username and password"}';
}
}

Resources