Example #1
0
  def performUserSignup(self, username, password, payment_nonce):
    """
    Signs up the User with the given username and password.
    """
    # First check if the user already in the database.
    user_login = self._fetchLoginByUsername(username)
    if user_login:
      raise Exception("User '%s' already exist.<br>"
                      "Please contact us for more information."
                      % username)

    user_login = Login(username=username)
    # Get the hash of the given password to store in the database.
    pass_hash = self._getHashedPassword(str(password))

    # Create a customer object in BrainTree
    result = braintree.Customer.create({
      "first_name": username,
      "last_name": "User",
      "payment_method_nonce": payment_nonce,
      "id": username,
    })

    if not result.is_success:
      raise Exception("Could not create BrainTree customer")

    # Save the User credentials in the databae.
    user_login.password_hash = pass_hash
    user_login.urole = int(Login.Role.USER)
    user_login.save()

    return user_login
Example #2
0
 def login(self):
     Login.setCredentials(self.username.text(), self.password.text())
     resp = loginController.getToken()
     if not resp:
         self.main = MainView()
         self.main.resize(800, 600)
         self.main.show()
         self.hide()
     else:
         self.message.setText(resp)
         self.message.show()
Example #3
0
 def _fetchLoginByUsername(self, username, password_hash=None):
   """
   Fetches the Login model corresponding to the given username.
   If an optional password_hash is given, verifies that the password hash
   matches as well.
   """
   try:
     if password_hash is None:
       return Login.objects(username=username).get()
     else:
       return Login.objects(username=username,
                            password_hash=password_hash).get()
   except:
     return None
Example #4
0
 def _fetchLoginByUsername(self, username, password_hash=None):
     """
 Fetches the Login model corresponding to the given username.
 If an optional password_hash is given, verifies that the password hash
 matches as well.
 """
     try:
         if password_hash is None:
             return Login.objects(username=username).get()
         else:
             return Login.objects(username=username,
                                  password_hash=password_hash).get()
     except:
         return None
Example #5
0
class LoginTest(unittest.TestCase):
    def setUp(self):
        self.login = Login()

    def test_login_no_username_and_password(self):
        '''当用户名和密码都为空时登陆'''
        result_list = self.login.get_login_error_message()
        assert set(['请输入手机号/邮箱', '请输入密码']).issubset(set(result_list))

    def test_login_no_password(self):
        '''当密码为空时登陆'''
        result_list = self.login.get_login_error_message(name='13500000018')
        assert set(['请输入密码']).issubset(set(result_list))

    def test_login_no_username(self):
        '''当用户名为空时登陆'''
        result_list = self.login.get_login_error_message(password='******')
        assert set(['请输入手机号/邮箱']).issubset(set(result_list))

    def test_login_error_password(self):
        '''当密码错误时登陆'''
        result = self.login.send_login_request(name='13500000018',
                                               password='******')
        assert result['success'] == False

    def test_login_error_username(self):
        '''当用户名错误时登陆'''
        result = self.login.send_login_request(name='13500000017',
                                               password='******')
        assert result['success'] == False

    def test_login_character(self):
        '''测试各种用户角色登陆'''
        user_list = excel_table_by_index()
        for user in user_list[1:]:
            try:
                username = int(user[0])
            except:
                username = user[0]
            try:
                password = int(user[1])
            except:
                password = user[1]
            character = user[2]
            session = get_front_session(username, password)
            web_response = session.get('http://www.zhankoo.com')
            soup = BeautifulSoup(web_response.text, 'lxml')
            result = soup.select('div.toolbar em')[0].get_text()
            assert result == character
Example #6
0
def getToken():
    try:
        response = requests.request('POST',
                                    'http://localhost:8000/oauth/token',
                                    data={
                                        "grant_type": "client_credentials",
                                        "client_id": Login.client_id,
                                        "client_secret": Login.client_secret
                                    })
        content = eval(response.content)
        if response.status_code == 200:
            Login.setToken(content["access_token"])
            return
        else:
            return content["error"]
    except Exception:
        return "Cannot connect to the server..."
Example #7
0
 def _fetchLogin(self, login_id):
   """
   Fetches the Login model by ID.
   """
   try:
     return Login.objects(login_id=login_id).get()
   except:
     return None
Example #8
0
 def _fetchLogin(self, login_id):
     """
 Fetches the Login model by ID.
 """
     try:
         return Login.objects(login_id=login_id).get()
     except:
         return None
Example #9
0
    def performUserSignup(self, username, password, payment_nonce):
        """
    Signs up the User with the given username and password.
    """
        # First check if the user already in the database.
        user_login = self._fetchLoginByUsername(username)
        if user_login:
            raise Exception("User '%s' already exist.<br>"
                            "Please contact us for more information." %
                            username)

        user_login = Login(username=username)
        # Get the hash of the given password to store in the database.
        pass_hash = self._getHashedPassword(str(password))

        # Create a customer object in BrainTree
        result = braintree.Customer.create({
            "first_name": username,
            "last_name": "User",
            "payment_method_nonce": payment_nonce,
            "id": username,
        })

        if not result.is_success:
            raise Exception("Could not create BrainTree customer")

        # Save the User credentials in the databae.
        user_login.password_hash = pass_hash
        user_login.urole = int(Login.Role.USER)
        user_login.save()

        return user_login
def login():
    if request.method == "GET":
        return render_template('login.html')
    elif request.method == "POST":
        form = request.form
        username = form['username']
        password = form['password']


        # có thể lấy username và password ở database
        user = Login.objects(username=username,
                            password=password
                            )

        if username == username and password == password:
            session['logged in'] = True
            return redirect(url_for('admin'))
        else:
            return "Wrong username or password"
Example #11
0
 def setUp(self):
     self.login = Login()
Example #12
0
 def setup_class(cls):
     cls.model = Login()
     cls.model.driver = webdriver.Chrome()
     cls.model.driver.maximize_window()
     cls.model.driver.implicitly_wait(5)
Example #13
0
class LoginService:
    """
  Handles the Login class during login, logout and persistence of sessions with
  session cookies.

  It allows different roles to have different token timeouts, both for active
  sessions and for global sessions.
  """
    def configure(self, app):
        """
    Configures the various timeouts and flags for each of the roles.
    """
        # Initialize the token service used within.
        token_service.configure(app.config)

    def performLoginFromCredentials(self, username, password, push_token=None):
        """
    Handles the login process for the given username and password, rejecting or
    logging in the respective Login model.
    Returns the Login model that was logged in, or None if login failed.
    """
        # Check if the credentials match.
        login = self._fetchLoginByUsername(username)
        if (not login or not self._isLoginPasswordMatch(login, password)):
            raise Exception("Incorrect username or password.")

        # Mark the Login as authenticated.
        login.authenticated = True
        login.push_token = push_token
        login.save()

        return token_service.generateToken(login)

    def performLogout(self, login):
        """
    Logs out the given Login model.
    """
        # Mark the Login as not authenticated.
        login.authenticated = False
        login.save()

    def performUserSignup(self, username, password, payment_nonce):
        """
    Signs up the User with the given username and password.
    """
        # First check if the user already in the database.
        user_login = self._fetchLoginByUsername(username)
        if user_login:
            raise Exception("User '%s' already exist.<br>"
                            "Please contact us for more information." %
                            username)

        user_login = Login(username=username)
        # Get the hash of the given password to store in the database.
        pass_hash = self._getHashedPassword(str(password))

        # Create a customer object in BrainTree
        result = braintree.Customer.create({
            "first_name": username,
            "last_name": "User",
            "payment_method_nonce": payment_nonce,
            "id": username,
        })

        if not result.is_success:
            raise Exception("Could not create BrainTree customer")

        # Save the User credentials in the databae.
        user_login.password_hash = pass_hash
        user_login.urole = int(Login.Role.USER)
        user_login.save()

        return user_login

    def loadLoginFromID(self, login_id):
        """
    Returns the Login corresponding to the given login ID.
    """
        # Check if the Login is valid under the various timeout conditions.
        login = self._fetchLogin(login_id)
        if not self._isLoginValid(login):
            return None

        return login

    def loadLoginFromToken(self, token_data):
        """
    Loads the token from the given serialized token data, returning the Login
    that matches or None if no match.
    """
        # First, get the deserialized data from the token using token_service.
        try:
            (username, password_hash) = token_service.loadToken(token_data)
        except Exception, e:
            print "ERROR: LoginService.loadLogin failed to deserialize token: %s" % e
            return None

        # Fetch the corresponding Login object.
        try:
            login = Login.objects(username=username,
                                  password_hash=password_hash).get()
        except Exception, e:
            print "ERROR: LoginService.loadToken failed to load Login: %s" % e
            return None
Example #14
0
 def run(self):
     user = Login()
     user.username = '******'
     user.password_ = 'secret'
     db.session.add(user)
     db.session.commit()