Example #1
0
 def create_server(self):
    # signal the controller on this metadata server's host to create this server
    self['status'] = 'stopped'
    server = self.api.connect_mdctl( self['host'] )
    
    import SMDS.user
    
    # get our users
    if self.get('user_ids') == None:
       self['user_ids'] = []
    
    user_ids = self['user_ids']
    users = []
    if user_ids:
       users = SMDS.user.Users( self.api, user_ids )
    
    logger.info("Creating metadata server '%s' with users '%s'" % (self['name'], [user['username'] for user in users]))
    
    rc = 0
    try:
       as_dict = {}
       as_dict.update( self )
       
       user_dicts = []
       for user in users:
          user_dict = {}
          user_dict.update( user )
          user_dicts.append( user_dict )
          
       rc = server.create_server( as_dict, user_dicts )
    except Exception, e:
       logger.exception( e, "Could not restart metadata server")
       rc = -500
Example #2
0
 def restart_server(self, force_start=True ):
    # signal the controller on this metadata server's host to restart this metadata server.
    # the state of the server (running/stopped) should not change, except on error
    
    server = self.api.connect_mdctl( self['host'] )
    
    import SMDS.user 
    
    # get our users
    user_ids = self['user_ids']
    users = []
    if user_ids:
       users = SMDS.user.Users( self.api, user_ids )
    
    
    logger.info("Restarting metadata server '%s' with users '%s'" % (self['name'], [user['username'] for user in users]))
    
    rc = 0
    try:
       as_dict = {}
       as_dict.update( self )
       
       user_dicts = []
       for user in users:
          user_dict = {}
          user_dict.update( user )
          user_dicts.append( user_dict )
          
       rc = server.restart_server( as_dict, user_dicts, force_start )
    except Exception, e:
       logger.exception( e, "Could not restart metadata server")
       rc = -500
       self['status'] = 'stopped'
       self.sync()
Example #3
0
 def __init__(self, config = "/etc/syndicate/syndicate-metadata-service.conf", encoding = "utf-8"):
     self.config = Config(config)
     
     CDN_inst = None
     try:
        cdn_interface = __import__("SMDS.API.CDN." + self.config.MD_CDN_INTERFACE, fromlist=["SMDS"])
        logger.info("Using CDN driver %s" % cdn_interface.__name__)
        CDN_inst = cdn_interface.CDNDriver()
     except Exception, e:
        traceback.print_exc()
        CDN_inst = PL_CoBlitz()
Example #4
0
 def destroy_server(self):
    # signal the controller on this metadata server's host to destroy this server
    self['status'] = 'stopped'
    server = self.api.connect_mdctl( self['host'] )
    
    logger.info("Destroying metadata server '%s'" % self['name'])
    
    rc = 0
    try:
       as_dict = {}
       as_dict.update( self )
       rc = server.destroy_server( as_dict )
    except Exception, e:
       logger.exception( e, "Could not restart metadata server")
       rc = -500
Example #5
0
 def start_server(self):
    # signal the controller on this metadata server's host to start this metadata server
    old_status = self['status']
    self['status'] = 'running'
    
    server = self.api.connect_mdctl( self['host'] )
    
    logger.info("Starting metadata server '%s'" % self['name'])
    
    ret = None
    try:
       as_dict = {}
       as_dict.update( self )
       ret = server.start_server( as_dict )
    except Exception, e:
       logger.exception( e, "Could not start metadata server")
       ret = None
Example #6
0
   def logout(self, next=DEFAULT, onlogout=DEFAULT, log=DEFAULT):
      """
      Handle a logout
      """
      
      session = current.session
      user = None
      if session.auth:
         user = session.auth['user']
         self.user = user
      
      if log:
         if user:
            logger.info("SMDS_Auth: User '%s' logged out" % user['username'])
            logger.flush()
      
      next = self.settings.logout_next

      #super(SMDS_Auth, self).logout( lambda x: redirect(self.url('index')), lambda x, log )
      
      if next == DEFAULT:
         next = self.settings.logout_next
      """
      if onlogout == DEFAULT:
         onlogout = self.settings.logout_onlogout
      if onlogout:
         onlogout(self.user)
      if log == DEFAULT:
         log = self.messages.logout_log
      if log and self.user:
         self.log_event(log % self.user)
      
      if self.settings.login_form != self:
         cas = self.settings.login_form
         cas_user = cas.get_user()
         if cas_user:
            next = cas.logout_url(next)
      """
      current.session.auth = None
      current.session.flash = self.messages.logged_out
      if next:
         redirect(next)
Example #7
0
 def stop_server(self):
    # signal the controller on this metadata server's host to stop this metadata server
    old_status = self['status']
    self['status'] = 'stopped'
    
    server = self.api.connect_mdctl( self['host'] )
    
    logger.info("Stopping metadata server '%s'" % self['name'])
    
    rc = 0
    try:
       as_dict = {}
       as_dict.update( self )
       rc = server.stop_server( as_dict )
       if rc == 0:
          logger.warn( "Server '%s' was not running" % self['name'])
          rc = 1      # it's OK if it wasn't running
          
    except Exception, e:
       logger.exception( e, "Could not stop metadata server")
       rc = -500;
Example #8
0
   def login(self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT):
      """
      Handle a login request, and redirect.
      """
      request = current.request
      response = current.response
      session = current.session
      
      username_field = self.settings.login_userfield
      password_field = self.settings.password_field
      
      if next == DEFAULT:
         next = request.get_vars._next \
            or request.post_vars._next \
            or self.settings.login_next
                
      if onvalidation == DEFAULT:
         onvalidation = self.settings.login_onvalidation
      if onaccept == DEFAULT:
         onaccept = self.settings.login_onaccept
      if log == DEFAULT:
         log = self.messages.login_log
      
      user = None
      accepted_form = False
      
      if self.settings.login_form == self:
         # this object was responsible for logging in
         form =FORM(                                                                          \
                     TABLE(                                                                   \
                        TR(TD('Username:'), TD(INPUT(_name="username",_type="text",requires=IS_SLUG(error_message="Invalid Username")))),        \
                        TR(TD('Password:'), TD(INPUT(_name="password", _type="password")))    \
                     ),                                                                       \
                     INPUT(_type="Submit",_value="Login"),                                    \
                     _name="login"
               )
            

         if form.accepts(request.vars, session,
                         formname='login',
                         onvalidation=onvalidation,
                         hideerror=self.settings.hideerror):
            
            # sanitize inputs
            
            accepted_form = True
            
            # check for username in db
            username = form.vars[username_field]
            user = None
            try:
               user = Users( self.api, {'username': username} )[0]
            except:
               pass
               
            if user:
               # user in db, check if registration pending or disabled
               temp_user = user
               if temp_user['enabled'] == False:
                  # user is not yet enabled
                  response.flash = self.messages.login_disabled
                  return form
                  
               # check password
               try:
                  rc = auth_password_check( self.api, {'Username':user['username'], 'AuthMethod':'password', 'AuthString':form.vars[password_field]}, user, None )
               except:
                  if log:
                     logger.error("SMDS_Auth: User '%s' authentication failed (invalid credentials)" % user['username'] )
                     logger.flush()
                     
                  user = None   # invalid credentials
               
            if not user:
               if log:
                  logger.error("SMDS_Auth: User could not be looked up" )
                  logger.flush()
                  
               # invalid login
               session.flash = self.messages.invalid_login
               redirect(self.url(args=request.args,vars=request.get_vars))

      if user:
         user_public = user.public()
         user_stored = Storage(user_public)

         if log:
            logger.info("SMDS_Auth: User '%s' logged in" % user_public['username'])

         # process authenticated users
         # user wants to be logged in for longer
         session.auth = Storage(
               user = user_stored,
               last_visit = request.now,
               expiration = self.settings.long_expiration,
               remember = request.vars.has_key("remember"),
               hmac_key = web2py_uuid()
               )

         self.user = user_public
         logger.info("SMDS_Auth: user_id = %s" % self.user_id)
         logger.flush()
         
         session.flash = self.messages.logged_in

      # how to continue
      if self.settings.login_form == self:
         if accepted_form:
            callback(onaccept,form)
            if isinstance(next, (list, tuple)):
               # fix issue with 2.6
               next = next[0]
            if next and not next[0] == '/' and next[:4] != 'http':
               next = self.url(next.replace('[id]', str(form.vars.id)))
            
            redirect(next)
         
         return form
      elif user:
         callback(onaccept,None)
      
      redirect(next)
Example #9
0
   def register(self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT):
      """
      Register a new user
      """
      
      request = current.request
      response = current.response
      session = current.session
      
      if self.is_logged_in():
         # don't allow registration if we're already logged in
         redirect(self.settings.logged_url)
      
      # fill in defaults
      if next == DEFAULT:
         next = request.get_vars._next \
               or request.post_vars._next \
               or self.settings.register_next
      if onvalidation == DEFAULT:
         onvalidation = self.settings.register_onvalidation
      if onaccept == DEFAULT:
         onaccept = self.settings.register_onaccept
      if log == DEFAULT:
         log = self.messages.register_log

      # create a form...
      userfield = self.settings.login_userfield
      passfield = self.settings.password_field
      formstyle = self.settings.formstyle
      form =FORM(                                                                             \
                     TABLE(                                                                   \
                        TR(TD('Username:'),         TD(INPUT(_name="username",_type="text",requires=IS_SLUG(error_message="Invalid username")))),        \
                        TR(TD('Email:'),            TD(INPUT(_name="email", _type="text",requires=IS_EMAIL(error_message=self.messages.invalid_email)))),          \
                        TR(TD('Password:'),         TD(INPUT(_name="password", _type="password"))),    \
                        TR(TD('Re-type Password:'), TD(INPUT(_name="password2", _type="password",                         \
                                                       requires=IS_EXPR("value==%s" % repr(request.vars.get('password',None))),                   \
                                                       error_message=self.settings.mismatched_password)))    \
                     ),                                                                       \
                     INPUT(_type="Submit",_value="Register"),                                    \
                     _name="register"
               )
            

      if form.accepts(request, session, formname='register', onvalidation=onvalidation,hideerror=self.settings.hideerror):
         
         # verify that the password forms are the same
         if form.vars['password'] != form.vars['password2']:
            response.flash = messages.mismatched_password
            
         # inform the admin
         """
         if not self.settings.mailer or \
            not self.settings.mailer.send(
               to=self.maint_email,
               subject=self.messages.verify_email_subject,
               message=self.messages.verify_email % dict(username=form.vars['username'], email=form.vars['email'])):
                     
            response.flash = self.messages.unable_send_email
            return form
            
         session.flash = self.messages.email_sent
         """
         
         # make sure this user does not exist
         rc = 0
         msg = ""
         try:
            user = Users(self.api, {'username': form.vars['username']})[0]
            rc = -1     # already exists
            msg = "User already exists"
         except:
            pass
            
         # create the user
         if rc == 0:
            try:
               user_fields = {'username': form.vars['username'], 'password': form.vars['password'], 'email': form.vars['email']}
               rc = self.api.call( ("127.0.0.1", "localhost"), "AddUser", self.api.maint_auth, user_fields )
            except Exception, e:
               logger.exception(e, "register: exception")
               logger.flush()
               msg = "User could not be registered"
               rc = -1
         
         if rc < 0:
            response.flash = msg
            logger.error("Failed to add user '%s' (email '%s')" % (user_fields['username'], user_fields['email']) )
            return form
            
         session.flash = self.messages.registration_pending
         if log:
            logger.info("Added user '%s' (email '%s')" % (user_fields['username'], user_fields['email']) )
         
         callback(onaccept,form)
         if not next:
            next = self.url(args = request.args)
         elif isinstance(next, (list, tuple)): ### fix issue with 2.6
            next = next[0]
         elif next and not next[0] == '/' and next[:4] != 'http':
            next = self.url(next.replace('[id]', str(form.vars.id)))
         redirect(next)
Example #10
0
      
      
      rc = False
      auth_struct = {'AuthMethod': 'password', 'Username': user['username'], 'AuthString': password}
      
      try:
         rc = auth_password_check( api, auth_struct, user, None )
      except Exception, e:
         logger.error( "User '%s' failed to authenticate" % username)

      if rc and user:
         user_public = user.public()
         user_stored = Storage(user_public)

         if log:
            logger.info("SMDS_Auth: User '%s' logged in" % user_public['username'])

         # process authenticated users
         # user wants to be logged in for longer
         session.auth = Storage(
               user = user_stored,
               last_visit = request.now,
               expiration = self.settings.expiration,
               hmac_key = web2py_uuid()
               )

         self.user = user_public
         logger.info("SMDS_Auth: user_id = %s" % self.user_id)
         logger.flush()
         
         return user
Example #11
0
    
    # get our content provider struct
    try:
       self.content_provider = self.cdn_api.Read( self.CDN_auth, "ContentProvider", api.config.MD_CONTENT_PROVIDER )[0]
       rc = 1
    except Exception, e:
       try:
          logger.warn("VerivueCoBlitz(setup): new API failed; trying old API")
          self.content_provider = self.cdn_api.GetContentProviders( self.CDN_auth, {'account': api.config.MD_CONTENT_PROVIDER} )[0]
          rc = 1
       except Exception, e2:
          logger.exception(e2, "VerivueCoBlitz(setup): could not look up SMDS CDN content provider account '%s'" % api.config.MD_CONTENT_PROVIDER )
          rc = None
    
    if rc == 1:
       logger.info("VerivueCoBlitz: connected to %s" % api.config.MD_CDN_API_URL )
    return rc
    
 
 def shutdown(self):
    return 1
 
 def add_user( self, user ):
    return 1
 
 def add_content( self, user, content_url ):
    content_info = {
       "url":                  content_url,
       "enabled":              True,
       "description":          "Created by SMDS",
       "content_provider_id":  self.content_provider['content_provider_id']