def addUser(self, user_details):
     if not ('username' in user_details and user_details['username'] and \
             'password' in user_details and user_details['password'] and \
            ('name' in user_details and user_details['name'] or \
            ('firstname' in user_details and user_details['firstname'] and \
            'lastname' in user_details and user_details['lastname']))):
         return False
     add_user(user_details)
     return True
    def add_user(self, username, password, name=None, firstname=None, lastname=None, email=None, membership=[]):
        # groups = [(silo1, role1),(silo2, role2)]
        #add user
        user_details = {
        'username':u'%s'%username,
        'password':u"%s"%password
        }
        if name and name.strip():
            user_details['name'] = name.strip()
        if firstname and firstname.strip():
            user_details['firstname'] = firstname.strip()
        if lastname and lastname.strip():
            user_details['lastname'] = lastname.strip()
        if email and email.strip():
            user_details['email'] = email.strip()

        #print user_details
        #print membership
        add_user(user_details)
        if membership:
            #Add user membership
            add_user_groups(username, membership)
        return
    def index(self):
        if not request.environ.get('repoze.who.identity'):
            abort(401, "Not Authorised")
        ident = request.environ.get('repoze.who.identity')
        if not ('administrator' in ident['permissions'] or 'manager' in ident['permissions']):
            abort(403, "Do not have administrator or manager credentials")

        c.ident = ident
        #silos = ag.authz(ident, permission=['administrator', 'manager'])
        c.users = list_users()
        if 'administrator' in ident['permissions']:
            c.roles = ["admin", "manager", "user"]
        else:
            c.roles = ["manager", "user"]
        
        http_method = request.environ['REQUEST_METHOD']
        
        if http_method == "GET":
            accept_list = None
            if 'HTTP_ACCEPT' in request.environ:
                try:
                    accept_list = conneg_parse(request.environ['HTTP_ACCEPT'])
                except:
                    accept_list= [MT("text", "html")]
            if not accept_list:
                accept_list= [MT("text", "html")]
            mimetype = accept_list.pop(0)
            while(mimetype):
                if str(mimetype).lower() in ["text/html", "text/xhtml"]:
                    return render("/users.html")
                elif str(mimetype).lower() in ["text/plain", "application/json"]:
                    response.content_type = 'application/json; charset="UTF-8"'
                    response.status_int = 200
                    response.status = "200 OK"
                    return simplejson.dumps(c.users)
                try:
                    mimetype = accept_list.pop(0)
                except IndexError:
                    mimetype = None
            #Whoops nothing satisfies - return text/plain
            response.content_type = 'application/json; charset="UTF-8"'
            response.status_int = 200
            response.status = "200 OK"
            return simplejson.dumps(c.users)
        elif http_method == "POST":
            params = request.POST
            if not ('username' in params and params['username'] and 'password' in params and params['password']):
                abort(400, "username and password not supplied")
            if not allowable_id2(params['username']):
                response.content_type = "text/plain"
                response.status_int = 400
                response.status = "400 Bad request. Username not valid"
                return "username can contain only the following characters - %s and has to be more than 1 character"%ag.naming_rule_humanized

            existing_users = list_usernames()
            if params['username'] in existing_users:
                abort(403, "User exists")
            if (('firstname' in params and params['firstname'] and 'lastname' in params and params['lastname']) \
                or 'name' in params and params['name']):
                add_user(params)
            else:   
                abort(400, "The following parameters have to be supplied: username, pasword and name (or firstname and lastname)")
            response.status_int = 201
            response.status = "201 Created"
            response.headers['Content-Location'] = url(controller="users", action="userview", username=params['username'])
            response_message = "201 Created"

            if 'HTTP_ACCEPT' in request.environ:
                try:
                    accept_list = conneg_parse(request.environ['HTTP_ACCEPT'])
                except:
                    accept_list= [MT("text", "html")]
            if not accept_list:
                accept_list= [MT("text", "html")]
            mimetype = accept_list.pop(0)
            while(mimetype):
                if str(mimetype).lower() in ["text/html", "text/xhtml"]:
                    redirect(url(controller="users", action="userview", username=params['username']))
                elif str(mimetype).lower() in ["text/plain", "application/json"]:
                    response.content_type = "text/plain"
                    return response_message
                try:
                    mimetype = accept_list.pop(0)
                except IndexError:
                    mimetype = None
            # Whoops - nothing satisfies - return text/plain
            response.content_type = "text/plain"
            return response_message
    #Initialize sqlalchemy
    f = '/var/lib/databank/production.ini' 
    if not os.path.exists(f):
        print "Config file not found"
        sys.exit()
    c = ConfigParser.ConfigParser()
    c.read(f)
    if not 'app:main' in c.sections():
        print "Section app:main not found in config file"
        sys.exit()

    engine = sa.create_engine(c.get('app:main', 'sqlalchemy.url'))
    init_model(engine)

    #add user
    username = sys.argv[1]
    password = sys.argv[2]
    email = sys.argv[3]
    user_details = {
        'username':u'%s'%username,
        'password':u"%s"%password,
        'name':u'Databank Administrator',
        'email':u"%s"%email
    }
    add_user(user_details)
    #Add user membership
    groups = []
    groups.append(('*', 'administrator'))
    add_user_groups(username, groups)