def reqister(request): username = request.POST.get("username") password = request.POST.get("password") email = request.POST.get("email") company = request.POST.get("company") location = request.POST.get("location") startdate = request.POST.get("startdate") enddate = request.POST.get("enddate") comments = request.POST.get("comments") datetimenow = timezone.now() user = User(username=username, email=email) user.set_password(password) user.save() userdetails = UserAccount(user=user, user_type='CU', company=company) userdetails.save() login(request, user) inquiry = Inquiry(location=location, start_date=startdate, end_date=enddate, sent_on=datetimenow, comments=comments, customer=user, status="AQ") inquiry.save() cart = request.session.get('cart', []) equipment = Equipment.objects.filter(id__in=cart) for unit in equipment: inquiryequipment = InquiryEquipment(equipment=unit, inquiry=inquiry) inquiryequipment.save() request.session['cart'] = [] return HttpResponse('1')
def signup(request): if request.method == 'POST': username = request.POST['username'] password = password1 = request.POST['password1'] password2 = request.POST['password2'] if password1 == password2: if User.objects.filter(username=username).exists() == False: o_ref = User.objects.create_user(username=username, password=password1) o_ref.save() u_ref = UserAccount(username=username, password=password1) u_ref.save() print('User Created') user = auth.authenticate(username=username, password=password) auth.login(request, user) print(user) return redirect('../../user/') else: print("User Already Exists") return render(request, "signup.html") else: print("Passwords don't Match") return render(request, "signup.html") else: return render(request, "signup.html")
def demo_login(): landing_page = request.args.get('lp') if not landing_page: landing_page = "advertise" # Create demo account user = UserAccount(name="Bump Demo", email="*****@*****.**", reply_to_email="*****@*****.**", is_demo=True) user.put() if user and flasklogin.login_user(user,False): if landing_page == "advertise": return redirect(url_for("advertise") + '?demo=true') elif landing_page == 'manage': return redirect(url_for("manage") + '?tour=start') return redirect(url_for("index") + '?whitelist=false')
def item_due_reminders(): count = 0 """find all the items due tomorrow and send reminder emails""" items = ItemCopy.query(ItemCopy.due_date==date.today() + timedelta(days=1)).fetch() for item in items: count += 1 owner = UserAccount.query(UserAccount.key==item.owner).get() mail.send_mail(sender=owner.email, to=UserAccount.query(UserAccount.key==item.borrower).get().email, subject="Item Due Soon", body="""The following item is due to be returned tomorrow: '%s'. Please return it to %s"""%(Item.query(Item.key==item.item).get().title,owner.name)) return "%s reminders were sent out" %count
def book_due_reminders(): count = 0 """find all the books due tomorrow and send reminder emails""" books = BookCopy.query(BookCopy.due_date==date.today() + timedelta(days=1)).fetch() for book in books: count += 1 owner = UserAccount.query(UserAccount.key==book.owner).get() mail.send_mail(sender=owner.email, to=UserAccount.query(UserAccount.key==book.borrower).get().email, subject="Book Due Soon", body="""Hey, remember that book you borrowed on Bookout from me, '%s'? Please get it back to me by tomorrow. Thanks! %s"""%(Book.query(Book.key==book.book).get().title,owner.name)) return "%s reminders were sent out" %count
def request_to_borrow(lenderID, itemCopyID): emailText = [] emailText.append("You have received the following message from " + current_user().name + ", a Sharing Commons user.\n----\n\n") emailText.append(request.data) emailText.append("\n\n----\nReply to this message to send an email to " + current_user().name + " and set up the exchange. Once you've lent the item, visit beta.sharingcommons.com to confirm lending the item. " + current_user().name + " will receive an email when the item is due") emailBody = ''.join(emailText) # Request item try: borrower = current_user() lender = UserAccount.getuser(int(lenderID)) itemCopy = ItemCopy.get_by_id(int(itemCopyID)) rtb1 = RequestToBorrow() rtb1.useraccount = lender.key rtb1.connection = borrower.key rtb1.item = itemCopy.key rtb1.put() wtb1 = WaitingToBorrow() wtb1.useraccount = borrower.key wtb1.connection = lender.key wtb1.item = itemCopy.key wtb1.put() except: return jsonify({"result":"error"}) # Send email mail.send_mail(sender="Sharing Commons <*****@*****.**>", to=lender.name + " <" + lender.email + ">", reply_to=borrower.name + " <" + borrower.email + ">", subject='Sharing Commons: Request to Borrow "' + Item.query(Item.key == itemCopy.item).get().title + '"', body=emailBody) return jsonify({"result":"success"})
def optin(user_ID=None): signup_method = request.args.get('signup_method') include_email = request.args.get('include_email') iframe = request.args.get('iframe') if not include_email: include_email = False elif include_email.lower() == "true": include_email = True else: include_email = False if not iframe: iframe = False elif iframe.lower() == "true": iframe = True else: iframe = False if not signup_method: signup_method = 3 # Default to website cur_user = current_user() if user_ID: # Regardless of who is logged in, send to page for provided user ID restaurant = UserAccount.get_by_id(int(user_ID)) else: # No one is logged in, send to provided user or if none redirect to home if cur_user.is_authenticated(): restaurant = cur_user else: return redirect(url_for("index")) return render_response("optin.html",restaurant=restaurant,signup_method=signup_method,include_email=include_email,iframe=iframe)
def test_recipe_list_page_render(self, api_client): new_user = UserAccount() api_client.force_authenticate(new_user) recipe_list_page_render = api_client.get(recipe_list_url) assert recipe_list_page_render.status_code == 200
def index(): # Each user has an invitation link (in /network) which they send to other users to # invite them to connect on BookOut. Currently, this is the only method of connecting # users. The link adds an argument to the index link (?connect=) with the inviter's # user ID. A modal appears in the view if otherUserID is not 0. # Grab User ID from connection invitation otherUserID = request.args.get('connect') # If no connect argument is present (just a regular visit to the dashboard), set to 0 (ignored in view) if otherUserID is None: connectionType = 0 #No connection request is being made otherUserID = 0 otherUserName = 0 else: # Get User Name from User ID otherUserObj = UserAccount.get_by_id(int(otherUserID)) # Set invalid objects to invalid if otherUserObj is None: otherUserID = 0 otherUserName = 0 connectionType = 1 #Invalid User ID else: otherUserName = otherUserObj.name connectionType = 2 #Valid User # Don't let a user connect with him/herself, set to 0 so they get nothing if int(otherUserID) == current_user().get_id(): connectionType = 3 #Own self # Don't let a user connect with an existing connection # if int(otherUserID) matches something in current_user().connected_accounts # connectionType = 4 #Existing Connection return render_response('home.html',connectUserID=otherUserID,connectUserName=otherUserName,connectType=connectionType)
def simple_add_connection(otherUserID): cur_user = current_user() otherUser = UserAccount.getuser(int(otherUserID)) if cur_user.add_connection(otherUser): return jsonify({"Message":"Connection successfully created"}) else: return jsonify({"Message":"Connection already existed"})
def test_comment_search_page_render(self, api_client): new_user = UserAccount() api_client.force_authenticate(new_user) search_comment_url = '/api/comments/search/' response = api_client.get(search_comment_url) assert response.status_code == 405 # 405 = method not allowed - get isnt allowed only post
def test_like_page_render(self, api_client): new_user = UserAccount() api_client.force_authenticate(new_user) like_page_render = api_client.get(like_url) assert like_page_render.status_code == 405
def optin_guest(user_ID,signup_method): user = UserAccount.get_by_id(int(user_ID)) # Opt in the guest (this will add them if they don't exist, and update and optin if they already do) guest = Guest.add_guest(firstName=request.form["firstName"], lastName=None, smsNumber=functions.digitizePhoneNumber(request.form["smsNumber"]), email=request.form["email"], preferredContact=request.form["preferredContact"], optIn=True, signup_method=int(signup_method), user=user) if guest: return "Success" else: return "Error"
def searchbooks(): booklist = {} searchterm = request.args.get('value') attr = request.args.get('refineSearch') if attr == "all": attr = None if searchterm is None: searchterm = "" else: searchterm = searchterm.lstrip() if searchterm is None or searchterm == "": pass else: cur_user = current_user() logging.info(cur_user) if not cur_user.is_authenticated(): #Assume no books in library or network, return results only booklist = Book.search_books_by_attribute(searchterm,attr) for book in booklist: booklist[book] = booklist[book].to_dict() #Assume not in booklist or networkbooklist booklist[book]["inLibrary"] = "False" booklist[book]["inNetwork"] = "False" else: user = current_user() #Create a dictionary of the user's books mybooklist = {} for copy in user.get_library(): mybooklist[copy.OLKey] = copy #Create a dictionary of the books in my network networkbooklist = {} string = "" for connection in user.get_connections(): u = UserAccount.getuser(connection.id()) for copy in u.get_library(): networkbooklist[copy.OLKey] = copy booklist = Book.search_books_by_attribute(searchterm,attr) for book in booklist: booklist[book] = booklist[book].to_dict() booklist[book]["escapedtitle"] = re.escape(booklist[book]["title"]) if booklist[book]['OLKey'] in mybooklist: booklist[book]["inLibrary"] = "True" else: booklist[book]["inLibrary"] = "False" if booklist[book]['OLKey'] in networkbooklist: booklist[book]["inNetwork"] = "True" else: booklist[book]["inNetwork"] = "False" return render_response('searchbooks.html', books=booklist, search=searchterm, attribute=attr)
def generate_gravatar(userID,size): try: int(userID) user = UserAccount.get_by_id(int(userID)) import hashlib import urllib gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(user.email).hexdigest() + "?s=" + size + "&d=" + urllib.quote(request.host_url,'') + "static%2Fimg%2Fnoimage.png" except: return False return redirect(gravatar_url)
def discover(): user = current_user() booklist = [] string = "" for connection in user.get_connections(): u = UserAccount.getuser(connection.id()) for copy in u.get_library(): book = Book.query(Book.key == copy.book).get() booklist.append(book) #Sort booklist alphabetically, with title as the primary sort key and author as secondary booklist.sort(key=lambda book: book.author.lower()) booklist.sort(key=lambda book: book.title.lower()) return render_response('discover.html',books=booklist)
def manage_connections(otherUserID = None): cur_user = current_user() if request.method == 'GET': connections = cur_user.get_all_connections() users = [] result = "you have " + str(len(connections)) + " connections" for connection in connections: result += "<br>" + connection.name user = dict() user["name"] = connection.name user["email"] = connection.email #user["username"] = connection.username user["id"] = connection.get_id() users.append(user) return jsonify({"connectedUsers":users}) elif request.method == 'POST': cur_user = current_user() otherUser = UserAccount.getuser(int(otherUserID)) result = cur_user.send_invite(otherUser) if(result == 0): return jsonify({"Message":"Invitation successfully sent"}) elif(result == 1): return jsonify({"Message":"Connection already existed"}) elif(result == 2): return jsonify({"Message":"Cannot create a connection with yourself"}) elif request.method == 'DELETE': cur_user = current_user() otherUser = UserAccount.getuser(int(otherUserID)) if cur_user.remove_connection(otherUser): return jsonify({"Message":"Connection successfully deleted"}) else: return jsonify({"Message":"Connection didn't existed"}) else: #this should never be reached return jsonify({"Message":"Error: http request was invalid"})
def get_borrowed_books(): cur_user = current_user() borrowedBooks = [] for bookcopy in cur_user.get_borrowed_books(): book = Book.get_by_id(bookcopy.book.id()) owner = UserAccount.get_by_id(bookcopy.owner.id()) bookInfo = dict() bookInfo["title"] = book.title bookInfo["author"] = book.author bookInfo["copyID"] = bookcopy.key.id() bookInfo["ownerId"] = bookcopy.owner.id() bookInfo["owner"] = owner.name bookInfo["due_date"] = str(bookcopy.due_date) borrowedBooks.append(bookInfo) return jsonify({"borrowedBooks":borrowedBooks})
def get_borrowed_items(): cur_user = current_user() borrowedItems = [] for itemcopy in cur_user.get_borrowed_books(): if not itemcopy.manual_borrower_name: #Don't include items the user is manually lending (they would come up because the borrower is set to the user) item = Item.get_by_id(itemcopy.item.id()) owner = UserAccount.get_by_id(itemcopy.owner.id()) itemInfo = dict() itemInfo["title"] = item.title itemInfo["author"] = item.author itemInfo["copyID"] = itemcopy.key.id() itemInfo["ownerId"] = itemcopy.owner.id() itemInfo["owner"] = owner.name itemInfo["due_date"] = str(itemcopy.due_date) borrowedItems.append(itemInfo) return jsonify({"borrowedItems":borrowedItems})
def profile(userID): profile_user = UserAccount.get_by_id(int(userID)) user = current_user() if not profile_user: return render_response('invalidprofile.html') if user.is_connected(profile_user): library = [] for copy in profile_user.get_library(): book = Book.query(Book.key == copy.book).get() library.append(book) if copy.borrower is None: book.available = True else: book.available = False book.copyid = copy.key.id() return render_response('profile.html',profile_user=profile_user,library=library) return render_response('invalidprofile.html')
def setup_item_borrow_actions(lenderID, itemCopyID): borrower = current_user() lender = UserAccount.getuser(int(lenderID)) itemCopy = ItemCopy.get_by_id(int(itemCopyID)) rtb1 = RequestToBorrow() rtb1.useraccount = lender.key rtb1.connection = borrower.key rtb1.item = itemCopy.key rtb1.put() wtb1 = WaitingToBorrow() wtb1.useraccount = borrower.key wtb1.connection = lender.key wtb1.item = itemCopy.key wtb1.put() return jsonify({"Message":"OK"})
def get_lent_items(): cur_user = current_user() lentItems = [] for itemcopy in cur_user.get_lent_books(): item = Item.get_by_id(itemcopy.item.id()) borrower = UserAccount.get_by_id(itemcopy.borrower.id()) itemInfo = dict() itemInfo["title"] = item.title itemInfo["author"] = item.author itemInfo["copyID"] = itemcopy.key.id() itemInfo["borrowerId"] = itemcopy.borrower.id() itemInfo["borrower"] = borrower.name itemInfo["due_date"] = str(itemcopy.due_date) if itemcopy.manual_borrower_name: itemInfo["manual_borrower_name"] = itemcopy.manual_borrower_name itemInfo["manual_borrower_email"] = itemcopy.manual_borrower_email lentItems.append(itemInfo) return jsonify({"lentItems":lentItems})
def search_network(item_key): user = current_user() networkuserlist = {} for connection in user.get_connections(): u = UserAccount.getuser(connection.id()) for copy in u.get_library(): if Item.query(Item.key == copy.item).get().item_key == item_key: user = {} user["username"] = u.name user["itemCopyID"] = copy.key.id() if copy.borrower == None: user["available"] = "True" else: user["available"] = "False" networkuserlist[u.get_id()] = user return jsonify(networkuserlist)
def see_who_in_network_has_book(OLKey): user = current_user() networkuserlist = {} string = "" for connection in user.get_connections(): u = UserAccount.getuser(connection.id()) for copy in u.get_library(): if copy.OLKey == OLKey: user = {} user["username"] = u.name user["bookCopyID"] = copy.key.id() if copy.borrower == None: user["available"] = "True" else: user["available"] = "False" networkuserlist[u.get_id()] = user return jsonify(networkuserlist)
def discover(): # Start by creating a list of items (as dicts) within the user's library # This is necessary prep to be able to show that the item is in the user's library librarylist = {} useraccount = current_user() for copy in useraccount.get_library(): item = Item.query(Item.key == copy.item).get().to_dict() item["item_subtype"] = copy.item_subtype item["escapedtitle"] = re.escape(item["title"]) librarylist[(item["item_key"],item["item_subtype"])] = item # Create a list of all items (as dicts) in the user's network user = current_user() itemlist = [] for connection in user.get_connections(): u = UserAccount.getuser(connection.id()) for copy in u.get_library(): item = Item.query(Item.key == copy.item).get().to_dict() item["item_subtype"] = copy.item_subtype item["escapedtitle"] = re.escape(item["title"]) if copy.borrower is None: item["available"] = True else: item["available"] = False # Check to see if book is in the user's library item["inLibrary"] = [] for item_subtype in ['book', 'ebook', 'audiobook']: if (item["item_key"],item_subtype) in librarylist: item["inLibrary"].append(item_subtype) itemlist.append(item) # Sort itemlist alphabetically, with title as the primary sort key, # author as secondary, and item_subtype as tertiary itemlist.sort(key=lambda item: item["item_subtype"]) itemlist.sort(key=lambda item: item["title"].lower()) #Remove duplicate books (dictionaries) from itemlist (list) dedupeditemlist = [] for item in itemlist: if item not in dedupeditemlist: dedupeditemlist.append(item) return render_response('discover.html',itemlist=dedupeditemlist)
def account(request): try: profile = request.user.useraccount except UserAccount.DoesNotExist: profile = UserAccount(user=request.user) my_form = UserAccountForm() if request.method == "POST": form = UserAccountForm(request.POST, instance=profile) if form.is_valid(): form.save() messages.success(request, ' Account Details Submitted Successfully') else: messages.error(request, 'Oops!!! There are Some Errors in your Form') else: form = UserAccountForm(instance=profile) return render(request, 'accounts/account_details.html', { 'form': form, })
def test_recipe_create_page_render(self, api_client): new_user = UserAccount() api_client.force_authenticate(new_user) create_recipe_page_render = api_client.get(create_recipe_url) assert create_recipe_page_render.status_code == 405 # 405 = method not allowed - get isnt allowed only post
def create(self, validated_data): return UserAccount(**validated_data)
import pytest from django.urls import reverse import conftest from accounts.models import UserAccount from factories import UserFactory top_rated_accounts_url = UserAccount.get_top_rated_accounts_url() # ------------------------------------------------ Tests pytestmark = pytest.mark.django_db def test_signup_success(signup): assert signup.response.status_code == 201 def test_login_fail_without_signup(api_client): user_data = UserFactory.build() login_url = '/api/users/login/' user_data = { 'email': user_data.email, 'password': user_data.password, } response = api_client.post(login_url, user_data) assert response.status_code == 400 def test_login_success(signup_and_login): assert signup_and_login.response.status_code == 200
def userpage(request, user): if request.method == 'POST': uploaded_file = request.FILES["document"] fs = UserAccount(file_user=uploaded_file) fs.save(uploaded_file) return render(request, 'user.html')
def get_user_email(userID): userEmail = UserAccount.get_by_id(int(userID)).email emailSplit = userEmail.split("@", 1) privacyEmail = userEmail[0:1] + '******@' + emailSplit[1] return jsonify({"email": privacyEmail})
def load_user(id): return UserAccount.getuser(int(id))
def profile(userID): try: int(userID) profile_user = UserAccount.get_by_id(int(userID)) # Check if profile user has a custom url and forward if so if profile_user.custom_url: try: long(profile_user.custom_url) # Custom URLs MUST include at least one letter, so this will always fail with a custom URL except: return redirect('/user/' + profile_user.custom_url) except: # Query custom URLs custom_url_user = UserAccount.query(UserAccount.custom_url==userID).get() if custom_url_user: profile_user = custom_url_user else: return redirect(url_for("invalid_profile")) user = current_user() if user.is_authenticated(): inNetwork = user.is_connected(profile_user) else: inNetwork = False if inNetwork or profile_user.profile_privacy == 1: if user == profile_user: inNetwork = True booklist = [] for copy in profile_user.get_library(): item = Item.query(Item.key == copy.item).get().to_dict() if item["item_type"] == "book": item["item_subtype"] = copy.item_subtype item["star_rating"] = copy.star_rating item["escapedtitle"] = re.escape(item["title"]) if copy.borrower is None: item["available"] = True else: item["available"] = False item["copyID"] = copy.key.id() booklist.append(item) # Sort library alphabetically, with title as the primary sort key, # author as secondary, and item_subtype as tertiary booklist.sort(key=lambda item: item["item_subtype"]) booklist.sort(key=lambda item: item["title"].lower()) movielist = [] for copy in profile_user.get_library(): item = Item.query(Item.key == copy.item).get().to_dict() if item["item_type"] == "movie": item["item_subtype"] = copy.item_subtype item["star_rating"] = copy.star_rating item["escapedtitle"] = re.escape(item["title"]) if copy.borrower is None: item["available"] = True else: item["available"] = False item["copyID"] = copy.key.id() movielist.append(item) # Sort library alphabetically, with title as the primary sort key, # author as secondary, and item_subtype as tertiary movielist.sort(key=lambda item: item["item_subtype"]) movielist.sort(key=lambda item: item["title"].lower()) import hashlib import urllib gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(profile_user.email).hexdigest() + "?s=150&d=" + urllib.quote(request.host_url,'') + "static%2Fimg%2Fnoimage.png" return render_response('profile.html',inNetwork=inNetwork,profile_user=profile_user,booklist=booklist,movielist=movielist,gravatar_url=gravatar_url) return redirect(url_for("invalid_profile"))
def test_get_top_rated_accounts_url(): assert UserAccount.get_top_rated_accounts_url() == reverse('accounts:top')
def search(): itemlist = {} item_type = request.args.get('item_type') subtype_book = request.args.get('subtype_book') subtype_ebook = request.args.get('subtype_ebook') subtype_audiobook = request.args.get('subtype_audiobook') subtype_dvd = request.args.get('subtype_dvd') subtype_bluray = request.args.get('subtype_bluray') user_email = request.args.get('user_email') searchterm = request.args.get('query') attr = request.args.get('refineSearch') src = request.args.get('src') # If searching for a user, redirect to profile if user_email: profile_user = UserAccount.query(UserAccount.email==searchterm).get() if not profile_user: return redirect(url_for("invalid_profile")) else: if profile_user.custom_url: return redirect('/user/' + profile_user.custom_url) else: return redirect('/user/' + str(profile_user.get_id())) subtype_specified = "true" # Used in javascript to determine whether out-of-network cookie should be respected or not if item_type is None and subtype_book is None and subtype_ebook is None and subtype_audiobook is None and subtype_dvd is None and subtype_bluray is None: #Nothing was specified, so act as if they searched books item_type = "book" if subtype_book or subtype_ebook or subtype_audiobook or subtype_dvd or subtype_bluray: # If subtype is included, item_type may not be, so it must be added if subtype_book or subtype_ebook or subtype_audiobook: item_type = "book" if subtype_dvd or subtype_bluray: item_type = "movie" else: # None are included, so only item_type is being pass; set all subtypes to true if item_type == "book": subtype_specified = "false" subtype_book = "true" subtype_ebook = "true" subtype_audiobook = "true" elif item_type == "movie": subtype_specified = "false" subtype_dvd = "true" subtype_bluray = "true" if attr == "all": attr = None if searchterm is None: searchterm = "" else: searchterm = searchterm.lstrip() if searchterm is None or searchterm == "": pass else: cur_user = current_user() logging.info(cur_user) if not cur_user.is_authenticated(): #Assume no books in library or network, return results only itemlist = Item.search_by_attribute(item_type,searchterm,attr) for item in itemlist: item["inLibrary"] = [] item["inNetwork"] = [] else: user = current_user() #Create a dictionary of the user's items librarylist = {} for copy in user.get_library(): copyItemKey = Item.query(Item.key == copy.item).get().item_key copyItemSubtype = copy.item_subtype librarylist[(copyItemKey,copyItemSubtype)] = copy.to_dict() #Create a dictionary of the items in the user's network #The dict, networkitemlist, includes each ItemCopy object, with it's associated item_key. networkitemlist = {} for connection in user.get_connections(): u = UserAccount.getuser(connection.id()) for copy in u.get_library(): copyItemKey = Item.query(Item.key == copy.item).get().item_key copyItemSubtype = copy.item_subtype networkitemlist[(copyItemKey,copyItemSubtype)] = copy.to_dict() itemlist = Item.search_by_attribute(item_type,searchterm,attr) for item in itemlist: item["escapedtitle"] = re.escape(item["title"]) # Check for copies in library and in network, # return "inLibrary" list with all item types in Library # return "inNetwork" list with all item types in Library item["inLibrary"] = [] item["inNetwork"] = [] for item_subtype in ['book', 'ebook', 'audiobook', 'dvd', 'bluray']: if (item["item_key"],item_subtype) in librarylist: item["inLibrary"].append(item_subtype) if (item["item_key"],item_subtype) in networkitemlist: item["inNetwork"].append(item_subtype) return render_response('search.html', itemlist=itemlist, search=searchterm, attribute=attr, include_type=item_type, subtype_book=subtype_book, subtype_ebook=subtype_ebook, subtype_audiobook=subtype_audiobook, subtype_specified=subtype_specified, src=src)