Dan Brown

Increased LDAP testing and fixed any Auth-based bugs found

...@@ -25,6 +25,9 @@ STORAGE_S3_BUCKET=false ...@@ -25,6 +25,9 @@ STORAGE_S3_BUCKET=false
25 # Used to prefix image urls for when using custom domains/cdns 25 # Used to prefix image urls for when using custom domains/cdns
26 STORAGE_URL=false 26 STORAGE_URL=false
27 27
28 +# General auth
29 +AUTH_METHOD=standard
30 +
28 # Social Authentication information. Defaults as off. 31 # Social Authentication information. Defaults as off.
29 GITHUB_APP_ID=false 32 GITHUB_APP_ID=false
30 GITHUB_APP_SECRET=false 33 GITHUB_APP_SECRET=false
......
...@@ -191,6 +191,7 @@ class AuthController extends Controller ...@@ -191,6 +191,7 @@ class AuthController extends Controller
191 } 191 }
192 192
193 $newUser->email_confirmed = true; 193 $newUser->email_confirmed = true;
194 +
194 auth()->login($newUser); 195 auth()->login($newUser);
195 session()->flash('success', 'Thanks for signing up! You are now registered and signed in.'); 196 session()->flash('success', 'Thanks for signing up! You are now registered and signed in.');
196 return redirect($this->redirectPath()); 197 return redirect($this->redirectPath());
......
...@@ -58,18 +58,31 @@ class UserController extends Controller ...@@ -58,18 +58,31 @@ class UserController extends Controller
58 public function store(Request $request) 58 public function store(Request $request)
59 { 59 {
60 $this->checkPermission('user-create'); 60 $this->checkPermission('user-create');
61 - $this->validate($request, [ 61 + $validationRules = [
62 'name' => 'required', 62 'name' => 'required',
63 'email' => 'required|email|unique:users,email', 63 'email' => 'required|email|unique:users,email',
64 - 'password' => 'required|min:5',
65 - 'password-confirm' => 'required|same:password',
66 'role' => 'required|exists:roles,id' 64 '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 +
68 76
69 $user = $this->user->fill($request->all()); 77 $user = $this->user->fill($request->all());
78 +
79 + if ($authMethod === 'standard') {
70 $user->password = bcrypt($request->get('password')); 80 $user->password = bcrypt($request->get('password'));
71 - $user->save(); 81 + } elseif ($authMethod === 'ldap') {
82 + $user->external_auth_id = $request->get('external_auth_id');
83 + }
72 84
85 + $user->save();
73 $user->attachRoleId($request->get('role')); 86 $user->attachRoleId($request->get('role'));
74 87
75 // Get avatar from gravatar and save 88 // Get avatar from gravatar and save
......
...@@ -48,6 +48,14 @@ class UserRepo ...@@ -48,6 +48,14 @@ class UserRepo
48 { 48 {
49 $user = $this->create($data); 49 $user = $this->create($data);
50 $this->attachDefaultRole($user); 50 $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 +
51 return $user; 59 return $user;
52 } 60 }
53 61
......
1 <?php namespace BookStack\Services; 1 <?php namespace BookStack\Services;
2 2
3 +use BookStack\Exceptions\ImageUploadException;
3 use BookStack\Image; 4 use BookStack\Image;
4 use BookStack\User; 5 use BookStack\User;
5 use Intervention\Image\ImageManager; 6 use Intervention\Image\ImageManager;
...@@ -71,6 +72,7 @@ class ImageService ...@@ -71,6 +72,7 @@ class ImageService
71 * @param string $imageData 72 * @param string $imageData
72 * @param string $type 73 * @param string $type
73 * @return Image 74 * @return Image
75 + * @throws ImageUploadException
74 */ 76 */
75 private function saveNew($imageName, $imageData, $type) 77 private function saveNew($imageName, $imageData, $type)
76 { 78 {
...@@ -86,17 +88,24 @@ class ImageService ...@@ -86,17 +88,24 @@ class ImageService
86 } 88 }
87 $fullPath = $imagePath . $imageName; 89 $fullPath = $imagePath . $imageName;
88 90
91 + if(!is_writable(dirname(public_path($fullPath)))) throw new ImageUploadException('Image Directory ' . public_path($fullPath) . ' is not writable by the server.');
92 +
89 $storage->put($fullPath, $imageData); 93 $storage->put($fullPath, $imageData);
90 94
91 - $userId = auth()->user()->id; 95 + $imageDetails = [
92 - $image = Image::forceCreate([
93 'name' => $imageName, 96 'name' => $imageName,
94 'path' => $fullPath, 97 'path' => $fullPath,
95 'url' => $this->getPublicUrl($fullPath), 98 'url' => $this->getPublicUrl($fullPath),
96 - 'type' => $type, 99 + 'type' => $type
97 - 'created_by' => $userId, 100 + ];
98 - 'updated_by' => $userId 101 +
99 - ]); 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);
100 109
101 return $image; 110 return $image;
102 } 111 }
...@@ -188,6 +197,7 @@ class ImageService ...@@ -188,6 +197,7 @@ class ImageService
188 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png'); 197 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
189 $image = $this->saveNewFromUrl($url, 'user', $imageName); 198 $image = $this->saveNewFromUrl($url, 'user', $imageName);
190 $image->created_by = $user->id; 199 $image->created_by = $user->id;
200 + $image->updated_by = $user->id;
191 $image->save(); 201 $image->save();
192 return $image; 202 return $image;
193 } 203 }
......
...@@ -36,6 +36,7 @@ class LdapService ...@@ -36,6 +36,7 @@ class LdapService
36 public function getUserDetails($userName) 36 public function getUserDetails($userName)
37 { 37 {
38 $ldapConnection = $this->getConnection(); 38 $ldapConnection = $this->getConnection();
39 + $this->bindSystemUser($ldapConnection);
39 40
40 // Find user 41 // Find user
41 $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]); 42 $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
...@@ -93,7 +94,7 @@ class LdapService ...@@ -93,7 +94,7 @@ class LdapService
93 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass); 94 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
94 } 95 }
95 96
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'));
97 } 98 }
98 99
99 /** 100 /**
......
...@@ -2,12 +2,24 @@ ...@@ -2,12 +2,24 @@
2 2
3 A platform to create documentation/wiki content. General information about BookStack can be found at https://www.bookstackapp.com/ 3 A platform to create documentation/wiki content. General information about BookStack can be found at https://www.bookstackapp.com/
4 4
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 +
5 17
6 ## Requirements 18 ## Requirements
7 19
8 BookStack has similar requirements to Laravel. On top of those are some front-end build tools which are only required when developing. 20 BookStack has similar requirements to Laravel. On top of those are some front-end build tools which are only required when developing.
9 21
10 -* PHP >= 5.5.9 22 +* PHP >= 5.5.9, Will need to be usable from the command line.
11 * OpenSSL PHP Extension 23 * OpenSSL PHP Extension
12 * PDO PHP Extension 24 * PDO PHP Extension
13 * MBstring PHP Extension 25 * MBstring PHP Extension
...@@ -21,9 +33,7 @@ BookStack has similar requirements to Laravel. On top of those are some front-en ...@@ -21,9 +33,7 @@ BookStack has similar requirements to Laravel. On top of those are some front-en
21 33
22 ## Installation 34 ## Installation
23 35
24 -Ensure the requirements are met before installing. 36 +Ensure the above requirements are met before installing. Currently BookStack requires its own domain/subdomain and will not work in a site subdirectory.
25 -
26 -Currently BookStack requires its own domain/subdomain and will not work in a site subdirectory.
27 37
28 This project currently uses the `release` branch of this repository as a stable channel for providing updates. 38 This project currently uses the `release` branch of this repository as a stable channel for providing updates.
29 39
...@@ -71,7 +81,7 @@ This command will update the repository that was created in the installation, in ...@@ -71,7 +81,7 @@ This command will update the repository that was created in the installation, in
71 81
72 ## Social Authentication 82 ## Social Authentication
73 83
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:
75 85
76 ### Google 86 ### Google
77 87
...@@ -97,6 +107,43 @@ BookStack currently supports login via both Google and Github. Once enabled opti ...@@ -97,6 +107,43 @@ BookStack currently supports login via both Google and Github. Once enabled opti
97 5. Set the 'APP_URL' environment variable to be the same domain as you entered in step 3. 107 5. Set the 'APP_URL' environment variable to be the same domain as you entered in step 3.
98 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. 108 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.
99 109
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 +
100 ## Testing 147 ## Testing
101 148
102 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. 149 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.
......
...@@ -19,18 +19,18 @@ class LdapTest extends \TestCase ...@@ -19,18 +19,18 @@ class LdapTest extends \TestCase
19 $this->mockUser = factory(User::class)->make(); 19 $this->mockUser = factory(User::class)->make();
20 } 20 }
21 21
22 - public function test_ldap_login() 22 + public function test_login()
23 { 23 {
24 $this->mockLdap->shouldReceive('connect')->once()->andReturn($this->resourceId); 24 $this->mockLdap->shouldReceive('connect')->once()->andReturn($this->resourceId);
25 $this->mockLdap->shouldReceive('setOption')->once(); 25 $this->mockLdap->shouldReceive('setOption')->once();
26 - $this->mockLdap->shouldReceive('searchAndGetEntries')->twice() 26 + $this->mockLdap->shouldReceive('searchAndGetEntries')->times(4)
27 ->with($this->resourceId, config('services.ldap.base_dn'), Mockery::type('string'), Mockery::type('array')) 27 ->with($this->resourceId, config('services.ldap.base_dn'), Mockery::type('string'), Mockery::type('array'))
28 ->andReturn(['count' => 1, 0 => [ 28 ->andReturn(['count' => 1, 0 => [
29 'uid' => [$this->mockUser->name], 29 'uid' => [$this->mockUser->name],
30 'cn' => [$this->mockUser->name], 30 'cn' => [$this->mockUser->name],
31 'dn' => ['dc=test'.config('services.ldap.base_dn')] 31 'dn' => ['dc=test'.config('services.ldap.base_dn')]
32 ]]); 32 ]]);
33 - $this->mockLdap->shouldReceive('bind')->times(1)->andReturn(true); 33 + $this->mockLdap->shouldReceive('bind')->times(6)->andReturn(true);
34 34
35 $this->visit('/login') 35 $this->visit('/login')
36 ->see('Username') 36 ->see('Username')
...@@ -38,6 +38,73 @@ class LdapTest extends \TestCase ...@@ -38,6 +38,73 @@ class LdapTest extends \TestCase
38 ->type($this->mockUser->password, '#password') 38 ->type($this->mockUser->password, '#password')
39 ->press('Sign In') 39 ->press('Sign In')
40 ->seePageIs('/login')->see('Please enter an email to use for this account.'); 40 ->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');
41 } 108 }
42 109
43 } 110 }
...\ No newline at end of file ...\ No newline at end of file
......