def view_profile(): """get user profile""" user_details = user_authentication.verify_and_decode_cookie() # print('view profiles', user_details) if user_details is None: # if unable to verify cookie, go to login page. response = jsonify("user not logged in") return response # if cookie is invalid eg expired, return an error to trigger the log out from frontend elif user_details == 'invalid cookie': response = jsonify(error="invalid cookie") response.status_code = 500 return response # get user's deck and order them by date created. # complex queries require indexing in firebase (which i already created) docs = db.collection(u'Decks').where(u'created_by', u'==', user_details.get('email')) \ .order_by(u'created_at', direction=firestore.Query.DESCENDING)\ .stream() x = user_details.get('email') doc_ref = db.collection(u'Users').document(x).get() first_name = doc_ref.get('firstName') deck_list = [] for doc in docs: #print(f'{doc.id} => {doc.to_dict()} \n') deck_list.append(doc.to_dict()) decks_in_json = json.dumps(deck_list) return jsonify( \ first_name=first_name, \ email=user_details.get('email'),\ profile=decks_in_json)
def complete_experiment(self): if (experiment_doc_ref): # Remove from inprogress db.collection("inprogress").document( self.experiment_doc_ref.id).delete() # Mark as completed self.experiment_doc_ref.set({u'completed': True}, merge=True) self.completed = True
def get_deck(deck_id): """get deck using their id""" user_details = user_authentication.verify_and_decode_cookie() if user_details is None: # if unable to verify cookie, go to login page. return redirect('/login') doc = db.collection(u'Users').document(user_details.get('email')).get() deckid_array = doc.get('deckId') # check if deck_id is in user's document in firestore, to ascertain ownership. if request.method == 'GET': if deck_id in deckid_array: deck_blob = bucket.get_blob(f"{deck_id}.apkg") if deck_blob is not None: url = deck_blob.generate_signed_url( version="v4", expiration=datetime.timedelta(minutes=15), method="GET") response = jsonify(status="Success", URL=url) return response else: response = jsonify(status="Failed", message="Deck does not exist") response.status_code = 400 return response else: response = jsonify(status="Failed", message="Deck is not yours") response.status_code = 400 return response elif request.method == "DELETE": # if deck id is in user's deck, delete deck if deck_id in deckid_array: # delete deck document from deck collection db.collection(u'Decks').document(deck_id).delete() # update user's deckid array deckid_array.remove(deck_id) db.collection(u'Users').document(user_details.get('email')) \ .update({u'deckId': deckid_array}) # delete from storage bucket.get_blob(f"{deck_id}.apkg").delete() response = jsonify(status="Success", message=f"{deck_id}.apkg deleted") response.status_code = 200 return response return 'deck does not exist'
def __check_inprogress(self): docs = db.collection("inprogress").order_by( u'createdAt', direction=firestore.Query.DESCENDING).stream() inp = [d.to_dict() for d in docs] if (len(inp) > 0): # There are still some in-progress left left return inp else: return None
def user_signup(self, first_name, last_name, email, password, confirm_password): """function to sign up user with fire base""" try: # validators for first and last name, cannot be empty if first_name == "": response = jsonify(first_name="Please fill in your first name") response.status_code = 400 return response if last_name == "": response = jsonify(last_name="Please fill in your last name") response.status_code = 400 return response # validate password confirm password if password == confirm_password: new_user = self.auth.create_user_with_email_and_password( email, password) # lowercased email so easier to query for document doc_ref = db.collection(u'Users').document(email.lower()) doc_ref.set({ u'firstName': first_name, u'lastName': last_name, u'email': email, u'createdAt': datetime.now().isoformat(), u'deckId': [], u'id': new_user['localId'] }) token = new_user.get('idToken') return self.change_token_for_cookie(token) if password != confirm_password: response = jsonify( confirm_password="******") response.status_code = 400 return response except requests.exceptions.HTTPError as error: # these are pyrebase exceptions. # convert text into json and parse it error_json = error.args[1] error = json.loads(error_json)['error']['message'] if error == "INVALID_EMAIL": response = jsonify(email="Invalid email") response.status_code = 400 return response elif error == "EMAIL_EXISTS": response = jsonify(email="Email already used") response.status_code = 400 return response else: response = jsonify(general=error) response.status_code = 500 return response
def __add_to_inprogress(self, experiment_id): ref = db.collection("inprogress").document(experiment_id) ref.set({ "experimentID": experiment_id, "createdAt": datetime.datetime.now() })
def create_deck(): """create deck api""" if request.method == 'POST': user_details = user_authentication.verify_and_decode_cookie() #print(user_details.get('email')) if user_details == None: # if unable to verify cookie, go to login page. # need to redirect front end to login page not backend. response = jsonify(error="User not authenticated") response.status_code = 500 return response #if user's cookie is invalid, log the user out and prompt for log in elif user_details == "invalid cookie": response = jsonify(error="invalid cookie") response.status_code = 500 return response # Get user info from form deck_input = request.json['input'] deck_title = request.json['title'] # Get style chosen by the user deck_css = request.json['css'] # ensure all inputs are non-empty # deck css will have a default setting so no need to check. if deck_title.strip() == "": response = jsonify(deck_title="Deck title must not empty") response.status_code = 400 print(response.data) return response if deck_input.strip() == "": response = jsonify(deck_input="Deck input must not empty") response.status_code = 400 print(response.data) return response create_anki_deck_with_string_input(deck_title, deck_input, deck_css) # Deck class details added deck = Deck(deck_title, user_details.get('email'), datetime.datetime.now(datetime.timezone.utc).isoformat()) # upload files to storage bucket.blob(f"{deck.deck_id}.apkg").upload_from_filename( f"{deck_title}.apkg") # remove deck from server os.remove(f"{deck_title}.apkg") # use this to print URL # add deck to database db.collection(u'Decks').document(deck.deck_id).set(deck.to_dict()) # add deck's id to user print(user_details.get('email')) db.collection(u'Users').document(user_details.get('email')) \ .update({u'deckId': firestore.ArrayUnion([deck.deck_id])}) response = jsonify(status="Success") response.status_code = 200 return response #TODO finish else portion of logic return "hello"