<?php
/**
* simple class for LDAP authentification
*
Copyright (C) 2013 Petr Palas This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* inspired by http://samjlevy.com/2010/09/php-login-script-using-ldap-verify-group-membership/
*/ namespace LDAP; use Exception; class auth {
/**
* url or ip of ldap server
* @var type string
*/
protected $ldap_host;
/**
* active directory DN
* @var type string
*/
protected $ldap_dn;
/**
* target user group
* @var type string
*/
protected $ldap_user_group;
/**
* manager group (shud contain users with management access)
* @var type string
*/
protected $ldap_manager_group;
/**
* contains email domain like "@somedomain.com"
* @var type string
*/
protected $ldap_usr_dom; /**
* countains connection resource
* @var type resource
*/
protected $ldap; /**
* contains status text
* if exeption is thrown msg contains this string
* @var type string
*/
public $status;
/**
* contains result array if ldap_search is succesfull
* @var type array
*/
public $result;
/**
* contains auth state 0=unathrized 1=authorized
* @var type int
*/
public $auth=0;
/**
* contains access level 0=none or unathorized 1=user 2=managment acc
* @var type int
*/
public $access=0; /**
* contains username after user init
* @var type string
*/
public $user; /**
* contain user password after user init
* @var type string
*/
protected $password; /**
* Exeptions code constants
*/
const ERROR_WRONG_USER_GROUP=2;
const ERROR_CANT_AUTH=1;
const ERROR_CANT_SEARCH=3;
const ERROR_IMG_DECODE=4;
const ERROR_CANT_CONNECT=5; /**
* loads passed configuration in case of the ldap_usr_dom it makes sure that this strings begins with '@'
* @param type $ldap_host
* @param type $ldap_dn
* @param type $ldap_user_group
* @param type $ldap_manager_group
* @param type $ldap_usr_dom
*/
function __construct($ldap_host,$ldap_dn,$ldap_user_group,$ldap_manager_group,$ldap_usr_dom) {
$this->ldap_host=$ldap_host;
$this->ldap_dn=$ldap_dn;
$this->ldap_user_group=$ldap_user_group;
$this->ldap_manager_group=$ldap_manager_group;
$this->ldap_usr_dom= '@'.trim($ldap_usr_dom,'@');
} /**
* well destructor :P
* just in case there is opened connection to LDAP while destructing this class
*/
public function __destruct() {
@ldap_unbind($this->ldap);
} /**
* dumps result array for debug enclosed in pre tag
* Wont terminate script!
*/
public function dump_resut() {
echo '<pre>';
print_r($this->result,FALSE);
echo '</pre>';
} /**
* Inits connection to LDAP server throws exeption on failure
* @return boolean
* @throws Exception
*/
protected function init_connection(){
$this->ldap=ldap_connect($this->ldap_host,3268);
if($this->ldap){
$this->status='connected :)';
ldap_set_option($this->ldap, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($this->ldap, LDAP_OPT_REFERRALS,0);
}
else {
//TODO: PHP actualy dont check if there is LDAP present on the other end nor it will fail if target host is unreachable. So I need some work around that :(
$this->status='Cant connect to LDAP';
throw new Exception($this->status, self::ERROR_CANT_CONNECT);
}
return TRUE;
} public function userInit($user,$password) {
$this->user=$user;
$this->password=$password; return TRUE;
} /**
* Converts Binary string (like thumbnail from LDAP to base64 datastring for display
* @param type $file
* @param type $mime
* @return type base64 datastring
*/
protected function data_uri($file, $mime) {
$base64 = base64_encode($file);
return ('data:' . $mime . ';base64,' . $base64);
} /**
* Gets LDAP thumbnail img
* @param type $user
* @param type $password
* @param type $raw if TRUE method will return raw binary string instead of base64 encoded with mime
* @return type base64 datatring of the thumbnail
* @throws Exception
*/
public function getLDAPimg($user=null,$password=null,$raw=FALSE) {
$this->refreshCredentials($user, $password);
//since conection is one off we need to get it
$this->init_connection(); $bind = @ldap_bind($this->ldap, $user . $this->ldap_usr_dom, $password);//ldap_bind($this->ldap, $this->ldap_dn, $password); if($bind){
$filter = "(sAMAccountName=" . $user . ")";
$attr = array("thumbnailphoto");
$result = @ldap_search($this->ldap, $this->ldap_dn, $filter, $attr);
if($result==FALSE){
throw new Exception("Unable to search LDAP server. Reason: ". ldap_error($this->ldap), self::ERROR_CANT_SEARCH);
}
$entry= ldap_first_entry($this->ldap, $result); if ($entry) {
$info = @ldap_get_values_len($this->ldap, $entry, "thumbnailphoto");
if(!$info){
throw new Exception("Unable to decode thumbnail. Error: ". ldap_error($this->ldap), self::ERROR_IMG_DECODE);
}
//echo '<img src="'.$this->data_uri($info[0], 'image/png').'">';
} if(!$raw){
return $this->data_uri($info[0], 'image/png');
}
else{
return $info[0];
}
}
else {
// invalid name or password
$this->status='Cant authenticate for search on LDAP';
throw new Exception($this->status.' '. ldap_error($this->ldap), self::ERROR_CANT_AUTH);
}
ldap_unbind($this->ldap);
} /**
* Tries to authenticate suplied user with suplied pass
* @param type $user
* @param type $password
* @return boolean
* @throws Exception
*/
public function authenticate($user=null, $password=null) {
$this->refreshCredentials($user, $password);
//since conection is one off we need to get it
$this->init_connection(); // verify user and password
$bind = @ldap_bind($this->ldap, $user . $this->ldap_usr_dom, $password); if($bind) {
// valid
// check presence in groups
$filter = "(sAMAccountName=" . $user . ")";
$attr = array("memberof");
$result = @ldap_search($this->ldap, $this->ldap_dn, $filter, $attr);
if($result==FALSE){
throw new Exception("Unable to search LDAP server. Reason: ". ldap_error($this->ldap), self::ERROR_CANT_SEARCH);
}
$entries = ldap_get_entries($this->ldap, $result); //save result for future use
$this->result=$entries; $access = 0; // check groups
foreach($entries[0]['memberof'] as $grps) {
// is manager, break loop
if (strpos($grps, $this->ldap_manager_group)) { $access = 2; break; } // is user
if (strpos($grps, $this->ldap_user_group)) $access = 1;
} if ($access != 0) {
// establish result vars $this->status='Authenticated';
$this->access=$access;
$this->user= $user;
$this->auth=1;
return true;
} else {
// user has no rights
$this->access=$access;
$this->user= $user;
$this->auth=1;
$this->status='User exists but not part of the target group';
throw new Exception($this->status.' '. ldap_error($this->ldap), self::ERROR_WRONG_USER_GROUP);
} } else {
// invalid name or password
$this->status='Cant authenticate for search on LDAP';
throw new Exception($this->status.' '. ldap_error($this->ldap), self::ERROR_CANT_AUTH);
}
ldap_unbind($this->ldap);
} /**
* Saves new credentials if we got new or sets the old ones into referenced vars
* @param type $user Reference to var that shuld contain username or null
* @param type $password Reference to var that shuld contain password or null
*/
private function refreshCredentials(&$user,&$password) {
$newCredentials=TRUE;
//since we cant set those in param def
if($password===null){$password= $this->password;$newCredentials=FALSE;}
if($user===null){$user= $this->user;$newCredentials=FALSE;}
//store user pass and name for future use
if($newCredentials){$this->userInit($user, $password);}
} }

simple-LDAP-auth的更多相关文章

  1. opennebula extend(expending) auth module ldap

    LDAP Authentication addon permits users to have the same credentials as in LDAP, so effectively cent ...

  2. LDAP Authentication for openNebula3.2

    LDAP Authentication 3.2 The LDAP Authentication addon permits users to have the same credentials as ...

  3. 《Linux菜鸟入门2》Ldap

    ldap网络帐号1.ldap是什么ldap目录服务认证,和windows活动目录类似,就是记录数据的一种方式 2.ldap客户端所需软件yum install sssd krb-workstation ...

  4. ldap集成grafana

    grafana版本: 5.0.3 grafana通过k8s方式安装,所以需将配置文件挂载过去. cat grafana-configmap.yaml apiVersion: v1 kind: Conf ...

  5. LDAP落地实战(二):SVN集成OpenLDAP认证

    上一篇文章我们介绍了LDAP的部署以及管理维护,那么如何接入LDAP实现账号统一认证呢?这篇文章将带你完成svn的接入验证 subversion集成OpenLDAP认证 系统环境:debian8.4 ...

  6. Mantis集成 LDAP 认证

    mantis的用户认证函数Authentication中相关有 $g_login_method MD5 LDAP PLAIN CRYPT CRYPT_FULL_SALT BASIC_AUTH Some ...

  7. LDAP方式连接AD获取用户信息

    LDAP资料介绍可以参考:http://wenku.baidu.com/view/262742f9f705cc17552709f9.html ldap访问AD域的的错误一般会如下格式: Ldap lo ...

  8. python实现ldap接入

    需要提前安装python-ldap模块 python接入ldap其实分了几个步骤: 1.使用一个管理员账户登陆到ldap 2.使用一个字段值是唯一的字段,去搜索到要验证用户的DN值(ldap搜索到的单 ...

  9. JAVA中使用LDAP登录的三种方式

    搜索中关于java 登录ldap,大部分会采用  cn=xxx,ou=xxx,dc=xxx的方式,此处的cn是用户的Display Name,而不是account,而且如果ou有多层,比如我们的OU就 ...

  10. linux 利用LDAP身份集中认证

    碰巧所在的公司用到了ldap 集中身份认证,所有打算研究下这套架构,但是看遍了网络上的很多教程,要么不完整,要么就是照着根本弄不出来,十月一研究了三天,结合八方资源终于弄出来了,真是不容易,哎,特此记 ...

随机推荐

  1. PHP采集程序中的常用函数

  2. elastic search查询命令集合

    Technorati 标签: elastic search,query,commands 基本查询:最简单的查询方式 query:{"term":{"title" ...

  3. 分享一个Fluent风格的邮件发送封装类

    C#中用SmtpClient发邮件很简单,闲着无事,简单封装一下 IEmailFactory public interface IEmailFactory { IEmailFactory SetHos ...

  4. 边工作边刷题:70天一遍leetcode: day 87

    Implement strStr() 要点:rolling hash方法的速度比较慢. 小优化:不用hash%base,而用hash-=base*最高位是一样的. rolling hash错误点: b ...

  5. HDU 5025 Saving Tang Monk --BFS

    题意:给一个地图,孙悟空(K)救唐僧(T),地图中'S'表示蛇,第一次到这要杀死蛇(蛇最多5条),多花费一分钟,'1'~'m'表示m个钥匙(m<=9),孙悟空要依次拿到这m个钥匙,然后才能去救唐 ...

  6. bootstrap学习总结-css样式设计(二)

    首先,很感谢各位园友对我的支持,关于bootstrap的学习总结,我会持续更新,如果有写的不对的地方,麻烦各位给我指正出来哈.关于上篇文章,固定布局和流式布局很关键,如果还不太清楚的可以再看看我写的h ...

  7. MySQL数据库学习笔记(十)----JDBC事务处理、封装JDBC工具类

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  8. Java Executor并发框架(三)ThreadPoolExecutor 队列缓存策略

    前面两篇讲解了线程池中线程创建后的运行情况,其中有一系列的策略来保证线程正常运行.但是我们知道线程池是可以设置容量的,而且这容量的设置也是至关重要的,如果容量设置的太小,那么将会影响系统的运行效率,如 ...

  9. Corotational 模型代码

    今天看了Corotational模型的代码. 在Vega中,获得模型内力的方法是先构造一个ForceModel对象,再调用其对应方法. 对于Corotational模型,构造的流程为: 构造Corot ...

  10. vrrp两用

    早上想了想vrrp的使用,1,网关冗余 2,服务器热备 思想稍微有点不一样.主要在于监控口 服务器的话有心跳线,用户同步一些配置和迁移一些服务.达到热备的目的.:牵涉到四个优先级:建议这样排序: 主机 ...