Skip to content

Commit 7bcd967

Browse files
committed
Increased LDAP testing and fixed any Auth-based bugs found
1 parent bb87401 commit 7bcd967

File tree

8 files changed

+172
-22
lines changed

8 files changed

+172
-22
lines changed

.env.example

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ STORAGE_S3_BUCKET=false
2525
# Used to prefix image urls for when using custom domains/cdns
2626
STORAGE_URL=false
2727

28+
# General auth
29+
AUTH_METHOD=standard
30+
2831
# Social Authentication information. Defaults as off.
2932
GITHUB_APP_ID=false
3033
GITHUB_APP_SECRET=false

app/Http/Controllers/Auth/AuthController.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ protected function registerUser(array $userData, $socialAccount = false)
191191
}
192192

193193
$newUser->email_confirmed = true;
194+
194195
auth()->login($newUser);
195196
session()->flash('success', 'Thanks for signing up! You are now registered and signed in.');
196197
return redirect($this->redirectPath());

app/Http/Controllers/UserController.php

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,18 +58,31 @@ public function create()
5858
public function store(Request $request)
5959
{
6060
$this->checkPermission('user-create');
61-
$this->validate($request, [
61+
$validationRules = [
6262
'name' => 'required',
6363
'email' => 'required|email|unique:users,email',
64-
'password' => 'required|min:5',
65-
'password-confirm' => 'required|same:password',
6664
'role' => 'required|exists:roles,id'
67-
]);
65+
];
66+
67+
$authMethod = config('auth.method');
68+
if ($authMethod === 'standard') {
69+
$validationRules['password'] = 'required|min:5';
70+
$validationRules['password-confirm'] = 'required|same:password';
71+
} elseif ($authMethod === 'ldap') {
72+
$validationRules['external_auth_id'] = 'required';
73+
}
74+
$this->validate($request, $validationRules);
75+
6876

6977
$user = $this->user->fill($request->all());
70-
$user->password = bcrypt($request->get('password'));
71-
$user->save();
7278

79+
if ($authMethod === 'standard') {
80+
$user->password = bcrypt($request->get('password'));
81+
} elseif ($authMethod === 'ldap') {
82+
$user->external_auth_id = $request->get('external_auth_id');
83+
}
84+
85+
$user->save();
7386
$user->attachRoleId($request->get('role'));
7487

7588
// Get avatar from gravatar and save

app/Repos/UserRepo.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,14 @@ public function registerNew(array $data)
4848
{
4949
$user = $this->create($data);
5050
$this->attachDefaultRole($user);
51+
52+
// Get avatar from gravatar and save
53+
if (!config('services.disable_services')) {
54+
$avatar = \Images::saveUserGravatar($user);
55+
$user->avatar()->associate($avatar);
56+
$user->save();
57+
}
58+
5159
return $user;
5260
}
5361

app/Services/ImageService.php

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<?php namespace BookStack\Services;
22

3+
use BookStack\Exceptions\ImageUploadException;
34
use BookStack\Image;
45
use BookStack\User;
56
use Intervention\Image\ImageManager;
@@ -71,6 +72,7 @@ private function saveNewFromUrl($url, $type, $imageName = false)
7172
* @param string $imageData
7273
* @param string $type
7374
* @return Image
75+
* @throws ImageUploadException
7476
*/
7577
private function saveNew($imageName, $imageData, $type)
7678
{
@@ -86,17 +88,24 @@ private function saveNew($imageName, $imageData, $type)
8688
}
8789
$fullPath = $imagePath . $imageName;
8890

91+
if(!is_writable(dirname(public_path($fullPath)))) throw new ImageUploadException('Image Directory ' . public_path($fullPath) . ' is not writable by the server.');
92+
8993
$storage->put($fullPath, $imageData);
9094

91-
$userId = auth()->user()->id;
92-
$image = Image::forceCreate([
95+
$imageDetails = [
9396
'name' => $imageName,
9497
'path' => $fullPath,
9598
'url' => $this->getPublicUrl($fullPath),
96-
'type' => $type,
97-
'created_by' => $userId,
98-
'updated_by' => $userId
99-
]);
99+
'type' => $type
100+
];
101+
102+
if (auth()->user() && auth()->user()->id !== 0) {
103+
$userId = auth()->user()->id;
104+
$imageDetails['created_by'] = $userId;
105+
$imageDetails['updated_by'] = $userId;
106+
}
107+
108+
$image = Image::forceCreate($imageDetails);
100109

101110
return $image;
102111
}
@@ -188,6 +197,7 @@ public function saveUserGravatar(User $user, $size = 500)
188197
$imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
189198
$image = $this->saveNewFromUrl($url, 'user', $imageName);
190199
$image->created_by = $user->id;
200+
$image->updated_by = $user->id;
191201
$image->save();
192202
return $image;
193203
}

app/Services/LdapService.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ public function __construct(Ldap $ldap)
3636
public function getUserDetails($userName)
3737
{
3838
$ldapConnection = $this->getConnection();
39+
$this->bindSystemUser($ldapConnection);
3940

4041
// Find user
4142
$userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
@@ -93,7 +94,7 @@ protected function bindSystemUser($connection)
9394
$ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
9495
}
9596

96-
if (!$ldapBind) throw new LdapException('LDAP access failed using ' . $isAnonymous ? ' anonymous bind.' : ' given dn & pass details');
97+
if (!$ldapBind) throw new LdapException('LDAP access failed using ' . ($isAnonymous ? ' anonymous bind.' : ' given dn & pass details'));
9798
}
9899

99100
/**

readme.md

Lines changed: 53 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,24 @@
22

33
A platform to create documentation/wiki content. General information about BookStack can be found at https://www.bookstackapp.com/
44

5+
1. [Requirements](#requirements)
6+
2. [Installation](#installation)
7+
- [Server Rewrite Rules](#url-rewrite-rules)
8+
3. [Updating](#updating-bookstack)
9+
4. [Social Authentication](#social-authentication)
10+
- [Google](#google)
11+
- [GitHub](#github)
12+
5. [LDAP Authentication](#ldap-authentication)
13+
6. [Testing](#testing)
14+
7. [License](#license)
15+
8. [Attribution](#attribution)
16+
517

618
## Requirements
719

820
BookStack has similar requirements to Laravel. On top of those are some front-end build tools which are only required when developing.
921

10-
* PHP >= 5.5.9
22+
* PHP >= 5.5.9, Will need to be usable from the command line.
1123
* OpenSSL PHP Extension
1224
* PDO PHP Extension
1325
* MBstring PHP Extension
@@ -21,9 +33,7 @@ BookStack has similar requirements to Laravel. On top of those are some front-en
2133

2234
## Installation
2335

24-
Ensure the requirements are met before installing.
25-
26-
Currently BookStack requires its own domain/subdomain and will not work in a site subdirectory.
36+
Ensure the above requirements are met before installing. Currently BookStack requires its own domain/subdomain and will not work in a site subdirectory.
2737

2838
This project currently uses the `release` branch of this repository as a stable channel for providing updates.
2939

@@ -67,11 +77,11 @@ To update BookStack you can run the following command in the root directory of t
6777
```
6878
git pull origin release && composer install && php artisan migrate
6979
```
70-
This command will update the repository that was created in the installation, install the PHP dependencies using `composer` then run the database migrations.
80+
This command will update the repository that was created in the installation, install the PHP dependencies using `composer` then run the database migrations.
7181

7282
## Social Authentication
7383

74-
BookStack currently supports login via both Google and Github. Once enabled options for these services will show up in the login, registration and user profile pages. By default these services are disabled. To enable them you will have to create an application on the external services to obtain the require application id's and secrets. Here are instructions to do this for the current supported services:
84+
BookStack currently supports login via both Google and GitHub. Once enabled options for these services will show up in the login, registration and user profile pages. By default these services are disabled. To enable them you will have to create an application on the external services to obtain the require application id's and secrets. Here are instructions to do this for the current supported services:
7585

7686
### Google
7787

@@ -97,6 +107,43 @@ BookStack currently supports login via both Google and Github. Once enabled opti
97107
5. Set the 'APP_URL' environment variable to be the same domain as you entered in step 3.
98108
6. All done! Users should now be able to link to their social accounts in their account profile pages and also register/login using their Github account.
99109

110+
## LDAP Authentication
111+
112+
BookStack can be configured to allow LDAP based user login. While LDAP login is enabled you cannot log in with the standard user/password login and new user registration is disabled. BookStack will only use the LDAP server for getting user details and for authentication. Data on the LDAP server is not currently editable through BookStack.
113+
114+
When a LDAP user logs into BookStack for the first time their BookStack profile will be created and they will be given the default role set under the 'Default user role after registration' option in the application settings.
115+
116+
To set up LDAP-based authentication add or modify the following variables in your `.env` file:
117+
118+
```
119+
# General auth
120+
AUTH_METHOD=ldap
121+
122+
# The LDAP host, Adding a port is optional
123+
LDAP_SERVER=ldap://example.com:389
124+
125+
# The base DN from where users will be searched within.
126+
LDAP_BASE_DN=ou=People,dc=example,dc=com
127+
128+
# The full DN and password of the user used to search the server
129+
# Can both be left as false to bind anonymously
130+
LDAP_DN=false
131+
LDAP_PASS=false
132+
133+
# A filter to use when searching for users
134+
# The user-provided user-name used to replace any occurrences of '${user}'
135+
LDAP_USER_FILTER=(&(uid=${user}))
136+
137+
# Set the LDAP version to use when connecting to the server.
138+
LDAP_VERSION=false
139+
```
140+
141+
You will also need to have the php-ldap extension installed on your system. It's recommended to change your `APP_DEBUG` variable to `true` while setting up LDAP to make any errors visible. Remember to change this back after LDAP is functioning.
142+
143+
A user in BookStack will be linked to a LDAP user via a 'uid'. If a LDAP user uid changes it can be updated in BookStack by an admin by changing the 'External Authentication ID' field on the user's profile.
144+
145+
You may find that you cannot log in with your initial Admin account after changing the `AUTH_METHOD` to `ldap`. To get around this set the `AUTH_METHOD` to `standard`, login with your admin account then change it back to `ldap`. You get then edit your profile and add your LDAP uid under the 'External Authentication ID' field. You will then be able to login in with that ID.
146+
100147
## Testing
101148

102149
BookStack has many integration tests that use Laravel's built-in testing capabilities which makes use of PHPUnit. To use you will need PHPUnit installed and accessible via command line. There is a `mysql_testing` database defined within the app config which is what is used by PHPUnit. This database is set with the following database name, user name and password defined as `bookstack-test`. You will have to create that database and credentials before testing.

tests/Auth/LdapTest.php

Lines changed: 70 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,25 +19,92 @@ public function setUp()
1919
$this->mockUser = factory(User::class)->make();
2020
}
2121

22-
public function test_ldap_login()
22+
public function test_login()
2323
{
2424
$this->mockLdap->shouldReceive('connect')->once()->andReturn($this->resourceId);
2525
$this->mockLdap->shouldReceive('setOption')->once();
26-
$this->mockLdap->shouldReceive('searchAndGetEntries')->twice()
26+
$this->mockLdap->shouldReceive('searchAndGetEntries')->times(4)
2727
->with($this->resourceId, config('services.ldap.base_dn'), Mockery::type('string'), Mockery::type('array'))
2828
->andReturn(['count' => 1, 0 => [
2929
'uid' => [$this->mockUser->name],
3030
'cn' => [$this->mockUser->name],
3131
'dn' => ['dc=test'.config('services.ldap.base_dn')]
3232
]]);
33-
$this->mockLdap->shouldReceive('bind')->times(1)->andReturn(true);
33+
$this->mockLdap->shouldReceive('bind')->times(6)->andReturn(true);
3434

3535
$this->visit('/login')
3636
->see('Username')
3737
->type($this->mockUser->name, '#username')
3838
->type($this->mockUser->password, '#password')
3939
->press('Sign In')
4040
->seePageIs('/login')->see('Please enter an email to use for this account.');
41+
42+
$this->type($this->mockUser->email, '#email')
43+
->press('Sign In')
44+
->seePageIs('/')
45+
->see($this->mockUser->name)
46+
->seeInDatabase('users', ['email' => $this->mockUser->email, 'email_confirmed' => 1, 'external_auth_id' => $this->mockUser->name]);
47+
}
48+
49+
public function test_initial_incorrect_details()
50+
{
51+
$this->mockLdap->shouldReceive('connect')->once()->andReturn($this->resourceId);
52+
$this->mockLdap->shouldReceive('setOption')->once();
53+
$this->mockLdap->shouldReceive('searchAndGetEntries')->times(2)
54+
->with($this->resourceId, config('services.ldap.base_dn'), Mockery::type('string'), Mockery::type('array'))
55+
->andReturn(['count' => 1, 0 => [
56+
'uid' => [$this->mockUser->name],
57+
'cn' => [$this->mockUser->name],
58+
'dn' => ['dc=test'.config('services.ldap.base_dn')]
59+
]]);
60+
$this->mockLdap->shouldReceive('bind')->times(3)->andReturn(true, true, false);
61+
62+
$this->visit('/login')
63+
->see('Username')
64+
->type($this->mockUser->name, '#username')
65+
->type($this->mockUser->password, '#password')
66+
->press('Sign In')
67+
->seePageIs('/login')->see('These credentials do not match our records.')
68+
->dontSeeInDatabase('users', ['external_auth_id' => $this->mockUser->name]);
69+
}
70+
71+
public function test_create_user_form()
72+
{
73+
$this->asAdmin()->visit('/users/create')
74+
->dontSee('Password')
75+
->type($this->mockUser->name, '#name')
76+
->type($this->mockUser->email, '#email')
77+
->press('Save')
78+
->see('The external auth id field is required.')
79+
->type($this->mockUser->name, '#external_auth_id')
80+
->press('Save')
81+
->seePageIs('/users')
82+
->seeInDatabase('users', ['email' => $this->mockUser->email, 'external_auth_id' => $this->mockUser->name, 'email_confirmed' => true]);
83+
}
84+
85+
public function test_user_edit_form()
86+
{
87+
$editUser = User::all()->last();
88+
$this->asAdmin()->visit('/users/' . $editUser->id)
89+
->see('Edit User')
90+
->dontSee('Password')
91+
->type('test_auth_id', '#external_auth_id')
92+
->press('Save')
93+
->seePageIs('/users')
94+
->seeInDatabase('users', ['email' => $editUser->email, 'external_auth_id' => 'test_auth_id']);
95+
}
96+
97+
public function test_registration_disabled()
98+
{
99+
$this->visit('/register')
100+
->seePageIs('/login');
101+
}
102+
103+
public function test_non_admins_cannot_change_auth_id()
104+
{
105+
$testUser = User::all()->last();
106+
$this->actingAs($testUser)->visit('/users/' . $testUser->id)
107+
->dontSee('External Authentication');
41108
}
42109

43110
}

0 commit comments

Comments
 (0)