Exemplo n.º 1
0
    def navbar(self, prefix='Welcome', action=None):
        """
      Create a pretty navigation bar
      """
        try:
            user = None
            session = current.session
            if session.auth:
                user = session.auth['user']

            request = current.request
            T = current.T
            if isinstance(prefix, str):
                prefix = T(prefix)
            if not action:
                action = URL(request.application, request.controller, 'user')
            if prefix:
                prefix = prefix.strip() + ' '

            if user:

                logout = A(T('logout'), _href=action + '/logout')
                profile = A(T('profile'), _href=action + '/profile')
                password = A(T('password'), _href=action + '/change_password')
                bar = SPAN(prefix,
                           user['username'],
                           ' [ ',
                           logout,
                           ']',
                           _class='auth_navbar')
                if not 'profile' in self.settings.actions_disabled:
                    bar.insert(4, ' | ')
                    bar.insert(5, profile)
                if not 'change_password' in self.settings.actions_disabled:
                    bar.insert(-1, ' | ')
                    bar.insert(-1, password)
            else:

                login = A(T('login'), _href=action + '/login')
                register = A(T('register'), _href=action + '/register')
                retrieve_username = A(T('forgot username?'),
                                      _href=action + '/retrieve_username')
                lost_password = A(T('lost password?'),
                                  _href=action + '/request_reset_password')
                bar = SPAN('[ ', login, ' ]', _class='auth_navbar')

                if not 'register' in self.settings.actions_disabled:
                    bar.insert(2, ' | ')
                    bar.insert(3, register)
                if 'username' in User.public_fieldnames and not 'retrieve_username' in self.settings.actions_disabled:
                    bar.insert(-1, ' | ')
                    bar.insert(-1, retrieve_username)
                if not 'request_reset_password' in self.settings.actions_disabled:
                    bar.insert(-1, ' | ')
                    bar.insert(-1, lost_password)

            return bar
        except Exception, e:
            logger.exception(e, "Navbar error")
            logger.flush()
Exemplo n.º 2
0
   def navbar(self,prefix='Welcome',action=None):
      """
      Create a pretty navigation bar
      """
      try:
         user = None
         session = current.session
         if session.auth:
            user = session.auth['user']
         
         request = current.request
         T = current.T
         if isinstance(prefix,str):
            prefix = T(prefix)
         if not action:
            action=URL(request.application,request.controller,'user')
         if prefix:
            prefix = prefix.strip()+' '
         
         if user:
            
            logout=A(T('logout'),_href=action+'/logout')
            profile=A(T('profile'),_href=action+'/profile')
            password=A(T('password'),_href=action+'/change_password')
            bar = SPAN(prefix, user['username'],' [ ', logout, ']',_class='auth_navbar')
            if not 'profile' in self.settings.actions_disabled:
                  bar.insert(4, ' | ')
                  bar.insert(5, profile)
            if not 'change_password' in self.settings.actions_disabled:
                  bar.insert(-1, ' | ')
                  bar.insert(-1, password)
         else:
            
            login=A(T('login'),_href=action+'/login')
            register=A(T('register'),_href=action+'/register')
            retrieve_username=A(T('forgot username?'),
                              _href=action+'/retrieve_username')
            lost_password=A(T('lost password?'),
                              _href=action+'/request_reset_password')
            bar = SPAN('[ ',login,' ]',_class='auth_navbar')

            if not 'register' in self.settings.actions_disabled:
                  bar.insert(2, ' | ')
                  bar.insert(3, register)
            if 'username' in User.public_fieldnames and not 'retrieve_username' in self.settings.actions_disabled:
                  bar.insert(-1, ' | ')
                  bar.insert(-1, retrieve_username)
            if not 'request_reset_password' in self.settings.actions_disabled:
                  bar.insert(-1, ' | ')
                  bar.insert(-1, lost_password)
         
         return bar
      except Exception, e:
         logger.exception(e, "Navbar error")
         logger.flush()
Exemplo n.º 3
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)
Exemplo n.º 4
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)
Exemplo n.º 5
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:'******'Password:'******'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)
Exemplo n.º 6
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:'******'Email:'),            TD(INPUT(_name="email", _type="text",requires=IS_EMAIL(error_message=self.messages.invalid_email)))),          \
                        TR(TD('Password:'******'Re-type Password:'******'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)
Exemplo n.º 7
0
         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
         
      return rc
      
      
   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
Exemplo n.º 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:'******'Password:'******'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)
Exemplo n.º 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:'******'Email:'),            TD(INPUT(_name="email", _type="text",requires=IS_EMAIL(error_message=self.messages.invalid_email)))),          \
                          TR(TD('Password:'******'Re-type Password:'******'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)
Exemplo n.º 10
0
            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

        return rc

    def login(self,
              next=DEFAULT,
              onvalidation=DEFAULT,
              onaccept=DEFAULT,
              log=DEFAULT):
        """
      Handle a login request, and redirect.
      """
        request = current.request
        response = current.response