def SetUp(self): graph.delete_all() User.add({ "email": self.default_username, "name": "Ignat", "surname": "Petrov" })
def patch(user_id): data = request.get_json() user = User.update(user_id, data) user_string = json.dumps(user) user_json = json.loads(user_string) emit('user_changed', user_json, namespace='/', broadcast=True) return jsonify(user)
def test_patch_user(self): self.SetUp() tester = app.test_client(self) body = {"name": "ChangedName"} id = User.find_all()[0]['id'] response = tester.patch(f'/api/users/{id}', headers={'Content-Type': 'application/json'}, data=json.dumps(body)) data = json.loads(response.data.decode()) self.assertEqual(response.status_code, 200) self.assertEqual(data['name'], 'ChangedName')
def test_one_user_dont_exist(self): self.SetUp() tester = app.test_client(self) response = tester.post('/api/login', headers={'Authorization': self.auth}) data = json.loads(response.data.decode()) token = data['token'] id = User.find_all()[0]['id'] response = tester.get(f'/api/users/{64512341235126431}', headers={'x-access-token': token}) data = json.loads(response.data.decode()) self.assertEqual(data['message'], "User not found!")
def make_connections(users, task, connection_type): if users: if type(users) == list: for user_id in users: user = User.find_one(user_id) if user.get("message") == "User not found!": return {"message": f"User {user_id} not found"} user_task_rel = Relationship(user, connection_type, task) graph.create(user_task_rel) return {} else: return {"message": "The users attributes must be lists!"} else: return {}
def find_all_projects_of_user(user_id): user = User.find_one(user_id) if user.get('message') == "User not found!": return {"message": f"User {user_id} not found"} projects = [] for rel in graph.match(start_node=user, rel_type="IS_USER"): project = rel.end_node() project['id'] = remote(project)._id project['users'] = Project.find_users(project, "IS_USER") project['admins'] = Project.find_users(project, "IS_ADMIN") projects.append(project) # for rel in graph.match(start_node=user, rel_type="IS_ADMIN"): # project = rel.end_node() # project['id'] = remote(project)._id # if project not in projects: # projects.append(project) return projects
def delete(user_id): del_msg = User.delete(user_id) return jsonify(del_msg)
def get(current_user_id, user_id): user = User.find_one(user_id) return jsonify(user)
def post(): data = request.get_json() user = User.add(data) return jsonify(user)
def get(): users = User.find_all() return jsonify(Users=users)
def oauth_handler(blueprint, token): """ Handles incoming OAuth events, login, signup :param blueprint: :param token: :return: """ if token is None: # Failed logger.info("Failed to log in with {}.".format(blueprint.name)) flash(_("Error logging in")) return False try: if blueprint.name == "github": response = blueprint.session.get("/user") elif blueprint.name == "google": response = blueprint.session.get("/plus/v1/people/me") elif blueprint.name == "facebook": response = blueprint.session.get("/me?fields=email") else: logger.critical("Missing blueprint handler for {}".format(blueprint.name)) flash(_("Error logging in")) return False except ValueError as e: sentry_sdk.capture_exception(e) flash(_("Error logging in")) return False if not response.ok: # Failed logger.info("Failed to fetch user info from {}.".format(blueprint.name)) logger.info(response) flash(_("Error logging in")) return False response = response.json() oauth_user_id = response["id"] # Get user ID try: # Check if existing service link authentication_link = AuthLinks.query.filter_by( provider=blueprint.name, provider_user_id=str(oauth_user_id), ).one() except NoResultFound: # New service link, at least store the token authentication_link = AuthLinks( provider=blueprint.name, provider_user_id=str(oauth_user_id), token=token["access_token"], ) logger.info("User not found, keeping token in memory") except Exception as e: # Failure in query! sentry_sdk.capture_exception(e) logger.error("Failed querying authentication links") flash(_("That account is not linked to any system account, check if you already have an account.")) return False # Link exists and it is associated with an user if authentication_link is not None and authentication_link.user_id is not None: login_user(User.query.get(authentication_link.user_id)) db.session.commit() logger.info("Successfully signed in with {}.".format(blueprint.name)) return False elif authentication_link is not None and \ authentication_link.user_id is None and \ "user_id" in session.keys(): try: authentication_link.user_id = int(session["user_id"]) # Update link with user id db.session.add(authentication_link) db.session.commit() return False except Exception as e: db.session.rollback() sentry_sdk.capture_exception(e) logger.error("Could not store user and oauth link") flash(_("Error signing up, please try again")) return False else: # Link does not exist or not associated if "oauth_sign_up" in session.keys() and \ session["oauth_sign_up"]: # If registration session["oauth_sign_up"] = False if "email" in response.keys(): user_email = response["email"] else: if "emails" in response.keys() and len(response["emails"]) > 0: user_email = response["emails"][0]["value"] else: user_email = None if "name" in response.keys(): if blueprint.name == "google": if "givenName" in response["name"].keys(): user_name = response["name"]["givenName"] else: logger.info("Google user does not have a givenName") flash(_("Error signing up")) return False else: user_name = response["name"] else: logger.info("User does not have a name!") flash(_("Error signing up")) return False if user_email is None or \ len(user_email) < len("*****@*****.**") or \ "@" not in user_email: # I'll assume noone with their own TLD will use this logger.info("User email is wrong or missing, trying other API endpoint") try: if blueprint.name == "github": # If we're authenticating against GitHub then we have to do # another get response = blueprint.session.get("/user/emails") if not response.ok: flash(_("Error signing up")) logger.info("Error requesting email addresses") return False else: response = response.json() if len(response) > 0 and "email" in response[0].keys(): user_email = response[0]["email"] else: user_email = None # Take the first email if not response[0]["verified"] or \ user_email is None or \ len(user_email) < len("*****@*****.**") or \ "@" not in user_email: flash(_( "You have no associated email addresses with your account or none of them are valid")) logger.error("User does not have any emails or none of them are valid") return False else: pass # All is okay again pass # New email is fine else: logger.info("No email addresses associated with the account") flash(_("You have no associated email addresses with that account")) return False except Exception: logger.info("Error asking for another emails") flash(_("Error signing up")) return False else: pass # Email is okay try: # Check if existing service link User.query.filter(User.email == user_email).one() flash(_("This email address is in use, you must log in with your password to link {provider}" .format(provider=blueprint.name))) logger.debug("Email address is in use, but not linked, to avoid hijacks the user must login") return False except NoResultFound: # Do not allow same email to sign up again pass user = User( email=user_email, username=user_name, password=hash_password(token_bytes(100)), active=True ) flash(_("Password is set randomly, use \"Forgot password\" to set another password")) try: db.session.add(user) # Populate User's ID first by committing db.session.commit() except Exception as e: db.session.rollback() sentry_sdk.capture_exception(e) logger.error("Could not store user and oauth link") flash(_("Error signing up")) return False try: authentication_link.user_id = user.id # Update link with user id db.session.add(authentication_link) db.session.commit() except Exception as e: db.session.rollback() sentry_sdk.capture_exception(e) logger.error("Could not store user and oauth link") flash(_("Error signing up")) return False login_user(user) db.session.commit() logger.info("Successfully signed up with {}.".format(blueprint.name)) return False else: logger.debug("User does not wish to sign up") flash(_("You do not have an account")) return False