def init_db(): db.create_all() # TODO: configure default user here db.session.add(User(username="******", password="******")) db.session.add(User(username="******", password="******")) db.session.add(User(username="******", password="******")) db.session.commit()
def post(self): args = api.payload found = User.login(**args) if not found: abort(code=400, message='Invalid username or password') return found
def signup(): form = SignUpForm() if form.validate_on_submit(): user = User(username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() flash('Welcome {}, Please login'.format(user.username)) return redirect(url_for('login')) return render_template('signup.html', form=form)
def post(self): args = api.payload with commit_or_abort( error_message='Operation failed. Could not create user.'): user_model = User(**args) db.session.add(user_model) return user_model
def login(): form = LoginForm() if form.validate_on_submit(): # login and validate the user: user = User.get_by_username(username=form.username.data) if user is not None and user.check_password(form.password.data): login_user(user=user, remember=form.remember_me.data) flash('Logged in successfully as {}'.format(user.username)) return redirect(request.args.get('next') or url_for('index')) flash('Incorrect username or password') return render_template('login.html', form=form)
def test_create_order_statistics_objects(self): user = User(api_key='key') responses = [ { 'symbol': 'BTCUSDT', 'orderId': 'binance_order_id', 'clientOrderId': 'binance_client_order_id', 'executed_quantity': Decimal('10'), 'mean_price': Decimal('9000'), 'side': 'SELL', 'commission_USDT': Decimal('100'), 'commission_BNB': Decimal('10'), 'product': 'BTC_USDT', 'price_estimates': { 'BTC': Decimal('10000'), 'BNB': Decimal('10'), 'USDT': Decimal('1') }, 'mid_market_price': Decimal('10000') }, # BINANCE { 'symbol': 'BTC-USDT', 'orderId': 'cbpro_order_id', 'executed_quantity': Decimal('10'), 'mean_price': Decimal('9000'), 'side': 'sell', 'commission_USDT': Decimal('200'), 'product': 'BTC_USDT', 'price_estimates': { 'BTC': Decimal('10000'), 'USDT': Decimal('1'), 'LTC': Decimal('100') }, 'mid_market_price': Decimal('10000') } ] statistics = create_order_statistics_objects(responses, user) for statistic in statistics: self.assertEqual(statistic.user, user) self.assertEqual(statistic.mid_market_price, 10000) self.assertEqual(statistic.average_exec_price, 9000) self.assertEqual(statistic.volume, 90200) self.assertEqual(statistic.pair, 'BTC_USDT') self.assertEqual(statistic.fee, 200) self.assertEqual(statistic.action, 'sell')
def handleAction(self, action, param): """ Handle the specified incoming action from the javascript interface """ self.logger.info("Got action '%s' from user '%s'" % (action, str(self.user))) # Handle login if action == "account.login": # Fetch user entry try: email = str(param['email']).lower() user = User.get(User.email == email) except User.DoesNotExist: self.sendAction('account.login.response', { 'status' : 'error', 'message': "A user with this e-mail does not exist!" }) return # Validate user password, hashed with a client-generated challenge if user.password != hashlib.sha1("%s:%s" % (user.salt, param['password'])).hexdigest(): self.sendAction('account.login.response', { 'status' : 'error', 'message': "Password mismatch" }) return # Send activation e-mail on old accounts if user.created is None: # Update created timestamp user.created = datetime.datetime.now() user.save() # Send activation e-mail HLUser.sendActivationMail( user, Config.BASE_URL + self.reverse_url("account.activate") ) # Check if account is disabled if (user.status & User.STATUS_DISABLED) != 0: # Reply denial self.sendAction('account.login.response', { 'status' : 'error', 'message': "Your account has been disabled because the e-mail was not confirmed." }) return # Check if account is not yet activated if (user.status & User.STATUS_ACTIVATED) == 0: # Calculate time delta delta = (datetime.datetime.now() - user.created).days # After 7 days, disable account if delta > 7: # First disable forum reflection for this user banForumUser(user) # Reply denial self.sendAction('account.login.response', { 'status' : 'error', 'message': "Your account has been disabled because the e-mail was not confirmed." }) return # After 1 day, start warning elif delta > 1: # Send notification self.sendNotification("Please validate your e-mail address or your account will be deleted in %i day(s)!" % (7 - delta), 'alert') # Success self.user = HLUser(user) self.sendAction('account.login.response', { 'status' : 'ok' }) self.sendUserProfile() # Listen for user events self.user.receiveEvents( self.handleEvent ) # Let all interface know that we are ready for i in self.interfaces: i.ready() elif action == "account.register": # Fetch user profile profile = param['profile'] # Try to register user try: # Register and return user instance self.user = HLUser.register( profile, Config.BASE_URL + self.reverse_url("account.activate") ) except KeyError as e: # Check for existing user exceptions self.sendAction('account.register.response', { 'status' : 'error', 'message': "A user with this %s already exists!" % str(e) }) return except Lab.DoesNotExist: # Lab does not exist? Configuration error self.sendError( 'Server not configured properly: Missing default lab for the new user!', 'server-error' ) return # Success self.sendAction('account.register.response', { 'status' : 'ok' }) self.sendUserProfile() # Listen for user events self.user.receiveEvents( self.handleEvent ) # Let all interface know that we are ready for i in self.interfaces: i.ready() # Reset password elif action == "account.passwordReset": # Fetch user entry try: email = str(param['email']).lower() user = User.get(User.email == email) except User.DoesNotExist: self.sendAction('account.passwordReset.response', { 'status' : 'error', 'message': "A user with this e-mail does not exist!" }) return # If 'pin' is missing, create new pin and send e-mail if not 'pin' in param: # Create a random pin if not already set pin = user.getState("passwordpin", "") pinDate = user.getState("passwordpindate", time.time()) # Generate new pin once per hour if (not pin) or (time.time() - pinDate >= 3600): # Create new pin pin = "" for i in range(0,6): pin += random.choice("01234567890") # Store pin in state record user.setState("passwordpin", pin) user.setState("passwordpindate", time.time()) user.save() # Send password reset e-mail HLUser.sendPasswordResetMail( user, pin ) # We are good self.sendAction('account.passwordReset.response', { 'status' : 'ok' }) else: # Validate pin v_pin = user.getState("passwordpin") if v_pin != param['pin']: self.sendAction('account.passwordReset.response', { 'status' : 'error', 'message': "The password reset pin is not valid!" }) return # Update password user.password = hashlib.sha1("%s:%s" % (user.salt, param['password'])).hexdigest() user.setState("passwordpin", "") user.save() # Success self.user = HLUser(user) self.sendAction('account.passwordReset.response', { 'status' : 'ok' }) self.sendUserProfile() # Listen for user events self.user.receiveEvents( self.handleEvent ) # Let all interface know that we are ready for i in self.interfaces: i.ready() # Handle logout elif action == "account.logout": # Disconnect user if self.user: self.user.cleanup() self.user = None # Fire callback self.sendAction('account.logout.response', { 'status' : 'ok' }) else: # Forward to API interfaces and catch APIError try: handled = False for i in self.interfaces: # Check if this action can be handled by this action domain if action[0:len(i.domain)+1] == "%s." % i.domain: # Handle action i.currentAction = action[len(i.domain)+1:] i.handleAction(i.currentAction, param) handled = True break # Not implemented if not handled: return self.sendError("Action '%s' is not implemented" % action) except KeyError as e: # Forward API Errors traceback.print_exc() return self.sendError("Missing argument %s on request" % str(e), "missing-argument") except TypeError as e: # Forward API Errors traceback.print_exc() return self.sendError("Wrong type of argument on request (%s)" % str(e), "wrong-argument") except APIError as e: # Forward API Errors return self.sendError(e.value, e.code) except Exception as e: # Burry exception traceback.print_exc() return self.sendError("Error processing request (%s)" % str(e), "unhandled-exception")
def example_jinja2_usage(): # jinja2 is an easy way to send object from server to client # This example describes simple usage of transfer items from db model from server to client and display it user = User.get_by_username('admin') return render_template('example_jinja.html', jinja_object=user)
def get(self): User.logout() return {'success': True}