def create_conversations(): user1 = User.objects(name="test").first() user2 = User.objects(name="test2").first() try: ChatCreation.create_new(members=[user1, user2]) conv1 = Chat.objects(members=[user1, user2]).first() Message(text="Testovací zpráva autora test", author=user1, chat=conv1).save() Message(text="Testovací zpráva autora test3", author=user2, chat=conv1).save() Message(text="1. Testovací zpráva autora test", author=user1, chat=conv1).save() m1 = Message(text="3. Testovací zpráva autora test", author=user1, chat=conv1).save() conv1.update(last_message_date=m1.date_created) except Exception as e: print(str(e))
def test_thing(self): User(name="test1", email="*****@*****.**", password=os.urandom(16)).save() user = User.objects().first() self.assertEqual(user.name, 'test1') user = User.objects(name="test1").get() self.assertEqual(user.name, 'test1')
def post_chats_add(): title = request.get_json()['title'] members = request.get_json()['members'] cur_user = User.objects(id=current_user["id"]).first() chat_members = [] for member in members: user = User.objects(name=member["label"], email=member["value"]).first() if cur_user.id == user.id: return jsonify({ "success": False, "message": "It is not allowed to chat with yourself".format(member) }), 400 if user is None: return jsonify({ "success": False, "message": "User not exists {}".format(member) }), 200 chat_members.append(user) chat_members.append(cur_user) try: new_chat = ChatCreation.create_new(title=title, members=chat_members).save() except: return jsonify({ "success": False, "message": "Chat with same users already exist" }), 400 return jsonify({ "success": True, "message": "New chat created, title: {}, members: {}".format( new_chat.title, new_chat.members), "chat": { "members": ",".join([m.name for m in chat_members]), "title": new_chat.title, "id": str(new_chat.id) } }), 200
def delete_user(username): """ Deletes a User. --- tags: - user summary: Deletes a User parameters: - id: username in: path description: The username of the user to be deleted. required: true schema: type: string responses: 200: description: User was successfully deleted. 400: description: Invalid username supplied. 404: description: User not found. """ user = User.objects(username=username).first() if not user: raise NotFound() user.delete() res = {"status": "success", "message": "user was deleted!"} return res, 200
def post(self): """ Handle post request, send email, save token to database :return: """ email = request.get_json()['email'] cur_user = User.objects(email=email).first() if not cur_user: return { "success": False, "message": "No user has this email: {}".format(email) } #PasswordReset_db(user=cur_user, token=token).save() token = s.dumps(email, salt='email-password-reset') msg = MailMessage('Confirm Email', sender='*****@*****.**', recipients=[email]) link = url_for('passwordreset', token=token, _external=True) link = "http://localhost:3000/reset/{}".format(token) msg.body = 'Your link is {}'.format(link) mail.send(msg) return { "success": True, "message": "Email was sent to: {}".format(email) }
def post_reset(): """ Handle post request, send email, save token to database :return: """ email = request.get_json()['email'] cur_user = User.objects(email=email).first() if not cur_user: return jsonify({ "success": False, "message": "No user has this email: {}".format(email) }), 200 token = s.dumps(email, salt='email-password-reset') msg = MailMessage('Confirm Email', sender=mail_settings["MAIL_USERNAME"], recipients=[email]) link = "https://pwachat2.herokuapp.com/?token={}".format(token) msg.body = 'Your link is {}'.format(link) mail.send(msg) return jsonify({ "success": True, "message": "Email was sent to: {}".format(email) }), 200
def post(self): user = User.objects(email=current_user["email"]).first() user.update(token="") logout_user() session.clear() return {"message": "User was logged out"}
def post(self): email = request.get_json()['email'] password = request.get_json()['password'] user = User.objects(email=email).first() expires = datetime.timedelta(days=1) if user: login_user(user) if check_password_hash(user.password, password): access_token = create_access_token(identity={ 'name': user.name, 'email': user.email }, expires_delta=expires) user.update(token=access_token) return { 'success': True, 'message': 'Logged in as {}'.format(user.name), 'access_token': access_token, 'user_name': user.name, } else: return {"success": False, 'message': 'Wrong credentials'} else: return {"success": False, "message": "Invalid user email"}
def post_registration(): email = request.get_json().get('email') name = request.get_json().get('name') password = request.get_json().get('password') print("requeat json ", request.get_json()) if password == "": return jsonify({"success": False, "message": 'Empty password'}) user = User.objects(email=email).first( ) # if this returns a user, then the email already exists in database user_name_exist = User.objects(name=name).first() print("user ", user) if user: # if a user is found, we want to redirect back to signup page so user can try again return jsonify({ "success": False, "message": 'User with this email address already exists', "email": email }) if user_name_exist: return jsonify({ "success": False, "message": 'User with this name already exists', "email": email }) try: # create new user with the form data. Hash the password so plaintext version isn't saved. user = User(email=email, name=name, password=generate_password_hash(password, method='sha256')).save() except ValidationError as err: return jsonify({"success": False, "message": err.message}) return jsonify({ "success": True, "message": 'email ' + user.email + ' successfully registered' })
def test_thing(self): User( name="FooBar1", email="*****@*****.**", password=os.urandom(16), ).save() current_user = User.objects().first() users = User.objects() con = Chat(members=users).save() Message(text="Message test text", author=current_user.id, conversation=con).save() message = Message.objects().first() self.assertEqual(message.author.id, current_user.id)
def load_user_from_request(request): token = request.headers.get('Authorization') if token: token = token.replace('Bearer ', '', 1) try: token = token except TypeError: pass user = User.objects(token=token).first() if user: return user # finally, method did not login the user return None
def get(self): """ Load chat addition form :return: """ all_users = User.objects(email__nin=[current_user["email"]]) users = [] for index, user in enumerate(all_users): if user.id == current_user["id"]: continue users.append({"label": user.name, "value": user.email}) return users
def load_messages(id): """ Get messages :param id: chat id :return: last 50 messages """ if current_user.is_authenticated: chat = Chat.objects(id=id).first() chat_members_ids = [member.id for member in chat.members] if current_user["id"] not in chat_members_ids: emit('all_messages', [False], room=id) else: messages = Message.objects(chat=id) messages = list(messages)[-50:] messages.sort(key=lambda x: x.id, reverse=False) all_messages = [] status = "" for message in messages: user = User.objects(name=current_user["name"]).first() # if message.author.id == user.id: # status = "sent" # else: # status = "replies" all_messages.append([ message.author.name, message.text, str(message.date_created), status ]) emit('all_messages', all_messages, room=id) # message_dict = {} # for message in messages: # user = User.objects(name=current_user["name"]).first() # if message.author.id == user.id: # status = "sent" # else: # status = "replies" # # message_dict[str(message.id)] = {"text": message.text, "status": status, # "author": message.author.name} # print("message ", message) else: #print("LOAD messages not authenticated") emit('all_messages', [False], room=id)
def post(self, id): author = request.get_json().get('author') text = request.get_json().get('text') chat = Chat_db.objects(id=id).first() user = User.objects(name=author).first() if user not in chat.members: return { "success": False, "message": "This user is not part of current chat" } message = Message(author=user, chat=chat, text=text).save() if message is not None: return {"success": True, "message": "Message was sent"}
def get(self, id): messages = Message.objects(chat=id) message_dict = {} for message in messages: user = User.objects(name=current_user["name"]).first() if message.author.id == user.id: status = "sent" else: status = "replies" message_dict[str(message.date_created)] = { "text": message.text, "status": status, "author": message.author.name } return message_dict
def load_users(): """ Load chat addition form :return: """ if current_user.is_authenticated: all_users = User.objects(email__nin=[current_user["email"]]) users = [] for user in all_users: if user.id == current_user["id"]: continue users.append([user.name, user.email]) emit('all_users', users) else: emit('all_users', False)
def handle_message(msg, room): user = User.objects(name=msg['author']).first() chat = Chat.objects(id=room).first() Message(author=user, chat=chat, text=msg['text']).save() status = "" if current_user.is_authenticated: # if msg["author"] == current_user["name"]: # status = "sent" # else: # status = "replies" message = [msg["author"], msg["text"], str(1), status] send(message, room=room) else: send(False, room=room)
def _get_all_chats(current_user): user = User.objects(name=current_user["name"]).first() chats = Chat_db.objects( members__contains=user).order_by('last_message_date') response = [] for chat in chats: chat.members.remove(user) chat_members = "" for member in chat.members: chat_members += member.name chat_members + " " response.append({ "members": chat_members, "title": chat.title, "id": str(chat.id) }) return response
def post_reset_token(token): """ Render form :return: """ email = request.get_json().get('email') password = request.get_json().get('password') try: token_email = s.loads(token, salt='email-password-reset', max_age=3600) except SignatureExpired: return jsonify({"success": False, "message": "The token is expired!"}) if email != token_email: return jsonify({"success": False, "message": "Bad email"}), 200 user = User.objects(email=email).first() user.update(password=generate_password_hash(password, method='sha256')) return jsonify({"success": True, "message": "Password was changed"}), 200
def test_thing(self): users = [] users.append( User(name="test1", email="*****@*****.**", password=os.urandom(16)).save()) users.append( User(name="test2", email="*****@*****.**", password=os.urandom(16)).save()) saved_users = User.objects() self.assertEqual(len(saved_users), len(users)) Chat(members=users).save() conversation = Chat.objects().first() self.assertEqual(len(conversation.members), len(users)) for con_user, user in zip(conversation.members, users): self.assertEqual(con_user.name, user.name) self.assertEqual(con_user.email, user.email)
def login_user(): """ Logs in User --- tags: - auth summary: Logs in User responses: 200: description: User was logged in successfully. headers: X-Expires-After: description: Date in UTC when token expires. schema: type: string format: date-time content: application/json: schema: type: object properties: auth_token: type: string example: abcde123456 message: type: string example: User was logged in! status: type: string example: success 400: description: User login failed. requestBody: content: application/json: schema: type: object properties: username: type: string example: foobar password: type: string format: password """ data = request.get_json() if not data: raise BadPayload() if not data.get("password"): raise BadPayload() user = User.objects(username=data["username"]).exclude("id").first() if not user: raise NotFound() if not bcrypt.check_password_hash(user.password, data["password"]): raise Forbidden() auth_token, expire_date = user.encode_auth_token() res = { "status": "success", "message": "user was logged in!", "auth_token": auth_token.decode() } return res, 200, [("X-Expires-After", expire_date)]
def load_user(user_id): user = User.objects(id=user_id).first() return user