Warning: Reason support is experimental. We are looking for beta-tester and contributors.

Implementing Web Interaction Using Eliom

The code of this tutorial has been tested with Eliom 6.0.

This chapter of the tutorial explains how to create a small web site with several pages, users, sessions, and other elements of classical web development. Then, in another tutorial, we will incorporate the features of this site into our Graffiti application, to demonstrate that we can combine this kind of interaction with client-side programs.

We assume you have read at least the first section of the previous chapter, which explained how to create a service and constuct valid HTML pages.

We will create a simple web site with one main page and a page for each user (assuming we have several users already created). Then we will add a login/connection form. We will also add a registration form, in order to learn how to create dynamically new services, and why it is very useful.

The full code of the program can be downloaded.

Services

The main page

Let's start again from scratch with the following site.

let main_service = Eliom_content.Html.D.(
  Eliom_registration.Html.create
    ~path:(Eliom_service.Path [""])
    ~meth:(Eliom_service.Get Eliom_parameter.unit)
    (fun () () ->
      Lwt.return
        (html (head (title (txt "")) [])
           (body [h1 [txt "Hello"]])))
)

Note that we are using Eliom_registration.Html, as we are not building a client side program for now.

For the same reason, you may want to remove the .eliom-file generated by the distillery and put the code into an .ml-file. But don't forget to add it to the server files in the Makefile.options:

SERVER_FILES := tuto.ml

Adding a page for each user

We will now create a page for each user. To do this, we will create a new service, taking the user name as parameter:

let user_service = Eliom_content.Html.D.(
  Eliom_registration.Html.create
    ~path:(Eliom_service.Path [""])
    ~meth:(Eliom_service.Get (Eliom_parameter.string "name"))
    (fun name () ->
      Lwt.return
        (html (head (title (txt name)) [])
           (body [h1 [txt name]])))
)

Add these lines to the same file, compile, start the server and verify that everything is working by trying, for example: http://localhost:8080/?name=toto.

For our program, we would prefer to take one part of the URL path as the parameter describing the name of the user. To achieve this we change the definition of the previous service this way:

let user_service =
  Eliom_registration.Html.create
    ~path:(Eliom_service.Path ["users"])
    ~meth:(Eliom_service.Get (
      Eliom_parameter.(suffix (string "name"))))
    (fun name () -> ... )

The user pages are now available at URLs http://localhost:8080/users/username.

Links

We now want to add a link on each user page to go back to the main page.

Change the handler of user_service into:

(fun name () -> Lwt.return
  (html
    (head (title (txt name)) [])
    (body [h1 [txt name];
           p [a ~service:main_service [txt "Home"] ()]])))

Links towards services with parameters

In our example above, the last parameter is () because the service does not expect any parameter. If the service expects, for example, a pair (int * string), you must provide a matching value as last parameter. OCaml checks at compile time that the type of the parameters in a link corresponds to the type expected by the service. Also parameter names are generated automatically from the service, making it impossible to erroneously create bad links.

To show an example of a link with parameters, we will display the list of user pages on the main page. Here is the new version of the full program:

(* Services *)
let main_service = Eliom_service.create
  ~path:(Eliom_service.Path [""])
  ~meth:(Eliom_service.Get Eliom_parameter.unit)
  ()

let user_service  = Eliom_service.create
  ~path:(Eliom_service.Path ["users"])
  ~meth:(Eliom_service.Get Eliom_parameter.(suffix (string "name")))
  ()

(* User names and passwords: *)
let users = ref [("Calvin", "123"); ("Hobbes", "456")]

let user_links = Eliom_content.Html.D.(
  let link_of_user = fun (name, _) ->
    li [a ~service:user_service [txt name] name]
  in
  fun () -> ul (List.map link_of_user !users)
)

(* Services Registration *)
let () = Eliom_content.Html.D.(

  Eliom_registration.Html.register
    ~service:main_service
    (fun () () ->
      Lwt.return
        (html (head (title (txt "")) [])
           (body [h1 [txt "Hello"];
                  user_links ()])));

  Eliom_registration.Html.register
    ~service:user_service
    (fun name () ->
      Lwt.return
        (html (head (title (txt name)) [])
           (body [h1 [txt name];
                  p [a ~service:main_service [txt "Home"] ()]])))
)

Sessions

Connection service

Now we want to add a connection form. First, we create a service for checking the name and password. Since we don't want the username and password to be shown in the URL, we use hidden parameters (or POST parameters). Thus, we need to create a new service taking these parameters:

let connection_service = Eliom_service.create_attached_post
  ~fallback:main_service
  ~post_params:Eliom_parameter.(string "name" ** string "password")
  ()

Now we can register a handler for the new service:

Eliom_registration.Html.register
    ~service:connection_service
    (fun () (name, password) ->
      let message =
        if check_pwd name password
        then "Hello " ^ name
        else "Wrong name or password"
      in
      Lwt.return
        (html (head (title (txt "")) [])
           (body [h1 [txt message];
                  user_links ()])));

where check_pwd is defined by:

let check_pwd name pwd =
  try List.assoc name !users = pwd with Not_found -> false

Connection form

For now, we will add the connection form only on the main page of the site.

Let's create a function for generating the form:

let connection_box () = Eliom_content.Html.D.(
  Form.post_form ~service:connection_service
    (fun (name1, name2) ->
      [fieldset
         [label [txt "login: "];
          Form.input
            ~input_type:`Text ~name:name1
            Form.string;
          br ();
          label [txt "password: "];
          Form.input
            ~input_type:`Password ~name:name2
            Form.string;
          br ();
          Form.input
            ~input_type:`Submit ~value:"Connect"
            Form.string
         ]]) ()
)

Now, add a call to this function in the handler of the main service (for example just before the user links).

Opening a session

Now we want to remember that the user is successfully connected. To do that we will set a reference when the user successfully connects, and we will restrict the scope of this reference to the session (that is, to the browser).

Define your Eliom reference with a default value:

let username =
  Eliom_reference.eref ~scope:Eliom_common.default_session_scope None

Here is the new connection_box function:

let connection_box () = Eliom_content.Html.D.(
  let%lwt u = Eliom_reference.get username in
  Lwt.return
    (match u with
      | Some s -> p [txt "You are connected as "; txt s]
      | None ->
        Form.post_form ~service:connection_service
          (fun (name1, name2) ->
            [fieldset
	       [label [txt "login: "];
                Form.input
                  ~input_type:`Text ~name:name1
                  Form.string;
                br ();
                label [txt "password: "];
                Form.input
                  ~input_type:`Password ~name:name2
                  Form.string;
                br ();
                Form.input
                  ~input_type:`Submit ~value:"Connect"
                  Form.string
               ]]) ())
)

... and replace the registration of the main service and the connection service by:

Eliom_registration.Html.register
    ~service:main_service
    (fun () () ->
      let%lwt cf = connection_box () in
      Lwt.return
        (html (head (title (txt "")) [])
              (body [h1 [txt "Hello"];
                     cf;
                     user_links ()])));

  Eliom_registration.Html.register
    ~service:connection_service
    (fun () (name, password) ->
      let%lwt message =
        if check_pwd name password then
	  begin
            let%lwt () = Eliom_reference.set username (Some name) in
            Lwt.return ("Hello "^name)
	  end
	else
	  Lwt.return "Wrong name or password"
      in
      Lwt.return
        (html (head (title (txt "")) [])
           (body [h1 [txt message];
                  user_links ()])));

Display the usual page after connection

As you can see, our connection service is displaying a welcome page which is different from the main page in connected mode. We would rather display the same page. One solution is to call the same handler after registering session data.

A cleaner solution is to use an action, that is: a service which will just perform a side effect. Replace the registration of the connection service by:

Eliom_registration.Action.register
    ~service:connection_service
    (fun () (name, password) ->
      if check_pwd name password
      then Eliom_reference.set username (Some name)
      else Lwt.return ());

Now the main page is displayed after connection.

Putting a connection form on each page

We transform the connection service into a non_attached coservice, to do so we replace the path we specified earlier for the ~path parameter:

let connection_service = Eliom_service.create
  ~path:(Eliom_service.No_path)
  ~meth:(Eliom_service.Post (
    Eliom_parameter.unit,
    Eliom_parameter.(string "name" ** string "password")))
  ()

Now you can add the connection box on user pages.

Eliom_registration.Html.register
    ~service:user_service
    (fun name () ->
      let%lwt cf = connection_box () in
      Lwt.return
        (html (head (title (txt name)) [])
              (body [h1 [txt name];
		     cf;
                     p [a ~service:main_service [txt "Home"] ()]])));

Disconnection

To create a logout/disconnection form, we create another non-attached coservice using POST method, and register another action. We call the function Eliom_state.discard with scope Eliom_common.default_session_scope to remove all session data.

let disconnection_service = Eliom_service.create
  ~path:(Eliom_service.No_path)
  ~meth:(Eliom_service.Post (Eliom_parameter.unit, Eliom_parameter.unit))
  ()

let disconnect_box () = Eliom_content.Html.D.(
  Form.post_form disconnection_service
    (fun _ ->
      [fieldset [Form.input ~input_type:`Submit ~value:"Log out" Form.string]]
    )
    ()
)

let () =
  Eliom_registration.Action.register
    ~service:disconnection_service
    (fun () () -> Eliom_state.discard ~scope:Eliom_common.default_session_scope ())

Then add this form in the connection box:

let connection_box () =
  let%lwt u = Eliom_reference.get username in
  Lwt.return
    (match u with
      | Some s -> div [p [txt "You are connected as "; txt s; ];
                       disconnect_box () ]
      | None -> ...

Registration of users

Basic registration form

We now add a registration form to the application. We create a new regular service, attached to the path /registration, that displays a registration form, and an action that will add the user to the "database":

let new_user_form_service = Eliom_service.create
  ~path:(Eliom_service.Path ["registration"])
  ~meth:(Eliom_service.Get Eliom_parameter.unit)
  ()

let create_account_service = Eliom_service.create_attached_post
  ~fallback:main_service
  ~post_params:(Eliom_parameter.(string "name" ** string "password"))
  ()

let account_form () = Eliom_content.Html.D.(
  Form.post_form ~service:create_account_service
    (fun (name1, name2) ->
      [fieldset
         [label [txt "login: "];
          Form.input ~input_type:`Text ~name:name1 Form.string;
          br ();
          label [txt "password: "];
          Form.input ~input_type:`Password ~name:name2 Form.string;
          br ();
          Form.input ~input_type:`Submit ~value:"Connect" Form.string
         ]]) ()
)

let _ = Eliom_content.Html.D.(
  Eliom_registration.Html.register
    ~service:new_user_form_service
    (fun () () ->
      Lwt.return
        (html (head (title (txt "")) [])
              (body [h1 [txt "Create an account"];
                     account_form ();
                    ])));

  Eliom_registration.Action.register
    ~service:create_account_service
    (fun () (name, pwd) ->
      users := (name, pwd)::!users;
      Lwt.return ())
)

Then add the link to this service in the connection box:

let connection_box () = Eliom_content.Html.D.(
  let%lwt u = Eliom_reference.get username in
  Lwt.return
    (match u with
      | Some s -> div [p [txt "You are connected as "; txt s; ];
                       disconnect_box () ]
      | None ->
        div [Form.post_form ~service:connection_service
                (fun (name1, name2) ->
...
                ) ();
             p [a new_user_form_service
                  [txt "Create an account"] ()]]
            )
)

It looks great, but if we refresh the page after creating an account, we can see there is a problem. We are creating the same account over and over again. This is because we are calling the create_account_service each time we refresh the page, obviously we don't want that. To solve this issue we will implement a dynamically created and registered service with limited lifespan and number of uses.

Registration form with confirmation

Now we want to add a confirmation page before actually creating the account. We replace the service create_account_service by a new POST attached coservice called account_confirmation_service:

let account_confirmation_service =
  Eliom_service.create_attached_post
    ~fallback:new_user_form_service
    ~post_params:(Eliom_parameter.(string "name" **  string "password"))
    ()

and we make the account creation form point at this new service.

We register an HTML handler on this service, with the confirmation page. As a side effect, this page will create the actual account creation service:

Eliom_registration.Html.register
    ~service:account_confirmation_service
    (fun () (name, pwd) ->
      let create_account_service =
	Eliom_service.create_attached_get
          ~fallback:main_service
          ~get_params:Eliom_parameter.unit
          ~timeout:60.
	  ~max_use:1
	  ()
      in
      let _ = Eliom_registration.Action.register
	~service:create_account_service
        (fun () () ->
          users := (name, pwd)::!users;
          Lwt.return ())
      in
      Lwt.return
	(html
           (head (title (txt "")) [])
           (body
              [h1 [txt "Confirm account creation for "; txt name];
               p [a ~service:create_account_service [txt "Yes"] ();
                  txt " ";
                  a ~service:main_service [txt "No"] ()]
              ])));

Also remove the registration of the create_account_service service and modify the user creation form to make it points towards account_confirmation_service.

We created dynamically a service with a limited lifespan as specified by the ?timeout parameter and a limited number of uses of this service defined by the ?max_use parameter. Now if we refresh the page after creating the account, it works as intended.

A few enhancements

Displaying a "wrong password" message

In the current version, our web site fails silently when the password is wrong. Let's improve this behavior by displaying an error message. To do that, we need to pass information to the service occurring after the action. We record this information in an Eliom reference with scope Eliom_common.request_scope.

Define an Eliom reference:

let wrong_pwd =
  Eliom_reference.eref ~scope:Eliom_common.request_scope false

Modify the connection box this way:

let connection_box () = Eliom_content.Html.D.(
  let%lwt u = Eliom_reference.get username in
  let%lwt wp = Eliom_reference.get wrong_pwd in
  Lwt.return
    (match u with
      | Some s -> div [p [txt "You are connected as "; txt s; ];
                       disconnect_box () ]
      | None ->
        let l =
          [Form.post_form ~service:connection_service
            (fun (name1, name2) ->
              [fieldset
	         [label [txt "login: "];
                  Form.input ~input_type:`Text ~name:name1 Form.string;
                  br ();
                  label [txt "password: "];
                  Form.input ~input_type:`Password ~name:name2 Form.string;
                  br ();
                  Form.input ~input_type:`Submit ~value:"Connect" Form.string
                 ]]) ();
             p [a new_user_form_service
                  [txt "Create an account"] ()]]
        in
        if wp
        then div ((p [em [txt "Wrong user or password"]])::l)
        else div l
    )
)

... and modify the connection_service handler:

Eliom_registration.Action.register
    ~service:connection_service
    (fun () (name, password) ->
      if check_pwd name password
      then Eliom_reference.set username (Some name)
      else Eliom_reference.set wrong_pwd true);

Sending 404 errors for non-existing users

Our service user_service responds to any request parameter, even if the user does not exist in the database. We want to check that the user is in the database before displaying the page, and send a 404 error if the user is not. To do that, we will replace module Eliom_registration.Html by Eliom_registration.Any to register the service user_service:

Eliom_registration.Any.register
    ~service:user_service
    (fun name () ->
      if List.mem_assoc name !users then
	begin
	  let%lwt cf = connection_box () in
	  Eliom_registration.Html.send
            (html (head (title (txt name)) [])
               (body [h1 [txt name];
                      cf;
                      p [a ~service:main_service [txt "Home"] ()]]))
	end
      else
	Eliom_registration.Html.send
          ~code:404
          (html (head (title (txt "404")) [])
             (body [h1 [txt "404"];
                    p [txt "That page does not exist"]]))
    );

Wrapping the server handler to easily get the user data

When you want to assume that you have informations available in sessions, for instance when a site is mainly available to connected users, it becomes tedious to check everywhere that a reference is not None. A simple way to distinguish authenticated and anonymous requests lies in the usage of Eliom_tools.wrap_handler. It allows to provide two handler functions, one is called if a certain information is not made available by the first argument, the other is called when that information is available.

let authenticated_handler f = Eliom_content.Html.D.(
  let handle_anonymous _get _post =
    let connection_box =
      Form.post_form ~service:connection_service
        (fun (name1, name2) ->
	  [fieldset
              [label [txt "login: "];
               Form.input ~input_type:`Text ~name:name1 Form.string;
               br ();
               label [txt "password: "];
               Form.input ~input_type:`Password ~name:name2 Form.string;
               br ();
               Form.input ~input_type:`Submit ~value:"Connect" Form.string
              ]]) ()
    in
    Lwt.return
      (html
        (head (title (txt "")) [])
        (body [h1 [txt "Please connect"];
	       connection_box;]))
    in
    Eliom_tools.wrap_handler
      (fun () -> Eliom_reference.get username)
      handle_anonymous (* Called when [username] is [None] *)
      f (* Called [username] contains something *)
)

let () = Eliom_content.Html.D.(
  Eliom_registration.Html.register ~service:main_service
    (authenticated_handler
       (fun username _get _post ->
       	 Lwt.return
           (html
              (head (title (txt "")) [])
              (body [h1 [txt ("Hello " ^ username) ]]))))
)

prev next