# Path: radarpost/cli.py
# COMMANDLINE_PLUGIN = 'radarpost.cli.command'
# 
# class BasicCommand(object):
#     """
#     Helper base class for Commands.
#     
#     subclasses should override as needed and
#     must implement
#     
#     command_name = <name used at command line>  
#     description = <brief description of command>
#     __call__(...): # perform the command
#     """
#     def __init__(self, config):
#         self.config = config
#     
#     def print_usage(self):
#         parser = get_basic_option_parser()
#         parser.set_usage(r"%prog " + "%s [options]" % self.command_name)
#         self.setup_options(parser)
#         print "\n%s: %s" % (self.command_name, self.description)
#         parser.print_help()
# 
#     @classmethod
#     def setup_options(cls, parser):
#         """
#         may be overridden by subclasses to provide additional 
#         command line arguments like --foo etc.
#         """
#         pass
#         
#     def clean_options(self, options):
#         kw = dict(options.__dict__)
#         del kw['config_filenames']
#         del kw['log_file']
#         return kw
#         
#     def run(self, args, options):
#         kw = self.clean_options(options)
#         try:
#             self(*args, **kw)
#         except TypeError:
#             self.print_usage()
# 
# def get_basic_option_parser():
#     parser = OptionParser(add_help_option=False)
#     parser.set_usage(r"%prog " + "<command> [options]")
#     parser.add_option('-C', action="append",
#                       type="string", dest="config_filenames",
#                       help="specify configuration files.  May be specified multipe times for overrides.",
#                       default=[])
#     parser.add_option('--log', type="string", dest="log_file", default=None, 
#                       help="log output to the file specified.")
#     return parser
# 
# Path: radarpost/plugins.py
# ENTRY_POINT = 'radarpost_plugins'
# def get(slot):
# def _get(slot):
# def register(thing, slot):
# def plugin(slot):
#     def dd(thing):
# def _search():
# 
# Path: radarpost/user.py
# class User(Document):
#     """
#     This is a representation of a 'standard' couchdb user
#     document.  Creating one of these in the couchdb users
#     database (usually _users) adds a database user.  They 
#     can be created elsewhere if database level access is 
#     not desirable.
#     
#     See http://wiki.apache.org/couchdb/Security_Features_Overview
#     
#     """
#     def __init__(self, username=None, password=None):
#         """
#         User may be initialized with the special keyword arguments
#         username and password for creating a new User:
#         
#         u = User(username=joe, password="bl0w")
#         """
#         Document.__init__(self)
# 
#         if 'username' is not None: 
#             self.id = 'org.couchdb.user:%s' % username
#             self['name'] = username
#     
#         if password is not None:
#             self.set_password(password)
#         else: 
#             self.lock_password()
# 
#     @classmethod
#     def get_by_username(cls, db, username):
#         natid = 'org.couchdb.user:%s' % username
#         return cls.load(db, natid)
# 
#     @property
#     def username(self):
#         return self['name']
# 
#     def get_public_id(self):
#         # same for now.
#         return self.username
# 
#     type = TextField(default="user")
#     roles = ListField(TextField)
#     password_sha = TextField()
#     salt = TextField()
# 
#     def set_password(self, plaintext_password):
#         self.salt = _generate_salt()
#         self.password_sha = _password_hash(plaintext_password, self.salt)
# 
#     def lock_password(self):
#         self.password_sha = LOCKED_PASSWORD
#         
#     def check_password(self, plaintext_password):
#         if self.password_sha == LOCKED_PASSWORD:
#             return False
#         hashed_pw = _password_hash(plaintext_password, self.salt)
#         return self.password_sha == hashed_pw
# 
#     def is_anonymous(self):
#         return False
# 
#     def has_role(self, role, obj=None):
#         return role in self.roles
# 
#     def has_perm(self, perm, obj=None):
#         if self.has_role(ROLE_ADMIN):
#             return True
#         if perm == PERM_READ:
#             return True
#         return False
# 
# ROLE_ADMIN = 'radar:role:admin'


from couchdb import Server, ResourceNotFound
from radarpost.cli import COMMANDLINE_PLUGIN, BasicCommand, get_basic_option_parser
from radarpost import plugins
from radarpost.user import User, ROLE_ADMIN
from getpass import getpass
        """
        Create a user with the given username. 
        is_locked - if True, create with a locked password
        is_admin  - if True, grant administrative rights to the user
        """
        couchdb = Server(self.config['couchdb.address'])
        try:
            udb = couchdb[self.config['couchdb.users_database']]
        except: 
            print "Failed to connect to couchdb at %s/%s" % (self.config['couchdb.address'], 
                                                             self.config['couchdb.users_database'])
            return 1
            
        new_user = User(username=username)
        if new_user.id in udb: 
            print 'User "%s" already exists' % username
            return 1
        
        if not is_locked:
            done = False
            while(not done):
                password = getpass(prompt="Password for %s: " % username)
                password2 = getpass(prompt="Repeat password: ")
                if password == password2: 
                    done = True
                else: 
                    print "Passwords did not match, try again.\n"        
            new_user.set_password(password)

        if is_admin:

# Path: radarpost/cli.py
# COMMANDLINE_PLUGIN = 'radarpost.cli.command'
# 
# class BasicCommand(object):
#     """
#     Helper base class for Commands.
#     
#     subclasses should override as needed and
#     must implement
#     
#     command_name = <name used at command line>  
#     description = <brief description of command>
#     __call__(...): # perform the command
#     """
#     def __init__(self, config):
#         self.config = config
#     
#     def print_usage(self):
#         parser = get_basic_option_parser()
#         parser.set_usage(r"%prog " + "%s [options]" % self.command_name)
#         self.setup_options(parser)
#         print "\n%s: %s" % (self.command_name, self.description)
#         parser.print_help()
# 
#     @classmethod
#     def setup_options(cls, parser):
#         """
#         may be overridden by subclasses to provide additional 
#         command line arguments like --foo etc.
#         """
#         pass
#         
#     def clean_options(self, options):
#         kw = dict(options.__dict__)
#         del kw['config_filenames']
#         del kw['log_file']
#         return kw
#         
#     def run(self, args, options):
#         kw = self.clean_options(options)
#         try:
#             self(*args, **kw)
#         except TypeError:
#             self.print_usage()
# 
# def get_basic_option_parser():
#     parser = OptionParser(add_help_option=False)
#     parser.set_usage(r"%prog " + "<command> [options]")
#     parser.add_option('-C', action="append",
#                       type="string", dest="config_filenames",
#                       help="specify configuration files.  May be specified multipe times for overrides.",
#                       default=[])
#     parser.add_option('--log', type="string", dest="log_file", default=None, 
#                       help="log output to the file specified.")
#     return parser
# 
# Path: radarpost/plugins.py
# ENTRY_POINT = 'radarpost_plugins'
# def get(slot):
# def _get(slot):
# def register(thing, slot):
# def plugin(slot):
#     def dd(thing):
# def _search():
# 
# Path: radarpost/user.py
# class User(Document):
#     """
#     This is a representation of a 'standard' couchdb user
#     document.  Creating one of these in the couchdb users
#     database (usually _users) adds a database user.  They 
#     can be created elsewhere if database level access is 
#     not desirable.
#     
#     See http://wiki.apache.org/couchdb/Security_Features_Overview
#     
#     """
#     def __init__(self, username=None, password=None):
#         """
#         User may be initialized with the special keyword arguments
#         username and password for creating a new User:
#         
#         u = User(username=joe, password="bl0w")
#         """
#         Document.__init__(self)
# 
#         if 'username' is not None: 
#             self.id = 'org.couchdb.user:%s' % username
#             self['name'] = username
#     
#         if password is not None:
#             self.set_password(password)
#         else: 
#             self.lock_password()
# 
#     @classmethod
#     def get_by_username(cls, db, username):
#         natid = 'org.couchdb.user:%s' % username
#         return cls.load(db, natid)
# 
#     @property
#     def username(self):
#         return self['name']
# 
#     def get_public_id(self):
#         # same for now.
#         return self.username
# 
#     type = TextField(default="user")
#     roles = ListField(TextField)
#     password_sha = TextField()
#     salt = TextField()
# 
#     def set_password(self, plaintext_password):
#         self.salt = _generate_salt()
#         self.password_sha = _password_hash(plaintext_password, self.salt)
# 
#     def lock_password(self):
#         self.password_sha = LOCKED_PASSWORD
#         
#     def check_password(self, plaintext_password):
#         if self.password_sha == LOCKED_PASSWORD:
#             return False
#         hashed_pw = _password_hash(plaintext_password, self.salt)
#         return self.password_sha == hashed_pw
# 
#     def is_anonymous(self):
#         return False
# 
#     def has_role(self, role, obj=None):
#         return role in self.roles
# 
#     def has_perm(self, perm, obj=None):
#         if self.has_role(ROLE_ADMIN):
#             return True
#         if perm == PERM_READ:
#             return True
#         return False
# 
# ROLE_ADMIN = 'radar:role:admin'


# Path: radarpost/commands/useradmin.py
from couchdb import Server, ResourceNotFound
from radarpost.cli import COMMANDLINE_PLUGIN, BasicCommand, get_basic_option_parser
from radarpost import plugins
from radarpost.user import User, ROLE_ADMIN
from getpass import getpass

        """
        Create a user with the given username. 
        is_locked - if True, create with a locked password
        is_admin  - if True, grant administrative rights to the user
        """
        couchdb = Server(self.config['couchdb.address'])
        try:
            udb = couchdb[self.config['couchdb.users_database']]
        except: 
            print "Failed to connect to couchdb at %s/%s" % (self.config['couchdb.address'], 
                                                             self.config['couchdb.users_database'])
            return 1
            
        new_user = User(username=username)
        if new_user.id in udb: 
            print 'User "%s" already exists' % username
            return 1
        
        if not is_locked:
            done = False
            while(not done):
                password = getpass(prompt="Password for %s: " % username)
                password2 = getpass(prompt="Repeat password: ")
                if password == password2: 
                    done = True
                else: 
                    print "Passwords did not match, try again.\n"        
            new_user.set_password(password)

        if is_admin:

            new_user.roles = [ROLE_ADMIN]