def resolve_user(self, args, **kwargs): id = kwargs.get('id') email = kwargs.get('email') if id: return User.objects(pk=id).first() elif email: return User.objects(email=email).first() else: raise Exception('Mala consulta!')
def get_attendees(event_id, attendee_type): user_id = auth.check_token(request.headers.get('session')) if not user_id: return "Unauthorized request: Bad session token", 401 user = Organizer.find_id(user_id) if not user: return "Unauthorized request: User doesn't have permission", 401 if not event_id: return "Event ID required", 400 event = Event.find_event(event_id) if not event: return "Event not found", 404 attendee_type = attendee_type.lower() if attendee_type not in ['attendees', 'students', 'mentors', 'organizers']: return "Invalid Attendee Type", 404 attendees = None if attendee_type == 'attendees': attendees = { 'students': [], 'mentors': [], 'organizers': [], 'checkins': [] } for usr in User.objects(events=event.id): if usr.type in ['student', 'mentor', 'organizer']: attendees[usr.type + 's'].append(usr.to_dict()) else: if not attendees['other']: attendees['other'] = [] attendees['other'].append(usr.to_dict()) for usr in User.objects(checkins=event.id): attendees['checkins'].append(usr.to_dict()) else: attendees = [] attendee_cls = None if attendee_type == 'students': attendee_cls = Student elif attendee_type == 'mentors': attendee_cls = Mentor elif attendee_type == 'organizers': attendee_cls = Organizer else: attendee_cls = User for usr in attendee_cls.objects(events=event.id): attendees.append(usr.to_dict()) return json.dumps(attendees), 200, jsonType
def mutate(root, info, **kwargs): user = User.objects(email=kwargs.get('email')).first() if not user: raise Exception('El usuario no existe') chat = Chat.objects(users__in=[user]) if chat: raise Exception('Ya hay un chat con el usuario') chat = Chat(users=[User.objects( pk=get_jwt_identity()).first(), user]).save() return CreateChat(chat)
def forgot_password(): data = request.json if 'tkn' in request.args: # TODO: check the token and set new password return jsonify({'tkn': request.args['tkn']}) else: if not data or 'email' not in data: return jsonify({'message': 'Missing email field in data'}), 400 user = User.objects(email=data['email']).first() if user is None: return jsonify({'message': 'User not found'}), 404 tkn = uuid.uuid4().hex msg = Message('Forgot password', recipients=[user.email]) new_pass_url = url_for('.forgot_password', tkn=tkn, _external=True) msg.html = 'A password change for your account has been requested. ' \ 'Click here to reset your password: <a href="{url}">{url}</a>'.format(url=new_pass_url) mail.send(msg) return jsonify( {'message': 'Email sent to user with further instructions'})
def login(): auth = request.authorization error_msg = {'message': 'Could not verify'} if not auth or not auth.username or not auth.password: return jsonify(error_msg, 401, {'WWW-Authenticate': 'Basic realm="Login required!"'}) user = User.objects(email=auth.username).first() if not user: return jsonify(error_msg), 401, { 'WWW-Authenticate': 'Basic realm="Login required!"' } if check_password_hash(user.password_hash, auth.password): token = jwt.encode( # the payload which will be encoded { 'public_id': user.public_id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=7) }, # key to use for encoding, which is needed when decoding. This is application specific app.config['SECRET_KEY']) return jsonify({'token': token, 'user': user_schema.dump(user).data}) return jsonify(error_msg), 401, { 'WWW-Authenticate': 'Basic realm="Login required!"' }
def authenticate(email, password): user = User.objects(email=email).first() if user and safe_str_cmp( user.password.encode('utf-8'), hashlib.sha256(password.encode('utf-8')).hexdigest()): return user return None
def register(): if not request.is_json: return jsonify({"msg": "Error mala consulta"}), 400 email = request.json.get('email', None) password = request.json.get('password', None) firstName = request.json.get('firstName', None) lastName = request.json.get('lastName', None) if not email: return jsonify({"msg": "El correo electrónico es requerido"}), 400 if not password: return jsonify({"msg": "La contraseña es requerida"}), 400 if not firstName: return jsonify({"msg": "El nombre del usuario es requerido"}), 400 if not lastName: return jsonify({"msg": "Los apellido del usuario es requerido"}), 400 if User.objects(email=email).first(): return jsonify({"msg": "El correo electrónico ya esta registrado"}), 400 user = User(email=email, first_name=firstName, last_name=lastName) user.set_password(password) user.save() return jsonify({ "msg": "Creado con éxito" }), 200
def post_load(self, data): if 'country_id' in data: data['country'] = Country.objects(country_code=data['country_id']).first() del data['country_id'] if 'owner_id' in data: data['owner'] = User.objects(pk=data['owner_id']).first() del data['owner_id'] if 'collaborator_ids' in data: collabs = [] for collab_id in data['collaborator_ids']: collabs.append(User.objects(pk=collab_id).first()) data['collaborators'] = collabs del data['collaborator_ids'] if 'latitude' in data: data['latitude'] = float(data['latitude']) if 'longitude' in data: data['longitude'] = float(data['longitude'])
def find_incomplete(token): print("line 1", token) user = User.objects(completion_token=token) print("line 2", user) if not user or len(user) < 1: return "Token invalid", 404 print("line 3") return json.dumps({ 'session': auth.create_token(user[0].id), 'user': user[0].to_dict() }), 200, jsonType
def user_exists(self, user_id): if user_id is not None: valid = True try: if User.objects(id=user_id).first() is None: valid = False except (DoesNotExist, MValidationError): valid = False if not valid: raise ValidationError('This user does not exists')
def mutate(root, info, **kwargs): user = User.objects(pk=get_jwt_identity()).first() first_name = kwargs.get('first_name') last_name = kwargs.get('last_name') if first_name: user.first_name = first_name if last_name: user.last_name = last_name user.save() return UpdateUserProfile(user)
def decorated(*args, **kwargs): token = get_bearer_token() current_user = None if token is not None: try: data = jwt.decode(token, current_app.config['SECRET_KEY']) current_user = User.objects( public_id=data['public_id']).first() except jwt.JWTError: pass return f(current_user, *args, **kwargs)
def populate(): print('populating countries') for country in countries: Country(**country).save() # populate users print('populating users') for user in users: User(**user).save() # populate projects print('populating projects') for project in projects: owner = User.objects(public_id=project['owner']).first() country = Country.objects(country_code=project['country']).first() collaborators = [] for collab in project['collaborators']: collaborators.append(User.objects(public_id=collab).first()) del project['owner'] del project['country'] del project['collaborators'] p = Project(**project) p.owner = owner p.collaborators += collaborators p.country = country p.save() print('populating donations') for donation in donations: project = Project.objects(title=donation['project']).first() donator = User.objects(public_id=donation['donator']).first() del donation['project'] del donation['donator'] d = Donation(**donation) d.project = project d.donator = donator d.save()
def login(): form_email = request.get_json().get('email') form_password = request.get_json().get('password') user = User.objects(email=form_email).first() if not user or not user.email: return 'Email not found', 404 hashed = user.password.encode('utf-8') if bcrypt.hashpw(form_password.encode('utf-8'), hashed) == hashed: return json.dumps({ 'session': create_token(user.id), 'user': user.to_dict() }), 200, jsonType else: return 'Incorrect password', 401
def search(): user_query = User.objects.all() project_query = Project.objects.all() if 'q' in request.args: q = request.args['q'] user_query = User.objects(username__icontains=q).all() project_query = Project.objects(title__icontains=q).all() return jsonify({ 'projects': project_schema.dump(project_query.all(), many=True).data, 'users': user_schema.dump(user_query, many=True).data })
def decorated(*args, **kwargs): token = get_bearer_token() if not token: return jsonify({'message': 'Token is missing!'}), 401 try: data = jwt.decode(token, current_app.config['SECRET_KEY']) current_user = User.objects(public_id=data['public_id']).first() if current_user is None: raise jwt.JWTError() except jwt.JWTError as e: return jsonify({ 'message': 'Token is invalid!', 'error': str(e) }), 401 return f(current_user, *args, **kwargs)
def create_project(): user_id = auth.check_token(request.headers.get('session')) if not user_id: return "Unauthorized request: Bad session token", 401 user = User.find_id(user_id) if not user: return "User not found", 404 project = Project() event_id = request.json.get('event') if not event_id: return "Event is required", 400 event = Event.find_event(event_id) if not event: return "Event not found", 404 if not (event in user.events or event.id in user.events): return "User not attending event", 400 teammate_email = request.json.get('teammate') # A team is required if not teammate_email: return "Teammate email is required", 400 teammate = User.objects(email=teammate_email).first() if not teammate: return "Teammate not found", 404 if not (event in teammate.events or event.id in teammate.events): return "Teammate not registered for event", 400 project.name = request.json.get('name') project.description = request.json.get('description') project.image = request.json.get('image') project.event = event project.team = [] project.team.append(user) project.team.append(teammate) project.save() if not project.id: return 'Error creating project', 500 return project.select_related(max_depth=1).to_json()
def remove_teammate(project_id): project = Project.find_id(project_id) if not project: return "Project not found", 404 teammate_email = request.json.get('teammate') # A team is required if not teammate_email: return "Teammate email is required", 400 teammate = User.objects(email=teammate_email).first() if not teammate: teammate = user.find_id(teammate_email) if not teammate or not teammate in project.team: return "Teammate not found", 404 project.team.remove(teammate) project.save() return project.to_json()
def signup(): form_name = request.json['name'] form_email = request.json['email'] form_password = request.json['password'] form_type = request.json['type'] # student or mentor if len(form_password) < 8: return 'Password must be 8 characters or longer', 400 if User.objects(email=form_email).first(): return 'Email already exists', 400 user = User() if form_type == 'student': user = Student() elif form_type == 'mentor': user = Mentor() elif form_type == 'organizer': if app.config['PRODUCTION']: return "Error: User doesn't have permission", 401 user = Organizer() for key, value in request.get_json().items(): if key == "password": setattr(user, key, bcrypt.hashpw(value.encode('utf-8'), bcrypt.gensalt())) elif not key.startswith( '_' ) and not key == "id" and not key == "type" and value != "": # Some security setattr(user, key, value) user.save() if not user.id: return 'Error creating account', 500 return json.dumps({ 'session': auth.create_token(user.id), 'user': user.to_dict() }), 200, jsonType
def add_teammate(project_id): project = Project.find_id(project_id) if not project: return "Project not found", 404 teammate_email = request.json.get('teammate') # A team is required if not teammate_email: return "Teammate email is required", 400 teammate = User.objects(email=teammate_email).first() if not teammate: return "Teammate not found", 404 if not project.event in teammate.events: return "Teammate not registered for event", 400 if len(project.team) >= 5: return "Your team is full. Max team size is 5 people.", 400 project.team.append(teammate) project.save() return project.select_related(max_depth=1).to_json()
def unique_email(self, email): if not self.partial and User.objects(email=email).count() > 0: raise ValidationError('User with this email already exists')
def find_user_email(user_email): user = User.objects(email=user_email).first() if not user: return "User not found", 404 return user.to_json()
def register(event_id): user = None discount = False sg = sendgrid.SendGridClient('gopilot', app.config["SENDGRID_PASS"]) event = Event.find_event(event_id) if not event: return "Event not found", 404 price = event.price if hasattr(request, 'json') and request.json and 'user' in request.json: if User.objects(email=request.json['user']['email']).first(): return json.dumps({ "status": "failed", "reason": "email", "message": "Your email already has a Pilot account." }), 400, jsonType print("has user") user = Student() user.name = request.json['user']['name'] user.email = request.json['user']['email'] user.complete = False user.completion_token = random_uuid().hex if 'discount' in request.json and request.json['discount'] != False: print("has discount") # user.save() discount = checkDiscount(request.json['discount']) if discount: price -= discount print("Charging user %s" % price) if 'stripe_token' in request.json: print("has stripe") stripe.api_key = app.config['STRIPE_KEY'] try: customer = stripe.Customer.create( source=request.json['stripe_token'], description=user.name, email=user.email) except stripe.CardError, e: app.logger.error("Customer Card Error: " + str(e)) err = e.json_body['error'] return json.dumps({ "status": "failed", "reason": err['param'] if ('param' in err) else 'customer', "message": err['message'] }), 400, jsonType user.stripe_id = customer.id try: stripe.Charge.create( amount=(price * 100), ## Cents currency="usd", customer=customer.id, description="Registration for " + event.name) except stripe.CardError, e: print("Charge Card Error", e) err = e.json_body['error'] return json.dumps({ "status": "failed", "reason": err['param'] if ('param' in err) else 'charge', "message": err['message'] }), 400, jsonType
def resolve_me(self, args, **kwargs): user = User.objects(pk=get_jwt_identity()).first() if user: return user raise Exception('El usuario no está en sesión!')
def get_all_users(current_user: User): users = User.objects() return jsonify({ 'users': UserSchema(exclude=['projects']).dump(users, many=True).data })
def resolve_chats(self, args, **kwargs): user = User.objects(pk=get_jwt_identity()).first() return Chat.objects.filter(users__in=[user])