This is a continuation of two past posts (one, two) on my first application with Opa called OpaDo. You can try the live demo here and check out the full source code on Github

Updating OpaDo to add user accounts the project structure has been changed a bit and modularized. Below is the new project layout.

opado/  
├── Makefile  
├── README.md  
├── dotcloud.yml  
├── resources  
│   ├── destroy.png  
│   └── todos.css  
└── src  
    ├── main.opa  
    ├── todo.opa  
    └── user.opa

Now there is a main, todo and user module. The main module is the entry point for the app and looks like:

package opado.main  

import opado.user  
import opado.todo  

urls : Parser.general_parser(http_request -> resource) =  
  parser  
  | {Rule.debug_parse_string(s -> Log.notice("URL",s))} Rule.fail -> error("")  
  | "/todos" result={Todo.resource} -> result  
  | "/user" result={User.resource} -> result  
  | "/login" result={User.resource} -> result  
  | (.*) result={Todo.resource} -> result  

server = Server.of_bundle([@static_resource_directory("resources")])  
server = Server.make(urls)

Here we define the name of this package and import the user and todo modules. Next is the url matching code. urls is a parser that takes an HTTP request and returns a resource. The matching is pretty straight forward. For example:

  | "/todos" result={Todo.resource} -> result

Here we are matching on URLs that begin with /todos but could have anything after that. What is contained after /todos is passed to the Todo.resource which the variable result is set to. And finally that result is returned.

The last two lines simple define the reource directory for the server and pass in the matching function for the HTTP requests.

The todo resource isn't important to us in this post since its hardly changed. But there are a two important changes:

db /todo_items : stringmap(stringmap(todo_item))  
db /todo_items[_][_]/done = false

Here we see that the /todoitems_ database is not longer simply a stringmap of todoitem's but a _stringmap of a that. This is so we can reference the items by a user identifier. For example a user identified by the string "user01" who has a todo item identified by "aaa" would be read from the data base as /todo["user01"]["aaa"].

There are a few other changes to the todo module so that items are properly inserted for the logged in user and deleting must be done in the second stringmap. But we'll move on to the user module now.

Much of the user module was taken from Matthieu Guffroy's OpaCMS code on github. But I've made a number of modification for my needs.

@abstract type User.password = string  
@abstract type User.ref = string  

type User.t =  
  {  
    username : string  
    fullname : string  
    password : User.password  
  }  

type User.status = { logged : User.ref } / { unlogged }  
type User.info = UserContext.t(User.status)  
type User.map('a) = ordered_map(User.ref, 'a, String.order)  

db /users : User.map(User.t)  

User_data = {{  
  mk_ref( login : string ) : User.ref =  
    String.to_lower(login)  

  ref_to_string( login : User.ref ) : string =  
    login  

  save( ref : User.ref, user : User.t ) : void =  
    /users[ref] <- user  

  get( ref : User.ref ) : option(User.t) =  
    ?/users[ref]  
}}

Above we have the data, types and database definitions necessary to handle the users.

User.t provides the record for storing necessary user data. Next, we have types for checking the user status of if they are logged in or not.

UserContext is a module provided by Opa for dealing with associating the user values with the client -- via cookies. And the data for that user can only accessed by the user that owns it.

Userdata_ object provides functions for accessing and manipulating users.

Now we can look at the User module.

User = {{  

  @private state = UserContext.make({ unlogged } : User.status)  

  create(username, password) =  
    do match ?/users[username] with  
      | {none} ->  
          user : User.t =  
            { username=username ;  
              fullname="" ;  
              password = Crypto.Hash.sha2(password) }  
          /users[username] <- user  

      | _ -> void  
    Client.goto("/login")

At the beginning of the User object we declare a UserContext and a function for creating new users. The function simply checks if the user exists already with the match statement and if not creates a new User.t record and inserts it to the users database.

If we wish to login we must also modify the UserContext

  login(login, password) =  
    useref = User_data.mk_ref(login)  
    user = User_data.get(useref)  
    do match user with  
     | {some = u} -> if u.password == Crypto.Hash.sha2(password) then  
                       UserContext.change(( _ -> { logged = User_data.mk_ref(login) }), state)  
     | _ -> void  
    Client.goto("/todos")

The function attempts to read the user from the database and checks if the passwords match. If so, it will set the UserContext to logged in. The function then tells the client to go to /todos. If the login was unsuccessful, it doesn't matter and will just redirect to the sign up page.

Obviously, better error handling and notification is the next step for the application.

The last interesting part for this I think is the request matching. The rest of the code is mostly just HTML and piecing together the functions I already described.

  resource : Parser.general_parser(http_request -> resource) =  
    parser  
    | "/new" ->  
      _req -> Resource.styled_page("New User", ["/resources/todos.css"], new())  
    | "/edit" ->  
      _req -> edit()  
    | "/view/" login=(.*) ->  
      _req -> view(Text.to_string(login))  
    | .* ->  
      _req -> start()

The key match to look at is:

    | "/view/" login=(.*) ->  
      _req -> view(Text.to_string(login))

This shows the request matching /view, which in this case comes after the main module matches '/user' and routes to the User module resource. But then we have login=(.*), this is matching the variable login to the rest of the url. This variable login can then be used in view(Text.tostring(login))_ to pass to the view function so it knows what user is being asked to be displayed.

There'll be more to come. Next, I need to add some validation, an admin page and then the ability for users to have categories to organize their todo items under.

And let me know anything else people would like to see!