def request_new_image(_name, room, data): print( "WARNING: using the new_image command is deprecated. Call `set_attribute` directly instead" ) if len(data) < 1: return if len(data) > 1: receiver = User.from_id(data[1]) if not receiver: return emit('new_image', { 'url': data[0], 'user': current_user.serialize(), 'timestamp': timegm(datetime.now().utctimetuple()), }, room=receiver.sid()) log({ 'type': "new_image", 'room': room.id(), 'url': data[0], 'receiver': receiver.id(), }) else: emit('new_image', { 'url': data[0], 'user': current_user.serialize(), 'timestamp': timegm(datetime.now().utctimetuple()) }, room=room.name()) log({'type': "new_image", 'room': room.id(), 'url': data[0]})
def message_text(data): if 'receiver_id' in data: user = User.from_id(data['receiver_id']) print(f"private message: {data['msg']}") emit('message', { 'msg': data['msg'], 'user': current_user.serialize(), 'timestamp': timegm(datetime.now().utctimetuple()), }, room=user.sid()) log({ 'type': 'text', 'msg': data['msg'], 'room': user.latest_room().id(), 'receiver': data['receiver_id'] }) elif 'room' in data: print(f"room message: {data['msg']}") emit('message', { 'msg': data['msg'], 'user': current_user.serialize(), 'timestamp': timegm(datetime.now().utctimetuple()), }, room=Room.from_id(data['room']).name()) log({'type': 'text', 'msg': data['msg'], 'room': data['room']}) else: print("`text` requires `room` or `receiver_id` as parameters") return
def message_image(data): if 'receiver_id' in data: user = User.from_id(data['receiver_id']) print(f"private image: {data['image']}") emit('message', { 'image': data['image'], 'user': current_user.serialize(), 'width': data['width'] if 'width' in data else None, 'height': data['width'] if 'width' in data else None, 'timestamp': timegm(datetime.now().utctimetuple()), }, room=user.sid()) log({ 'type': 'image', 'msg': data['image'], 'room': user.latest_room().id(), 'receiver': data['receiver_id'] }) elif 'room' in data: print(f"room image: {data['image']}") emit('message', { 'image': data['image'], 'user': current_user.serialize(), 'width': data['width'] if 'width' in data else None, 'height': data['height'] if 'height' in data else None, 'timestamp': timegm(datetime.now().utctimetuple()), }, room=Room.from_id(data['room']).name()) log({'type': 'image', 'msg': data['image'], 'room': data['room']}) else: print("`image` requires `room` or `receiver_id` as parameters") return
def login(): if current_user.is_authenticated: return jsonify({ 'success': True, 'message': 'already autheticated', 'user': current_user.serialize() }) email = request.json.get('email') password = request.json.get('password') form = LoginForm(email=email, password=password) if form.validate(): user = User.query.filter_by(email=email).first() if user is None or not user.check_password(password): return jsonify({ 'success': False, 'message': 'You are not registered with us or Your password is wrong.' }) login_user(user) return jsonify({ 'success': True, 'message': 'Logged in Successfully', 'user': current_user.serialize() }) return jsonify({ 'success': False, 'message': 'Invalid form input', 'errors': form.errors })
def ping(message): emit('my_pong', {'timestamp': timegm(datetime.now().utctimetuple())}, room=request.sid) last_typing = message['typing'] if last_typing == 0: emit('start_typing', {'user': current_user.serialize()}, room=current_user.latest_room().name()) elif last_typing == 3: emit('stop_typing', {'user': current_user.serialize()}, room=current_user.latest_room().name())
def profile(): subjects = Subject.query.all() latest_messages = current_user.contacts_latest_messages() u = current_user placeholders = { 'title': u.prof.title, 'birth_date': u.birth_date.strftime("%d/%m/%Y"), 'about_me': u.prof.about_me, } educations = current_user.prof.educations experiences = current_user.prof.experiences """if request.method == 'POST': u.client.about_me = request.form['aboutMe'] #print request.form['birth_date'] u.birth_date = datetime.strptime(request.form['birthDate'], "%d/%m/%Y") db.session.commit() flash(u"enregistré!")""" return render_template('prof/profile.html', user=current_user.serialize(), prof=current_user.prof, subjects=subjects, educations=educations, experiences=experiences, latest_messages=latest_messages, placeholders=placeholders)
def index(): """Index of the client side""" latest_messages = current_user.contacts_latest_messages() return render_template('client/index.html', user=current_user.serialize(), latest_messages=latest_messages)
def picture_upload(): latest_messages = current_user.contacts_latest_messages() return render_template('client/picture_upload.html', user=current_user.serialize(), latest_messages=latest_messages)
def log(data): if 'room' not in data: print("logging requires a room") return room = data['room'] if isinstance(room, int) or isinstance(room, str): data['room'] = Room.from_id(room).serialize() elif not isinstance(room, Room): raise TypeError( f"Object of type `int`, `str` or `Room` expected, however type `{type(room)}` was passed" ) if room not in ROOMS: print("Could not log") return if 'user' not in data: data['user'] = current_user.serialize() else: user = data['user'] if isinstance(user, int) or not isinstance(user, str): data['user'] = User.from_id(user).serialize() if 'type' not in data: data['type'] = "custom" ROOMS[room]['log'].append(data)
def account(): """Return account information **Example request**: .. sourcecode:: http GET /auth/account HTTP/1.1 Host: do.cert.europa.eu Content-Type: application/json **Example success response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "api_key": "V3lKallXeGxlRUJqWlhKMExtVjFjbTl3WVM1bGRTSXNJa3hFUVZBVs", "email": "*****@*****.**", "name": "Big dummy" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string api_key: API key :>json string email: E-mail :>json string name: Full name :statuscode 200: :statuscode 401: Unauthorized """ return ApiResponse(current_user.serialize())
def search(): """Where a client looks for profs""" latest_messages = current_user.contacts_latest_messages() keywords = None subject = None _subject = request.args.get('subject') _keywords = request.args.get('keywords') if _subject: all_subjects = Subject.query.all() for s in all_subjects: if s.url_safe_name() == _subject: subject = s break elif _keywords: keywords = _keywords form_choices = { 'subjects': Subject.query.all(), 'levels': Level.query.all(), 'cities': City.query.all() } return render_template('client/search.html', user=current_user.serialize(), latest_messages=latest_messages, keywords=keywords, form_choices=form_choices, default_subject=subject, default_keywords=keywords)
def api_user(user_id): try: err = valid_user_api(user_id) if err: return err except Exception as err: return str(err), HTTPStatus.INTERNAL_SERVER_ERROR return current_user.serialize(), HTTPStatus.OK
def index_all(path): params = {} if current_user.is_authenticated: params['user'] = current_user.serialize() params['authenticated'] = True else: params['authenticated'] = False return render_template('index.html', params=json.dumps(params))
def rem_connection(follow_id): """Remove user connection for a user""" followed_user = User.query.get_or_404(follow_id) current_user.following.remove(followed_user) sess.commit() user = current_user.serialize() return jsonify(user=user)
def add_connection(follow_id): """Add user connection for a user""" followed_user = User.query.get_or_404(follow_id) current_user.following.append(followed_user) sess.commit() user = current_user.serialize() return jsonify(user=user)
def is_authenticated() -> FLASK_RESPONSE_TYPE: if current_user.is_authenticated(session): return ( current_user.serialize( skip_list=['password'], serialize_method=json.dumps, ), HTTP_STATUS_CODE.HTTP_200_OK.value, ) return '', HTTP_STATUS_CODE.HTTP_401_UNAUTHORIZED.value
def picture_upload(): #from flask import session #session.pop('_flashes', None) latest_messages = current_user.contacts_latest_messages() return render_template('prof/picture_upload.html', user=current_user.serialize(), prof=current_user.prof, latest_messages=latest_messages)
def interested_in_item(post_id): post = Post.query.filter_by(id=post_id).first() if post is None: return failure_response('Item not found') if post.active != None and post.active != True: return failure_response('Item inactive') if not logged_in(current_user): return failure_response('User not logged in') post.interested.append(current_user) db.session.commit() return success_response(current_user.serialize())
def update_me_photo(): if 'photo' not in request.files: raise BadRequest(message="Missing parameter", field='photo') try: photo = m.Photo.upload(file=request.files['photo']) except InvalidImage: raise BadRequest(message="Invalid image", field='photo') current_user.photo = photo db.session.add(current_user) db.session.commit() return render_json(current_user.serialize())
def profile_overview(): latest_messages = current_user.contacts_latest_messages() prof_obj = current_user.prof safe_name = current_user.safe_name return render_template('prof/aprof.html', user=current_user.serialize(), prof=prof_obj.serialize(), latest_messages=latest_messages, safe_name=safe_name)
def search_o(): """Where a client looks for profs""" latest_messages = current_user.contacts_latest_messages() keywords = request.args.get('keywords') prof_list = Prof.query.all() return render_template('client/search.html', user=current_user.serialize(), latest_messages=latest_messages, keywords=keywords, prof_list=prof_list)
def mouse_position(data): """ Emit an event 'mouse_position' to pass the coordinates of user clicks or mouse movement (specified via 'type') within an HTML element (specified via 'element'). """ emit('mouse_position', { 'type': data.get('type'), 'coordinates': data.get('coordinates'), 'element': data.get('element'), 'user': current_user.serialize(), 'timestamp': timegm(datetime.now().utctimetuple()), }, room=Room.from_id(data['room']).name())
def aprof(safe_name): """How a client views a prof""" latest_messages = current_user.contacts_latest_messages() prof_obj = Prof.query.filter(Prof.user == User.query.filter_by( safe_name=safe_name).first()).first() if not prof_obj: abort(404) return render_template('client/aprof.html', user=current_user.serialize(), prof=prof_obj.serialize(), latest_messages=latest_messages, safe_name=safe_name)
def get_me(): """Get my profile **Example JSON response**: .. sourcecode:: json { "username": "******", "photo": null, "created_at": "2017-02-21T16:59:35+0000", "id": 1 } :statuscode 401: Not authorized """ return render_json(current_user.serialize())
def chat(safe_name): """a chat view""" latest_messages = current_user.contacts_latest_messages() client_obj = Client.query.filter(Client.user == User.query.filter_by( safe_name=safe_name).first()).first() if not client_obj: abort(404) r = room_name(current_user.id, client_obj.user.id) return render_template('prof/chat.html', user=current_user.serialize(), client=client_obj.serialize(), latest_messages=latest_messages, safe_name=safe_name, room_name=r)
def create_user(): user_name = request.form.get('username') name_first = request.form.get('firstname') name_last = request.form.get('lastname') email = request.form.get('email') password = request.form.get('password') newUser = User() newUser.user_name = user_name newUser.name_first = name_first newUser.name_last = name_last newUser.email = email newUser.password = password db.session.add(newUser) db.session.commit() LoginFacilitator().log_user_in(newUser) return jsonify(current_user.serialize())
def profile(): latest_messages = current_user.contacts_latest_messages() u = current_user placeholders = { 'about_me': u.client.about_me, 'birth_date': u.birth_date.strftime("%d/%m/%Y"), } """if request.method == 'POST': u.client.about_me = request.form['aboutMe'] #print request.form['birth_date'] u.birth_date = datetime.strptime(request.form['birthDate'], "%d/%m/%Y") db.session.commit() flash(u"enregistré!")""" return render_template('client/profile.html', user=current_user.serialize(), latest_messages=latest_messages, placeholders=placeholders)
def accept_friend(friend_id): are_friends, is_pending_sent, is_pending_received = are_friends_or_pending( current_user.id, friend_id) if current_user.id == friend_id: return "You cannot add yourself as a friend." elif are_friends: return "You are already friends." elif is_pending_received: friend_request = Friends.query.filter_by( user_id_1=friend_id, user_id_2=current_user.id, status=FriendStatus.requested).first() friend_request.status = FriendStatus.accepted db.session.commit() return jsonify({ "status": "Request accepted.", "user": current_user.serialize() }) else: return "An error occured."
def unfriend(friend_id): are_friends, is_pending_sent, is_pending_received = are_friends_or_pending( current_user.id, friend_id) if are_friends: relationship = Friends.query.filter_by( user_id_1=current_user.id, user_id_2=friend_id, status=FriendStatus.accepted).first() if relationship is None: relationship = Friends.query.filter_by( user_id_1=friend_id, user_id_2=current_user.id, status=FriendStatus.accepted).first() db.session.delete(relationship) db.session.commit() return jsonify({ "status": "Sucessfully unfriended.", "user": current_user.serialize() }) else: return "You cannot unfriend this user."
def settings(): latest_messages = current_user.contacts_latest_messages() password_form = ChangePassword() wrong_password = False if password_form.validate_on_submit(): if current_user.verify_password(password_form.old_password.data): current_user.change_password(password_form.new_password.data) db.session.commit() flash(u"Nouveau mot de passe enregistré") return redirect(url_for('auth.logout')) else: wrong_password = True return render_template('prof/settings.html', user=current_user.serialize(), password_form=password_form, wrong_password=wrong_password, latest_messages=latest_messages)
def updatePassword(): user_json = json.loads(request.data).get("user") if not user_json: abort(ErrorCodes.BAD_REQUEST) username = user_json.get("username") if username != current_user.user_nicename: abort(ErrorCodes.UNAUTHORIZED) old_password = user_json.get("old_password") new_password = user_json.get("new_password") if not old_password or not new_password: abort(ErrorCodes.BAD_REQUEST) try: user_service.updatePassword(current_user.user_id, old_password, new_password) except InvalidPasswordException: abort(ErrorCodes.UNAUTHORIZED) return jsonify({'user': current_user.serialize()})
def get_account(): sub = None cards = {} invoices = [] if current_user.stripe_id: try: customer = stripe.Customer.retrieve(current_user.stripe_id) sub = ( customer.subscriptions.data[0] if customer.subscriptions.data else None ) invoices = stripe.Invoice.list(customer=customer, limit=12) cards = customer.sources.list(object="card").data for card in cards: if customer.default_source == card.id: card.default = True card.css_name = CARD_MAPPINGS[card.brand] except stripe.error.StripeError: return ( jsonify( { "ok": False, "error": "Failed to get your subscription details from Stripe.", } ), 503, ) pending_emails = [] verified_emails = [] for e in current_user.emails.order_by(Email.registered_on.desc()): if e.verified: verified_emails.append(e.address) else: pending_emails.append(e.address) return jsonify( { "ok": True, "user": current_user.serialize(), "emails": {"verified": verified_emails, "pending": pending_emails}, "cards": cards, "invoices": [ { "id": inv.id, "date": datetime.datetime.fromtimestamp(inv.date).strftime( "%A, %B %d, %Y" ), "attempted": inv.attempted, "total": inv.total, "paid": inv.paid, } for inv in invoices ], "sub": { "cancel_at_period_end": sub.cancel_at_period_end, "current_period_end": datetime.datetime.fromtimestamp( sub.current_period_end ).strftime("%A, %B %d, %Y"), } if sub else None, } )
def editor_all(path): return render_template('editor.html', params=json.dumps({'user': current_user.serialize()}))
def get_profile(): return jsonify(current_user.serialize())