Update files to PSR-2 standards

This commit is contained in:
Brennan Murphy 2018-07-02 17:27:43 +00:00
parent d640cc1eee
commit 37aa8b05f8
3 changed files with 302 additions and 298 deletions

View File

@ -97,14 +97,14 @@ class LoginController extends Controller
auth()->login($user); auth()->login($user);
} }
// ldap groups refresh // ldap groups refresh
if (config('services.ldap.user_to_groups') !== false && $request->filled('username')) { if (config('services.ldap.user_to_groups') !== false && $request->filled('username')) {
$ldapRepo = new LdapRepo($this->userRepo); $ldapRepo = new LdapRepo($this->userRepo);
$ldapRepo->syncGroups($user,$request->input('username')); $ldapRepo->syncGroups($user, $request->input('username'));
} }
$path = session()->pull('url.intended', '/'); $path = session()->pull('url.intended', '/');
$path = baseUrl($path, true); $path = baseUrl($path, true);
return redirect($path); return redirect($path);
} }

View File

@ -8,77 +8,77 @@ use BookStack\Repos\UserRepo;
class LdapRepo class LdapRepo
{ {
protected $ldap = null; protected $ldap = null;
protected $ldapService = null; protected $ldapService = null;
protected $config; protected $config;
/** /**
* LdapRepo constructor. * LdapRepo constructor.
* @param \BookStack\Repos\UserRepo $userRepo * @param \BookStack\Repos\UserRepo $userRepo
*/ */
public function __construct(UserRepo $userRepo) public function __construct(UserRepo $userRepo)
{ {
$this->config = config('services.ldap'); $this->config = config('services.ldap');
if (config('auth.method') !== 'ldap') { if (config('auth.method') !== 'ldap') {
return false; return false;
} }
$this->ldapService = new LdapService(new Ldap); $this->ldapService = new LdapService(new Ldap);
$this->userRepo = $userRepo; $this->userRepo = $userRepo;
} }
/** /**
* If there is no ldap connection, all methods calls to this library will return null * If there is no ldap connection, all methods calls to this library will return null
*/ */
public function __call($method, $arguments) public function __call($method, $arguments)
{ {
if ($this->ldap === null) { if ($this->ldap === null) {
return null; return null;
} }
return call_user_func_array(array($this,$method),$arguments); return call_user_func_array(array($this,$method), $arguments);
} }
/** /**
* Sync the LDAP groups to the user roles for the current user * Sync the LDAP groups to the user roles for the current user
* @param \BookStack\User $user * @param \BookStack\User $user
* @param string $userName * @param string $userName
* @throws \BookStack\Exceptions\NotFoundException * @throws \BookStack\Exceptions\NotFoundException
*/ */
public function syncGroups($user,$userName) public function syncGroups($user, $userName)
{ {
$userLdapGroups = $this->ldapService->getUserGroups($userName); $userLdapGroups = $this->ldapService->getUserGroups($userName);
$userLdapGroups = $this->groupNameFilter($userLdapGroups); $userLdapGroups = $this->groupNameFilter($userLdapGroups);
// get the ids for the roles from the names // get the ids for the roles from the names
$ldapGroupsAsRoles = Role::whereIn('name',$userLdapGroups)->pluck('id'); $ldapGroupsAsRoles = Role::whereIn('name', $userLdapGroups)->pluck('id');
// sync groups // sync groups
if ($this->config['remove_from_groups']) { if ($this->config['remove_from_groups']) {
$user->roles()->sync($ldapGroupsAsRoles); $user->roles()->sync($ldapGroupsAsRoles);
$this->userRepo->attachDefaultRole($user); $this->userRepo->attachDefaultRole($user);
} else { } else {
$user->roles()->syncWithoutDetaching($ldapGroupsAsRoles); $user->roles()->syncWithoutDetaching($ldapGroupsAsRoles);
} }
// make the user an admin? // make the user an admin?
if (in_array($this->config['admin'],$userLdapGroups)) { if (in_array($this->config['admin'], $userLdapGroups)) {
$this->userRepo->attachSystemRole($user,'admin'); $this->userRepo->attachSystemRole($user, 'admin');
} }
} }
/** /**
* Filter to convert the groups from ldap to the format of the roles name on BookStack * Filter to convert the groups from ldap to the format of the roles name on BookStack
* Spaces replaced with -, all lowercase letters * Spaces replaced with -, all lowercase letters
* @param array $groups * @param array $groups
* @return array * @return array
*/ */
private function groupNameFilter($groups) private function groupNameFilter($groups)
{ {
$return = []; $return = [];
foreach ($groups as $groupName) { foreach ($groups as $groupName) {
$return[] = str_replace(' ', '-', strtolower($groupName)); $return[] = str_replace(' ', '-', strtolower($groupName));
} }
return $return; return $return;
} }
} }

View File

@ -11,263 +11,267 @@ use Illuminate\Contracts\Auth\Authenticatable;
class LdapService class LdapService
{ {
protected $ldap; protected $ldap;
protected $ldapConnection; protected $ldapConnection;
protected $config; protected $config;
/** /**
* LdapService constructor. * LdapService constructor.
* @param Ldap $ldap * @param Ldap $ldap
*/ */
public function __construct(Ldap $ldap) public function __construct(Ldap $ldap)
{ {
$this->ldap = $ldap; $this->ldap = $ldap;
$this->config = config('services.ldap'); $this->config = config('services.ldap');
} }
/** /**
* Search for attributes for a specific user on the ldap * Search for attributes for a specific user on the ldap
* @param string $userName * @param string $userName
* @param array $attributes * @param array $attributes
* @return null|array * @return null|array
* @throws LdapException * @throws LdapException
*/ */
private function getUserWithAttributes($userName,$attributes) private function getUserWithAttributes($userName, $attributes)
{ {
$ldapConnection = $this->getConnection(); $ldapConnection = $this->getConnection();
$this->bindSystemUser($ldapConnection); $this->bindSystemUser($ldapConnection);
// Find user // Find user
$userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]); $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
$baseDn = $this->config['base_dn']; $baseDn = $this->config['base_dn'];
$followReferrals = $this->config['follow_referrals'] ? 1 : 0; $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
$this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals); $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
$users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes); $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
if ($users['count'] === 0) { if ($users['count'] === 0) {
return null; return null;
} }
return $users[0]; return $users[0];
} }
/** /**
* Get the details of a user from LDAP using the given username. * Get the details of a user from LDAP using the given username.
* User found via configurable user filter. * User found via configurable user filter.
* @param $userName * @param $userName
* @return array|null * @return array|null
* @throws LdapException * @throws LdapException
*/ */
public function getUserDetails($userName) public function getUserDetails($userName)
{ {
$emailAttr = $this->config['email_attribute']; $emailAttr = $this->config['email_attribute'];
$user = $this->getUserWithAttributes($userName, ['cn', 'uid', 'dn', $emailAttr]); $user = $this->getUserWithAttributes($userName, ['cn', 'uid', 'dn', $emailAttr]);
if ($user === null) { if ($user === null) {
return null; return null;
} }
return [ return [
'uid' => (isset($user['uid'])) ? $user['uid'][0] : $user['dn'], 'uid' => (isset($user['uid'])) ? $user['uid'][0] : $user['dn'],
'name' => $user['cn'][0], 'name' => $user['cn'][0],
'dn' => $user['dn'], 'dn' => $user['dn'],
'email' => (isset($user[$emailAttr])) ? (is_array($user[$emailAttr]) ? $user[$emailAttr][0] : $user[$emailAttr]) : null 'email' => (isset($user[$emailAttr])) ? (is_array($user[$emailAttr]) ? $user[$emailAttr][0] : $user[$emailAttr]) : null
]; ];
} }
/** /**
* @param Authenticatable $user * @param Authenticatable $user
* @param string $username * @param string $username
* @param string $password * @param string $password
* @return bool * @return bool
* @throws LdapException * @throws LdapException
*/ */
public function validateUserCredentials(Authenticatable $user, $username, $password) public function validateUserCredentials(Authenticatable $user, $username, $password)
{ {
$ldapUser = $this->getUserDetails($username); $ldapUser = $this->getUserDetails($username);
if ($ldapUser === null) { if ($ldapUser === null) {
return false; return false;
} }
if ($ldapUser['uid'] !== $user->external_auth_id) { if ($ldapUser['uid'] !== $user->external_auth_id) {
return false; return false;
} }
$ldapConnection = $this->getConnection(); $ldapConnection = $this->getConnection();
try { try {
$ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password); $ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password);
} catch (\ErrorException $e) { } catch (\ErrorException $e) {
$ldapBind = false; $ldapBind = false;
} }
return $ldapBind; return $ldapBind;
} }
/** /**
* Bind the system user to the LDAP connection using the given credentials * Bind the system user to the LDAP connection using the given credentials
* otherwise anonymous access is attempted. * otherwise anonymous access is attempted.
* @param $connection * @param $connection
* @throws LdapException * @throws LdapException
*/ */
protected function bindSystemUser($connection) protected function bindSystemUser($connection)
{ {
$ldapDn = $this->config['dn']; $ldapDn = $this->config['dn'];
$ldapPass = $this->config['pass']; $ldapPass = $this->config['pass'];
$isAnonymous = ($ldapDn === false || $ldapPass === false); $isAnonymous = ($ldapDn === false || $ldapPass === false);
if ($isAnonymous) { if ($isAnonymous) {
$ldapBind = $this->ldap->bind($connection); $ldapBind = $this->ldap->bind($connection);
} else { } else {
$ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass); $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
} }
if (!$ldapBind) { if (!$ldapBind) {
throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed'))); throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
} }
} }
/** /**
* Get the connection to the LDAP server. * Get the connection to the LDAP server.
* Creates a new connection if one does not exist. * Creates a new connection if one does not exist.
* @return resource * @return resource
* @throws LdapException * @throws LdapException
*/ */
protected function getConnection() protected function getConnection()
{ {
if ($this->ldapConnection !== null) { if ($this->ldapConnection !== null) {
return $this->ldapConnection; return $this->ldapConnection;
} }
// Check LDAP extension in installed // Check LDAP extension in installed
if (!function_exists('ldap_connect') && config('app.env') !== 'testing') { if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
throw new LdapException(trans('errors.ldap_extension_not_installed')); throw new LdapException(trans('errors.ldap_extension_not_installed'));
} }
// Get port from server string and protocol if specified. // Get port from server string and protocol if specified.
$ldapServer = explode(':', $this->config['server']); $ldapServer = explode(':', $this->config['server']);
$hasProtocol = preg_match('/^ldaps{0,1}\:\/\//', $this->config['server']) === 1; $hasProtocol = preg_match('/^ldaps{0,1}\:\/\//', $this->config['server']) === 1;
if (!$hasProtocol) { if (!$hasProtocol) {
array_unshift($ldapServer, ''); array_unshift($ldapServer, '');
} }
$hostName = $ldapServer[0] . ($hasProtocol?':':'') . $ldapServer[1]; $hostName = $ldapServer[0] . ($hasProtocol?':':'') . $ldapServer[1];
$defaultPort = $ldapServer[0] === 'ldaps' ? 636 : 389; $defaultPort = $ldapServer[0] === 'ldaps' ? 636 : 389;
$ldapConnection = $this->ldap->connect($hostName, count($ldapServer) > 2 ? intval($ldapServer[2]) : $defaultPort); $ldapConnection = $this->ldap->connect($hostName, count($ldapServer) > 2 ? intval($ldapServer[2]) : $defaultPort);
if ($ldapConnection === false) { if ($ldapConnection === false) {
throw new LdapException(trans('errors.ldap_cannot_connect')); throw new LdapException(trans('errors.ldap_cannot_connect'));
} }
// Set any required options // Set any required options
if ($this->config['version']) { if ($this->config['version']) {
$this->ldap->setVersion($ldapConnection, $this->config['version']); $this->ldap->setVersion($ldapConnection, $this->config['version']);
} }
$this->ldapConnection = $ldapConnection; $this->ldapConnection = $ldapConnection;
return $this->ldapConnection; return $this->ldapConnection;
} }
/** /**
* Build a filter string by injecting common variables. * Build a filter string by injecting common variables.
* @param string $filterString * @param string $filterString
* @param array $attrs * @param array $attrs
* @return string * @return string
*/ */
protected function buildFilter($filterString, array $attrs) protected function buildFilter($filterString, array $attrs)
{ {
$newAttrs = []; $newAttrs = [];
foreach ($attrs as $key => $attrText) { foreach ($attrs as $key => $attrText) {
$newKey = '${' . $key . '}'; $newKey = '${' . $key . '}';
$newAttrs[$newKey] = $attrText; $newAttrs[$newKey] = $attrText;
} }
return strtr($filterString, $newAttrs); return strtr($filterString, $newAttrs);
} }
/** /**
* Get the groups a user is a part of on ldap * Get the groups a user is a part of on ldap
* @param string $userName * @param string $userName
* @return array|null * @return array|null
*/ */
public function getUserGroups($userName) public function getUserGroups($userName)
{ {
$groupsAttr = $this->config['group_attribute']; $groupsAttr = $this->config['group_attribute'];
$user = $this->getUserWithAttributes($userName, [$groupsAttr]); $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
if ($user === null) { if ($user === null) {
return null; return null;
} }
$userGroups = $this->groupFilter($user); $userGroups = $this->groupFilter($user);
$userGroups = $this->getGroupsRecursive($userGroups,[]); $userGroups = $this->getGroupsRecursive($userGroups, []);
return $userGroups; return $userGroups;
} }
/** /**
* Get the parent groups of an array of groups * Get the parent groups of an array of groups
* @param array $groupsArray * @param array $groupsArray
* @param array $checked * @param array $checked
* @return array * @return array
*/ */
private function getGroupsRecursive($groupsArray,$checked) { private function getGroupsRecursive($groupsArray, $checked)
$groups_to_add = []; {
foreach ($groupsArray as $groupName) { $groups_to_add = [];
if (in_array($groupName,$checked)) continue; foreach ($groupsArray as $groupName) {
if (in_array($groupName, $checked)) {
continue;
}
$groupsToAdd = $this->getGroupGroups($groupName); $groupsToAdd = $this->getGroupGroups($groupName);
$groups_to_add = array_merge($groups_to_add,$groupsToAdd); $groups_to_add = array_merge($groups_to_add, $groupsToAdd);
$checked[] = $groupName; $checked[] = $groupName;
} }
$groupsArray = array_unique(array_merge($groupsArray,$groups_to_add), SORT_REGULAR); $groupsArray = array_unique(array_merge($groupsArray, $groups_to_add), SORT_REGULAR);
if (!empty($groups_to_add)) { if (!empty($groups_to_add)) {
return $this->getGroupsRecursive($groupsArray,$checked); return $this->getGroupsRecursive($groupsArray, $checked);
} else { } else {
return $groupsArray; return $groupsArray;
} }
} }
/** /**
* Get the parent groups of a single group * Get the parent groups of a single group
* @param string $groupName * @param string $groupName
* @return array * @return array
*/ */
private function getGroupGroups($groupName) private function getGroupGroups($groupName)
{ {
$ldapConnection = $this->getConnection(); $ldapConnection = $this->getConnection();
$this->bindSystemUser($ldapConnection); $this->bindSystemUser($ldapConnection);
$followReferrals = $this->config['follow_referrals'] ? 1 : 0; $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
$this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals); $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
$baseDn = $this->config['base_dn']; $baseDn = $this->config['base_dn'];
$groupsAttr = strtolower($this->config['group_attribute']); $groupsAttr = strtolower($this->config['group_attribute']);
$groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, 'CN='.$groupName, [$groupsAttr]); $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, 'CN='.$groupName, [$groupsAttr]);
if ($groups['count'] === 0) { if ($groups['count'] === 0) {
return []; return [];
} }
$groupGroups = $this->groupFilter($groups[0]); $groupGroups = $this->groupFilter($groups[0]);
return $groupGroups; return $groupGroups;
} }
/**
* Filter out LDAP CN and DN language in a ldap search return
* Gets the base CN (common name) of the string
* @param string $ldapSearchReturn
* @return array
*/
protected function groupFilter($ldapSearchReturn)
{
$groupsAttr = strtolower($this->config['group_attribute']);
$ldapGroups = [];
$count = 0;
if (isset($ldapSearchReturn[$groupsAttr]['count'])) $count = (int) $ldapSearchReturn[$groupsAttr]['count'];
for ($i=0;$i<$count;$i++) {
$dnComponents = ldap_explode_dn($ldapSearchReturn[$groupsAttr][$i],1);
if (!in_array($dnComponents[0],$ldapGroups)) {
$ldapGroups[] = $dnComponents[0];
}
}
return $ldapGroups;
}
/**
* Filter out LDAP CN and DN language in a ldap search return
* Gets the base CN (common name) of the string
* @param string $ldapSearchReturn
* @return array
*/
protected function groupFilter($ldapSearchReturn)
{
$groupsAttr = strtolower($this->config['group_attribute']);
$ldapGroups = [];
$count = 0;
if (isset($ldapSearchReturn[$groupsAttr]['count'])) {
$count = (int) $ldapSearchReturn[$groupsAttr]['count'];
}
for ($i=0; $i<$count; $i++) {
$dnComponents = ldap_explode_dn($ldapSearchReturn[$groupsAttr][$i], 1);
if (!in_array($dnComponents[0], $ldapGroups)) {
$ldapGroups[] = $dnComponents[0];
}
}
return $ldapGroups;
}
} }