Debian Codegraph @

doc/sources/admin/plugincustom.rst

raw
1 Write a custom plugin
2 =====================
3
4 Presentation
5 ------------
6
7 Portal plugins let you customize LemonLDAP::NG's behavior.
8
9 Common use cases for plugins are:
10
11 * Looking up session information in an additional backend
12 * Implementing additional controls or steps during login
13 * Adjusting the behavior of SAML, OIDC or CAS protocols to work around application bugs
14
15 Creating a plugin can be as simple as writing a short Perl module file and
16 declaring it in your configuration. See below for an example.
17
18
19 .. _plugin-options:
20
21 Enabling custom plugins
22 -----------------------
23
24 LemonLDAP::NG comes with many plugins already, but you might want to write your owns and load them as well
25
26 In *General parameters* » *Plugins* » *Custom plugins*
27
28 - **Modules list**: The list of custom modules to load. Modules will be loaded after the built-in ones
29 - **Additional parameters**: Configuration for your custom plugins
30 - **Disabled plugins**: (*since 2.21.0*): List of built-in modules you do not
31 want LemonLDAP::NG to load. This is useful if you want to overload a built-in
32 module with one of your own.
33
34 Plugin API
35 ----------
36
37 Authentication entry points
38 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
39
40 You can now write a custom portal plugin that will hook in the
41 authentication process:
42
43 - ``beforeAuth``: method called before authentication process
44 - ``betweenAuthAndData``: method called after authentication and before
45 setting "sessionInfo" provisionning
46 - ``afterData``: method called after "sessionInfo" provisionning
47 - ``endAuth``: method called when session is validated (after cookie
48 build)
49 - ``authCancel``: method called when user click on "cancel" during auth
50 process
51 - ``forAuthUser``: method called for already authenticated users
52 - ``beforeLogout``: method called before logout
53
54 Generic entry points
55 ~~~~~~~~~~~~~~~~~~~~
56
57 If you need to call a method just after any standard method in
58 authentication process, then use ``afterSub``, for example:
59
60 .. code-block:: perl
61
62 use constant afterSub => {
63 getUser => 'mysub',
64 };
65 sub mysub {
66 my ( $self ,$req ) = @_;
67 # Do something
68 return PE_OK;
69 }
70
71 If you need to call a method instead any standard method in
72 authentication process, then use ``aroundSub``, for example:
73
74 .. code-block:: perl
75
76 use constant aroundSub => {
77 getUser => 'mysub',
78 };
79 sub mysub {
80 my ( $self, $sub, $req ) = @_;
81 # Do something before
82 my $ret = $sub->($req);
83 # Do something after
84 return $ret;
85 }
86
87
88 Hooks
89 ~~~~~
90
91 .. versionadded:: 2.0.10
92
93 Your plugin can also register itself to be called at some points of interest
94 within the main LemonLDAP::NG code.
95
96 Check the :doc:`list of available plugin hooks <hooks>` for details
97
98 Routes
99 ~~~~~~
100
101 The plugin can also define new routes and call actions on them.
102
103 See also ``Lemonldap::NG::Portal::Main::Plugin`` man page.
104
105 Configuration
106 ~~~~~~~~~~~~~
107
108 The current LemonLDAP::NG configuration can be accessed in the ``$self->conf`` hash. This variable is only meant to be read. Don't try changing its content, or *Bad Things* may happen.
109
110 You can set your own parameters in ``General Parameters`` » ``Plugins`` » ``Custom plugins`` » ``Additional parameters``
111 and reach them through ``customPluginsParams``
112
113 .. tip::
114
115 If you have got several plugins with several parameters, parameters can be passed by using JSON notation ``myPluginParams = {"title":"myTitle", "msg":"myMsg"}`` and converted into a PERL object with ``from_json`` function.
116
117
118 .. code-block:: perl
119
120 use Mouse;
121 use JSON 'from_json';
122
123 has myPluginParams => (
124 is => 'ro',
125 builder => sub {
126 my $self = $_[0];
127 my $defaultParams = {
128 title => 'title',
129 msg => 'msg',
130 path => 'path',
131 };
132 my $params = eval {
133 from_json( $self->conf->{customPluginsParams}->{myPluginParams} );
134 };
135 if ($@) {
136 my $package = __PACKAGE__;
137 $self->userLogger->warn(
138 "Bad JSON file: $package plugin will use default parameters ($@)"
139 );
140 return $defaultParams;
141 }
142 return { %$defaultParams, %$params };
143 }
144 );
145
146 sub my_function {
147 my ($self, $req) = @_;
148
149 # Get a standard LLNG option
150 my $llng_logo = $self->conf->{portalMainLogo};
151
152 # Get your custom LLNG option
153 my $myvar = $self->conf->{customPluginsParams}->{myvar};
154
155 # Get your custom LLNG option from your parameters hash
156 my $title = $self->myPluginParams->{title};
157 }
158
159 Logs
160 ~~~~
161
162 You can use the ``$self->logger`` and ``$self->userLogger`` objects to log information during your plugin execution. Use ``logger`` for technical logs and ``userLogger`` for accounting and tracability events.
163
164 .. code-block:: perl
165
166 sub my_function {
167 my ($self, $req) = @_;
168
169 $self->logger->debug("Debug message");
170 if (my_custom_test($req->user)) {
171 $self->userLogger->debug("User ". $req->user .
172 " is not allowed because XXX");
173
174 return PE_ERROR;
175 }
176 return PE_OK;
177 }
178
179
180 Remembering data
181 ~~~~~~~~~~~~~~~~
182
183 In order to remember data between different steps, you can use the ``$req->data`` hash.
184
185 Data will not be remembered in between requests, only in between methods that process the same HTTP request.
186
187 History management
188 ~~~~~~~~~~~~~~~~~~
189
190 Plugins may declare additional session fields to be stored in the :doc:`loginhistory`.
191
192 .. code:: perl
193
194 sub init {
195 my ($self) = @_;
196
197 $self->addSessionDataToRemember({
198 # This field will be hidden from the user
199 _language => '__hidden__',
200
201 # This field will be displayed on the portal. The column name
202 # is treated like a message and can be internationalized
203 authenticationLevel => "Human friendly column name",
204 });
205 return 1;
206 }
207
208 Column names can be translated by :ref:`overriding the corresponding message <intlmessages>`
209
210 .. _pluginppolicy:
211
212 Password policies
213 ~~~~~~~~~~~~~~~~~
214
215 You can implement custom password policies in your plugins.
216
217 In order to do this, implement the :ref:`passwordBeforeChange hook <passwordBeforeChange>`.
218
219 If you want to display user feedback, you need to do two additional things
220
221 * In you plugin's ``init`` method, declare a HTML control for your policy ::
222
223 $self->p->addPasswordPolicyDisplay(
224 'ppolicy-custom1',
225 {
226 # Activation condition
227 condition => $self->conf->{customPluginsParams}->{myPpolicyEnabled},
228 # Label to show the user
229 label => "myppolicy",
230 # What value to display in front of the label
231 value => 1,
232 # Optional key-value HTML data-* elements
233 data => { },
234 # Custom HTML code to inject before the element
235 customHtml => qq'<script type="text/javascript" src="$self->{p}->{staticPrefix}/common/js/myppolicy.min.js"></script>',
236 # Custom HTML code to inject after the element
237 customHtmlAfter => qq'<div id="advanced_feedback"></div>',
238 # Optional display order, higher goes last
239 order => 100,
240 }
241 );
242
243 * Implement a JS check and trigger it on the :ref:`checkpassword event <checkpassword>`
244
245 Creating a custom CAPTCHA
246 ~~~~~~~~~~~~~~~~~~~~~~~~~
247
248 See the ``Lemonldap::NG::Portal::Captcha`` manual page for details on how to
249 implement a Captcha module.
250
251 Creating a custom menu tab
252 ~~~~~~~~~~~~~~~~~~~~~~~~~~
253
254 See the ``Lemonldap::NG::Portal::MenuTab`` manual page for details on how to
255 implement a new tab for the application menu
256
257 Creating a second factor module
258 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
259
260 Adding a new type of second factor requires one or two modules:
261
262 * A module for using the second factor during authentication
263
264 This module must inherit from ``Lemonldap::NG::Portal::Main::SecondFactor``.
265
266 .. code:: perl
267
268 package My::SFA;
269
270 use strict;
271 use Mouse;
272
273 extends 'Lemonldap::NG::Portal::Main::SecondFactor';
274
275 * (optional) A module for registering the second factor
276
277 This module must inherit from ``Lemonldap::NG::Portal::2F::Register::Base``.
278
279 .. code:: perl
280
281 package My::SFARegister;
282
283 use strict;
284 use Mouse;
285
286 extends 'Lemonldap::NG::Portal::2F::Register::Base';
287
288 Custom entry points
289 ~~~~~~~~~~~~~~~~~~~
290
291 Entrypoints allow plugins to register custom actions when they are loaded.
292 LemonLDAP::NG comes with many pre-defined entrypoints already. But you may want
293 to add your own, especially if you are creating a plugin that can itself have
294 plugins.
295
296 You can call the ``addEntryPoint`` method in your plugin's ``init`` to
297 create your custom entrypoints.
298
299 .. note::
300
301 Only plugins loaded *after* registering the entry point will trigger it. Be
302 careful with the ordering of your ``customPlugins`` variable.
303
304 Here are a few examples:
305
306 .. code:: perl
307
308 sub init {
309 my ($self) = @_;
310
311 # ...
312
313 # From now on, when loading a new plugin that inherits from
314 # My::Base::Class, run the provided code reference, with an
315 # instance of the plugin being loaded as first argument
316 $self->addEntryPoint(
317 isa => "My::Base::Class",
318 callback => sub {
319 my ($plugin) = @_;
320 $self->do_domething_with($plugin);
321 }
322 );
323
324 # From now on, when loading a new plugin that uses My::Role
325 # Call a particular method of a particular service, passing the new
326 # plugins instance and optional extra arguments.
327 # This will effectively run:
328 # $portal->getService('myservice')
329 # ->mymethod($plugin, "role_entry_point")
330 $self->addEntryPoint(
331 does => "My::Role",
332 service => "myservice",
333 method => "mymethod",
334 args => ["role_entry_point"],
335 );
336
337 # ...
338 return 1;
339 }
340
341 See also ``Lemonldap::NG::Portal::Main::Plugin`` man page for full details.
342
343 Example
344 -------
345
346 Plugin Perl module
347 ~~~~~~~~~~~~~~~~~~
348
349 This example creates a ``Lemonldap::NG::Portal::Plugins::MyPlugin`` plugin that
350 showcases some features of the plugin system.
351
352 First, create a file to contain the plugin code ::
353
354 vi /usr/share/perl5/Lemonldap/NG/Portal/Plugins/MyPlugin.pm
355
356 .. tip::
357
358 If you do not want to mix files from the distribution with
359 your own work, put your own code in
360 ``/usr/local/lib/site_perl/Lemonldap/NG/Portal/Plugins/MyPlugin.pm``.
361 Or you can use your own namespace such as ``ACME::Corp::MyPlugin``.
362
363 .. code-block:: perl
364
365 # The package name must match the file path
366 # This file must be in Lemonldap/NG/Portal/Plugins/MyPlugin.pm
367 package Lemonldap::NG::Portal::Plugins::MyPlugin;
368
369 use Mouse;
370 use Lemonldap::NG::Portal::Main::Constants;
371 extends 'Lemonldap::NG::Portal::Main::Plugin';
372
373 # Declare when LemonLDAP::NG must call your functions
374 use constant beforeAuth => 'verifyIP';
375 use constant hook => { passwordAfterChange => 'logPasswordChange' };
376
377 # This function will be called at the "beforeAuth" login step
378 sub verifyIP {
379 my ($self, $req) = @_;
380 return PE_ERROR if($req->address !~ /^10/);
381 return PE_OK;
382 }
383
384 # This function will be called when changing passwords
385 sub logPasswordChange {
386 my ( $self, $req, $user, $password, $old ) = @_;
387 $self->userLogger->info("Password changed for $user");
388 return PE_OK;
389 }
390
391 # You can define your custom initialization in the
392 # init method.
393 # Before LemonLDAP::NG 2.0.14, this function was mandatory
394 sub init {
395 my ($self) = @_;
396
397 # This is how you declare HTTP routes
398 $self->addUnauthRoute( mypath => 'hello', [ 'GET', 'PUT' ] );
399 $self->addAuthRoute( mypath => 'welcome', [ 'GET', 'PUT' ] );
400
401 # The function can return 0 to indicate failure
402 return 1;
403 }
404
405 # This method will be called to handle unauthenticated requests to /mypath
406 sub hello {
407 my ($self, $req) = @_;
408 ...
409 return $self->p->sendJSONresponse($req, { hello => 1 });
410 }
411
412 # This method will be called to handle authenticated requests to /mypath
413 sub welcome {
414 my ($self, $req) = @_;
415
416 my $userid = $req->user;
417 $self->p->logger->debug("Call welcome for $userid");
418
419 ...
420 return $self->p->sendHtml($req, 'template', params => { WELCOME => 1 });
421 }
422
423 # Your file must return 1, or Perl will complain.
424 1;
425
426
427 Enabling your plugin
428 ~~~~~~~~~~~~~~~~~~~~
429
430 Declare the plugin in lemonldap-ng.ini:
431
432 ::
433
434 vi /etc/lemonldap-ng/lemonldap-ng.ini
435
436 .. code-block:: perl
437
438 [portal]
439 customPlugins = Lemonldap::NG::Portal::Plugins::MyPlugin
440 ;customPlugins = Lemonldap::NG::Portal::Plugins::MyPlugin1, Lemonldap::NG::Portal::Plugins::MyPlugin2, ...
441
442 Since 2.0.7, it can also be configured in Manager, in General Parameters
443 > Plugins > Custom Plugins.