Susan Potter
snippets: Created / Updated

Custom Security Handler Nitrogen

An example of a custom security handler implementation for Nitrogen 2.x.

customer_security_handler.erl

%%%   HEADER
%%% @author Susan Potter <me@susanpotter.net>
%%% @date 2011-02-16T17:08
%%% @license BSD
%%% @doc Example of a security_handler behavior implementation module.
%%% It assumes a callback module is passed in that exports:
%%% login_path/0 and authorized/2.
%%% @end
-module(custom_security_handler).

-include_lib("nitrogen_core/include/wf.hrl").

-behaviour(security_handler).

% security_handler behavior exports
-export([init/2, finish/2]).

%%%.
%%%   CALLBACKS

%% @hidden
%% @todo Add authentication code. Currently only authorization.
init(CallbackModule, State) ->
  PageModule = wf:page_module(),
  User = wf:user(),
  case CallbackModule:authorized(User, PageModule) of
      true -> {CallbackModule, State};
      _ -> redirect_to_login_page(CallbackModule)
  end.

%% @hidden
finish(CallbackModule, State) ->
  {CallbackModule, State}.

%%%.
%%%   PRIVATE FUNCTIONS
%% @private
redirect_to_login_page(CallbackModule) ->
  wf:redirect_to_login(CallbackModule:login_path()).

%%%.
%%% vim: set filetype=erlang tabstop=2 foldmarker=%%%',%%%. foldmethod=marker:

custom_security_handler_callback.erl

%%%   HEADER
%%% @author Susan Potter <me@susanpotter.net>
%%% @date 2011-02-16T17:08
%%% @license BSD
%%% @doc Example of a security_handler callback module.
%%% @end
-module(custom_security_handler_callback).

-include_lib("nitrogen_core/include/wf.hrl").

% security_handler callback exports
-export([authorized/2, login_url/0]).

%%%.
%%%   CALLBACKS

%% @hidden
authorized(_User, home_page) -> true;
authorized(User, admin_page) -> admin_authorization(User);
authorized(User, _) -> user_authorization(User).

%% @hidden
login_path() ->
  "/login".

%%%.
%%%   PRIVATE FUNCTIONS
%% @private
admin_authorization(User) ->
  case User of
    "admin" -> true;
    _ -> false
  end.

user_authorization(User) ->
  case User of
    undefined -> false;
    _ -> true
  end.
%%%.
%%% vim: set filetype=erlang tabstop=2 foldmarker=%%%',%%%. foldmethod=marker:

In your application's supervisor code:

%% in your supervisor loop function where you call
%% nitrogen:run/0, you will need to add the following
%% code above your nitrogen:run/0 call
nitrogen:handler(custom_security_handler, custom_security_handler_callback),

If you enjoyed this content, please consider sharing this link with a friend, following my GitHub, Twitter/X or LinkedIn accounts, or subscribing to my RSS feed.