def changepin(): form = ChangePinForm() if request.method == 'POST': user = db.session \ .query(User) \ .filter_by(id=current_user.id) \ .first() if form.validate_on_submit(): if User.decryptpassword(pwdhash=user.wallet_pin, password=form.currentpin.data): cryptedpwd = User.cryptpassword(password=form.newpin2.data) user.wallet_pin = cryptedpwd db.session.add(user) db.session.commit() flash('Pin has been added.', category="success") else: flash('Invalid Pin', category="danger") return redirect((request.args.get('next', request.referrer))) else: flash('Invalid Form Entry', category="danger") return redirect((request.args.get('next', request.referrer))) return render_template('users/account/changepin.html', form=form)
def changepassword(): form = ChangePasswordForm() user = db.session \ .query(User) \ .filter_by(id=current_user.id) \ .first() if request.method == 'POST': if form.validate_on_submit(): if User.decryptpassword(pwdhash=user.password_hash, password=form.currentpassword.data): cryptedpwd = User.cryptpassword( password=form.newpasswordtwo.data) user.password_hash = cryptedpwd db.session.add(user) db.session.commit() flash('Password has been changed', category="success") return redirect(url_for('users.account')) else: flash('Bad Password', category="danger") return redirect((request.args.get('next', request.referrer))) else: flash(form.errors, category="danger") return redirect(url_for('users.account')) return render_template('users/account/changepassword.html', form=form)
def test_user_keys(self): ''' classes.user: Test that the User class returns the right keys. ''' result = User('luiscape').info() for key in self.keys: self.assertIn(key, result.keys())
def changeemail(): form = ChangeEmailForm() user = User.query.filter_by(user_name=current_user.user_name).first() if request.method == 'POST': if form.validate_on_submit(): try: if User.decryptpassword(pwdhash=user.wallet_pin, password=form.accountpin.data): if User.decryptpassword(pwdhash=user.password_hash, password=form.accountpassword.data): user.email = form.newemail.data user.fails = 0 db.session.add(user) db.session.commit() flash('Email updated', category="success") return redirect(url_for('users.account', user_name=current_user.user_name)) else: x = int(user.fails) y = x + 1 user.fails = y db.session.add(user) db.session.commit() if int(user.fails) == 5: user.locked = 1 db.session.add(user) db.session.commit() return redirect(url_for('users.account_locked')) else: flash("Invalid Password/Pin", category="danger") return redirect(url_for('users.changeemail', user_name=current_user.user_name)) else: x = int(user.fails) y = x + 1 user.fails = y db.session.add(user) if int(user.fails) == 5: user.locked = 1 db.session.add(user) db.session.commit() return redirect(url_for('users.account_locked')) else: db.session.commit() flash("Invalid Password/Pin", category="danger") return redirect(url_for('users.changeemail', user_name=current_user.user_name)) except Exception: return redirect(url_for('index')) else: flash("Error in Form") return redirect(url_for('users.changeemail', user_name=current_user.user_name)) return render_template('users/account/changeemail.html', form=form, user=user )
def setpin(): form = NewPinForm() user = db.session \ .query(User) \ .filter_by(id=current_user.id) \ .first() if user.wallet_pin != '0': return redirect((request.args.get('next', request.referrer))) if request.method == 'POST': if form.validate_on_submit(): if user.wallet_pin == '0': cryptedpwd = User.cryptpassword(password=form.newpin2.data) user.wallet_pin = cryptedpwd db.session.add(user) db.session.commit() flash('Pin has been changed', category="success") return redirect( url_for('wallet_btc.home', user_name=current_user.user_name)) else: flash('Invalid Pin', category="danger") return redirect((request.args.get('next', request.referrer))) else: flash('Invalid Form Entry', category="danger") return redirect((request.args.get('next', request.referrer))) return render_template('users/account/setpin.html', form=form)
def reset_with_token(token): form = PasswordFormReset() try: password_reset_serializer = URLSafeTimedSerializer( app.config['SECRET_KEY']) email = password_reset_serializer.loads(token, salt='password-reset-salt', max_age=3600) except: flash( 'The password reset link is invalid or has expired. Request another email through lost password.', category="danger") return redirect(url_for('users.login')) if request.method == 'POST': if form.validate_on_submit(): try: user = db.session \ .query(User) \ .filter_by(email=email) \ .first() except: flash('Invalid email address!', category="danger") return redirect(url_for('users.login')) cryptedpwd = User.cryptpassword(password=form.newpasswordtwo.data) user.password_hash = cryptedpwd db.session.add(user) db.session.commit() flash('Your password has been updated! Please login with it.', category="success") return redirect(url_for('users.login')) return render_template('users/newpassword.html', form=form, token=token)
def reset_walletpin_token(token): form = LostPinForm() try: password_reset_serializer = URLSafeTimedSerializer(app.config['SECRET_KEY']) email = password_reset_serializer.loads(token, salt='password-reset-salt', max_age=3600) except: flash('The pin reset link is invalid or has expired. ' 'Request another email through lost pin.', category="danger") return redirect(url_for('users.login')) if request.method == 'POST': if form.validate_on_submit(): try: user = User.query.filter_by(email=email).first() except: flash('Invalid email address!', category="danger") return redirect(url_for('users.reset_walletpin_token', token=token)) cryptedpwd = User.cryptpassword(password=form.pintwo.data) user.wallet_pin = cryptedpwd db.session.add(user) db.session.commit() flash('Your pin has been updated!', category="success") return redirect(url_for('index')) else: flash('Invalid form. Pin must be 6 digits and match!', category="danger") return redirect(url_for('users.reset_walletpin_token', token=token)) return render_template('users/lostpinsubmit.html', form=form, token=token)
class TestUser(unittest.TestCase): """ This class tests the user """ def setUp(self): self.user = User('ariana', '*****@*****.**', 'abcde') def test_correct_login(self): """ user login with the correct credentials """ self.assertFalse(self.user.login('Ariana', 'abcdef')) def test_incorrect_login(self): """ user login details are rejected if they login with incorrect credentials """ self.assertFalse(self.user.login('Adriana', 'ghijk')) def test_add_book(self): """ user can add a book """ self.user.add_book('get rich') self.assertEqual(self.user.books, ['get rich']) def test_delete_book(self): """ user can delete books """ self.user.books.append('get rich') self.user.books.append('transformation') self.user.delete_book('get rich') self.assertEqual(self.user.books, ['transformation']) def test_get_books(self): """ User can view books added """ self.user.books.append('book1') self.assertEqual(self.user.get_books(),['book1']) def test_borrow_books(self): """ User can borrow books """ self.user.books.append('get rich') self.user.books.append('transformation') self.user.borrow_book('get rich') self.assertEqual(self.user.books, ['transformation'])
def send_mail_user(username, id): user = User.get(username=username) reco_movies = recommend_movies(id, 5)[1] dict_reco_movies = reco_movies.to_dict("records") msg = Message(subject="Recommended movies", recipients=[user.json["emailAddress"]]) msg.html = render_template("mail.html", dict_reco_movies=dict_reco_movies, user=user.json) mail.send(msg)
def login_post(): if request.method == 'POST': form = LoginForm(request.form) if form.validate_on_submit(): user = db.session\ .query(User)\ .filter_by(user_name=form.user_name.data)\ .first() if user is not None: if User.decryptpassword(pwdhash=user.password_hash, password=form.password_hash.data): if user.locked == 0: user.fails = 0 db.session.add(user) db.session.commit() login_user(user) current_user.is_authenticated() current_user.is_active() return redirect(url_for('index')) else: return redirect(url_for('users.account_locked')) else: x = user.fails y = x + 1 user.fails = y db.session.add(user) db.session.commit() if int(user.fails) >= 5: user.locked = 1 db.session.add(user) db.session.commit() return redirect(url_for('users.account_locked')) else: flash("Please retry user name or password.", category="danger") return redirect(url_for('users.login')) else: flash("Please retry user name or password", category="danger") return redirect(url_for('users.login')) else: flash("Please retry user name or password.", category="danger") return redirect(url_for('users.login')) else: flash("Incorrect form.", category="danger") return redirect(url_for('index'))
def sendcoin(): if request.method == "GET": pass if request.method == "POST": form = WalletSendcoin() wallet = BchWallet.query.filter(BchWallet.user_id == current_user.id).first_or_404() # get walletfee walletthefee = db.session.query(BchWalletFee).get(1) wfee = Decimal(walletthefee.bch) if form.validate_on_submit(): if User.decryptpassword(pwdhash=current_user.wallet_pin, password=form.pin.data): sendto = form.sendto.data comment = form.description.data amount = form.amount.data # test wallet_bch stuff for security walbal = Decimal(wallet.currentbalance) amount2withfee = Decimal(amount) + Decimal(wfee) # greater than amount with fee if floating_decimals(walbal, 8) >= floating_decimals(amount2withfee, 8): # greater than fee if Decimal(amount) > Decimal(wfee): # add to wallet_bch work bch_cash_send_coin_offsite( user_id=current_user.id, sendto=sendto, amount=amount, comment=comment ) flash("BCH Sent: " + str(sendto), category="success") flash("Please allow a few minutes for your coin to be added to transactions", category="success") return redirect(url_for('wallet_bch.home', user_name=current_user.user_name)) else: flash("Cannot withdraw amount less than fee: " + str(wfee), category="danger") return redirect(url_for('wallet_bch.home', user_name=current_user.user_name)) else: flash("Cannot withdraw more than your balance including fee.", category="danger") return redirect(url_for('wallet_bch.home', user_name=current_user.user_name)) else: flash("Invalid Pin.", category="danger") return redirect(url_for('wallet_bch.home', user_name=current_user.user_name)) else: flash("Form Error. Did you enter something inccorrectly? ", category="danger") return redirect(url_for('wallet_bch.home', user_name=current_user.user_name))
def signin(): form = CustomerSigninForm() if request.method == 'POST': password=request.form['password'] email=request.form['email'] if email and password: user = User(email, password, mysql) if user.authenticated: login_user(user) session['logged_in'] = True session['user email'] = user.get_id() session['user name'] = user.get_user_name() return render_template('account_management.html', accountInfo = { "name" : user.get_user_name(), "email" : user.get_id(), "counts" : session['counts']}) else: session['logged_in'] = False return render_template('signin.html', form=form) else: session['logged_in'] = False return render_template('signin.html', form=form)
def sendcoin(): # forms form = WalletSendCoin() # Get wallet wallet = db.session.query(MoneroWalletStagenet).filter_by(user_id=current_user.id).first() # walletfee walletthefee = db.session.query(MoneroWalletFeeStagenet).get(1) wfee = Decimal(walletthefee.amount) if request.method == "POST": if form.validate_on_submit(): if User.decryptpassword(pwdhash=current_user.wallet_pin, password=form.pin.data): sendto = form.sendto.data amount = form.amount.data # test wallet_btc stuff for security walbal = Decimal(wallet.currentbalance) amount2withfee = Decimal(amount) + Decimal(wfee) # greater than amount with fee if floating_decimals(walbal, 8) >= floating_decimals(amount2withfee, 8): # greater than fee if Decimal(amount) > Decimal(wfee): # add to wallet_btc work monerosendcoin_stagenet( user_id=current_user.id, sendto=sendto, amount=amount, ) flash("XMR Sent: " + str(sendto), category="success") flash("Please allow a few minutes for the transaction to appear and process to begin.", category="success") return redirect(url_for('wallet_xmr_stagenet.home', user_name=current_user.user_name)) else: flash("Cannot withdraw amount less than wallet_btc fee: " + str(wfee), category="danger") return redirect(url_for('wallet_xmr_stagenet.home', user_name=current_user.user_name)) else: flash("Cannot withdraw amount less than wallet_btc fee: " + str(wfee), category="danger") return redirect(url_for('wallet_xmr_stagenet.home', user_name=current_user.user_name)) else: flash("Invalid Pin", category="danger") return redirect(url_for('wallet_xmr_stagenet.home', user_name=current_user.user_name)) else: flash("Bad Form. Did you enter the information correctly?", category="danger") return redirect(url_for('wallet_xmr_stagenet.home', user_name=current_user.user_name))
def send_mail_flask(): for user in User.all(): try: # We run the recommend_movies function from the svd.py file for every users reco_movies = recommend_movies(user.mongo_id, 5)[1] except ValueError: continue dict_reco_movies = reco_movies.to_dict("records") msg = Message(subject="Recommended movies", recipients=[user.json["emailAddress"]]) msg.html = render_template("mail.html", dict_reco_movies=dict_reco_movies, user=user.json) mail.send(msg)
class TestUser(unittest.TestCase): """ This includes the tests for the user model """ def setUp(self): self.user = User('dottie', '*****@*****.**', 'abcdefg') def test_correct_login(self): """ user can login with the correct credentials """ self.assertFalse(self.user.login('Dottie', 'abcdef')) def test_incorrect_login(self): """ test to reject user login if the user login with incorrect credentials """ self.assertFalse(self.user.login('Drottie', 'fedcba')) def test_create_shopping_list(self): """ user create shoppinglist """ self.user.create_shopping_list('groceries') self.assertEqual(self.user.shopping_lists, ['groceries']) def test_delete_shopping_list(self): """ user can delete their shoppinglist the list should exist in their shoppinglist before it's deleted """ self.user.shopping_lists.append('list1') self.user.shopping_lists.append('list2') self.user.delete_shopping_list('list1') self.assertEqual(self.user.shopping_lists, ['list2']) def test_view_shopping_list(self): """ User can view shoppinglist created """ self.user.shopping_lists.append('list1') self.assertEqual(self.user.view_shopping_list(), ['list1'])
def fetchClassData(key=None, id=None): ''' Loads data from specified CKAN object class. ''' classes = { 'users': User(id), 'countries': Country(id), 'datasets': Dataset(id), 'revisions': Revision(id), 'resources': Resource(id), 'gallery_items': GalleryItem(id), 'organizations': Organization(id) } # # Selects only the fields # of interest from the dictionary. # result = {k: classes[key].info()[k] for k in _fields(config, key)} return result
def load_user(user_id): return User.get(user_id=user_id, db=mysql)
def contact(user_id): form = SubmitInvite() if form.validate_on_submit(): User.delete_user_by_id(user_id) return redirect(url_for('invites')) return render_template('contact.html', user=User.get_user_by_id(user_id), form=form)
def invites(): users = User.get_users() user_count = [*range(1, len(users)+1)] users = list(zip(users, user_count)) return render_template('invites.html', users=users)
def setUp(self): self.user = User('dottie', '*****@*****.**', 'abcdefg')
def register(): form = RegistrationForm() if request.method == 'POST': if form.validate_on_submit(): try: theanonid = random_user_name_anon() now = datetime.utcnow() cryptedpwd = User.cryptpassword(password=form.password.data) # add user to db newuser = User(user_name=form.user_name.data, email=form.email.data, password_hash=cryptedpwd, wallet_pin='0', profileimage='', bannerimage='', member_since=now, admin=0, admin_role=0, bio='', last_seen=now, locked=0, fails=0, confirmed=0, anon_id=theanonid, anon_mode=0, over_age=0, agree_to_tos=True, banned=0, color_theme=3, post_style=1) db.session.add(newuser) db.session.commit() # profile info userbio = UserPublicInfo(user_id=newuser.id, bio='', short_bio='') stats_for_bch = UserStatsBCH( user_name=newuser.user_name, user_id=newuser.id, # given to posters/commenters total_donated_to_postcomments_bch=0, total_donated_to_postcomments_usd=0, # recieved from posting total_recievedfromposts_bch=0, total_recievedfromposts_usd=0, # recieved from comments total_recievedfromcomments_bch=0, total_recievedfromcomments_usd=0, # given to charities total_donated_to_cause_bch=0, total_donated_to_cause_usd=0, ) stats_for_user = UserStats(user_name=newuser.user_name, user_id=newuser.id, post_upvotes=0, post_downvotes=0, comment_upvotes=0, comment_downvotes=0, total_posts=0, total_comments=0, user_level=1, user_exp=0, user_width_next_level='0') users_timers = UserTimers(user_name=newuser.user_name, user_id=newuser.id, account_created=now, last_post=now, last_common_creation=now, last_comment=now, last_report=now) # add to db db.session.add(userbio) db.session.add(users_timers) db.session.add(stats_for_user) db.session.add(stats_for_bch) # commit db.session.commit() # make a user a directory getusernodelocation = userimagelocation(x=newuser.id) userfolderlocation = os.path.join(UPLOADED_FILES_DEST, current_disk, 'user', getusernodelocation, str(newuser.id)) mkdir_p(path=userfolderlocation) # login new user try: # bitcoin cash bch_create_wallet(user_id=newuser.id) except: pass login_user(newuser) current_user.is_authenticated() current_user.is_active() flash( "Successfully Registered." " If you want to access your wallet," " you will need to confirm your email. If you used an invalid email," " you can change this in account settings.", category="success") return redirect(url_for('welcome')) except Exception as e: return redirect((request.args.get('next', request.referrer))) else: for errors in form.user_name.errors: flash(errors, category="danger") for errors in form.password.errors: flash(errors, category="danger") for errors in form.passwordtwo.errors: flash(errors, category="danger") for errors in form.passwordtwo.errors: flash(errors, category="danger") return redirect((request.args.get('next', request.referrer))) return render_template('users/register.html', form=form)
class UserCase(unittest.TestCase): @classmethod def setUp(self): self.user = User('*****@*****.**', 'password', 'joy') self.slist = SList('joybirthday') self.item = Item('cake', 2000) def test_user_created(self): """Should test that user is created successfully""" self.assertTrue(self.user) def test_create_list(self): """Should succesfully added list""" self.user.create_list('travel') self.assertEqual(len(self.user.slist), 1) def test_create_list_that_already_exists(self): """Should return false if list name already exists""" self.user.create_list('travel') self.assertFalse(self.user.create_list('travel')) def test_update_list(self): """Should test for update list""" self.user.create_list(self.slist) new_list_name = 'joybirthday' self.user.update_list( self.slist.name, new_list_name, ) self.assertEqual(self.slist.name, new_list_name) def test_get_user_list(self): #Should check that a user can fetch all their lists self.slist = SList('joybirthday') self.user.create_list(self.slist) self.assertIsInstance(self.user.get_lists(), list) self.assertEqual(len(self.user.get_lists()), 1) def test_get_single_list(self): """Should check getting a list""" self.slist = SList('travel') self.user.create_list(self.slist) lst = self.user.get_single_list('travel') self.assertEqual(self.slist.name, 'travel') def test_delete_list(self): """Should check if list is deleted by user""" # self.slist = SList('joybirthday') self.user.create_list('joybirthday') length_before = len(self.user.get_lists()) self.user.delete_list('joybirthday') length_after = len(self.user.get_lists()) self.assertEqual(length_before, length_after + 1) def test_user_add_item_to_list(self): """Should check if item is successfully added to list""" self.user.create_list("joybirthday") self.user.add_item('joybirthday', 'cake', '3000') self.assertEqual(self.user.slist[-1].items[-1].name, 'cake') def test_user_edit_item_in_list(self): """Should check if an item in a list is updated """ # list_name = 'joybirthday' # item_name = 'cake' # new_item_name = 'bag' # price=10000 self.user.create_list('joybirthday') self.user.add_item('joybirthday', 'cake', 3000) self.user.edit_item('joybirthday', 'cake', 'bag', 2000, True) self.assertEqual(self.user.slist[-1].items[-1].name, 'bag') def test_get_items_in_list(self): """Should check if the list items are well fetched""" list_name = 'travel' item1 = 'cake' item2 = 'soda' self.user.create_list('travel') self.user.add_item('travel', 'cake', 4000) self.user.add_item('travel', 'soda', 3000) items = self.user.get_items('travel') self.assertIsInstance(items, list) self.assertEqual(len(items), 2) def test_delete_item_from_list(self): """Should check if item is deleted from list""" list_name = 'joybirthday' price = 2000 self.user.create_list('joybirthday') self.user.add_item('joybirthday', 'candle', 10000) length_before = len(self.user.slist[-1].items) self.user.delete_item('joybirthday', 'candle') length_after = len(self.user.slist[-1].items) self.assertEqual(length_before - 1, length_after)
def setUp(self): self.user = User('*****@*****.**', 'password', 'joy') self.slist = SList('joybirthday') self.item = Item('cake', 2000)
def setUp(self): self.user = User('ariana', '*****@*****.**', 'abcde')
def recommend_movies(userID, num_recommendations): start_time3 = time.time() global movies_df # We retrieve the movies database from mongodb db if it is not in the cache movies = Movie.all_values_list(id=1, name=1, genres=1, poster_path=1, _id=0) if movies_df is None: movies_df = pd.DataFrame(movies) movies_df = movies_df.astype({"id": "int32"}) start_time6 = time.time() print("--- load movies df: %s seconds ---" % (start_time6 - start_time3)) # We retrieve the ratings database from a csv file saved in the folder baseRatings = pd.read_csv("./rating_update.csv", header=0)[:300000] # We retrieve the user's ratings database and concatenate it to all the ratings we have ratings = User.get(_id=ObjectId(userID)).json["ratings"] ratings_df = pd.DataFrame(ratings, columns=("cinema", "rating")) ratings_df["userId"] = baseRatings["userId"].max() + 1 ratings_df = ratings_df.rename(columns={"cinema": "movieId"}) ratings_df = ratings_df.astype({ "userId": "int32", "movieId": "int32", "rating": "float32" }) baseRatings = baseRatings.astype({ "userId": "int32", "movieId": "int32", "rating": "float32" }) baseRatings = pd.concat([baseRatings, ratings_df], ignore_index=True, sort=False) start_time7 = time.time() print("--- load rating df: %s seconds ---" % (start_time7 - start_time6)) # We create the pivot database between the movies and the ratings and normalize it Rating = baseRatings.pivot(index="userId", columns="movieId", values="rating").fillna(0) R = Rating.to_numpy() user_ratings_mean = np.mean(R, axis=1) Ratings_demeaned = R - user_ratings_mean.reshape(-1, 1) start_time4 = time.time() print("--- construct the pivot %s seconds ---" % (start_time4 - start_time7)) # We build the singular value decomposition using 30 vectors U, sigma, Vt = svds(Ratings_demeaned, k=30) # We use this decomposition to estimate ratings of the current user sigma = np.diag(sigma) all_user_predicted_ratings = np.dot(np.dot(U, sigma), Vt) + user_ratings_mean.reshape(-1, 1) preds = pd.DataFrame(all_user_predicted_ratings, columns=Rating.columns) # We sort the user ratings that we have just estimated user_row_number = (baseRatings["userId"].max()) - 1 sorted_user_predictions = preds.iloc[user_row_number].sort_values( ascending=False) # From the initial movies database, we merge the estimated ratings to user_data = baseRatings[baseRatings.userId == ( baseRatings["userId"].max())] user_full = user_data.merge(movies_df, how="left", left_on="movieId", right_on="id").sort_values(["rating"], ascending=False) # We return the database of the top rated movies for the user according # to the number of recommendations we want recommendations = ( movies_df[~movies_df["id"].isin(user_full["movieId"])].merge( pd.DataFrame(sorted_user_predictions).reset_index(), how="left", left_on="id", right_on="movieId", ).rename(columns={ user_row_number: "Predictions" }).sort_values("Predictions", ascending=False).iloc[:num_recommendations, :-1]) start_time5 = time.time() print("--- building the svd %s seconds ---" % (start_time5 - start_time4)) return user_full, recommendations