Ejemplo n.º 1
0
 def send_message(self, request):
     """
     Create a message and then wire relationships as following
     Session to message for Logging
     Sender to message for Activity of user
     Message to Receiver for Alerting
     :param request:
     :return:
     """
     if str(type(request)) == "<class 'werkzeug.local.LocalProxy'>":
         form = request.form.to_dict()
         sessionId = request.headers['SESSIONID']
     # For internal requests not coming from HTTP
     else:
         form = request
         sessionId = request['sessionId']
     # Create the Message Node
     msg = self.create_node(class_name="Message",
                            text=form['text'],
                            title=form['title'],
                            sender=form['sender'],
                            receiver=form['receiver'],
                            createDate=get_datetime(),
                            icon=self.ICON_POST)
     # Create relations from sender to post and post to receiver.
     try:
         senderKey = self.get_user(
             userName=form['sender'])[0].oRecordData['key']
     except:
         msg['message'] = "No sender identified with key %s" % form['sender']
         return msg
     try:
         receiverKey = self.get_user(
             userName=form['receiver'])[0].oRecordData['key']
     except:
         msg['message'] = "No receiver identified with key %s" % form[
             'receiver']
         return msg
     msgKey = msg['data']['key']
     msg['message'] = "Message sent from %s with subject %s to %s on %s" % (
         form['sender'], form['title'], form['receiver'], get_datetime())
     self.create_edge(fromNode=sessionId,
                      fromClass="Session",
                      toNode=msgKey,
                      toClass="Message",
                      edgeType="Logged")
     self.create_edge(fromNode=senderKey,
                      fromClass="User",
                      toNode=msgKey,
                      toClass="Message",
                      edgeType="Sent")
     self.create_edge(fromNode=msgKey,
                      fromClass="Message",
                      toNode=receiverKey,
                      toClass="User",
                      edgeType="SentTo")
     # for tag in tags create a new node and relate it TODO
     return msg
Ejemplo n.º 2
0
 def check_standard_users(self):
     """
     Sets up the initial users as channels to fill Application dependent lists. Users serve standard functions
     that can be used in various automated situations
     TODO only the first user's password works
     :return:
     """
     users = []
     for r in self.client.command('''
     select userName from User 
     '''):
         users.append(r.oRecordData['userName'])
     message = "created with auto users and passwords: "
     i = 1
     for au in self.auto_users:
         if au not in users:
             click.echo('[%s_UserServer_init] Creating auto user %s' %
                        (get_datetime(), au))
             password = randomString(16)
             r = self.create_user({
                 "userName": au,
                 "email": "*****@*****.**",
                 "passWord": password,
                 "confirmed": "true",
                 "icon": self.auto_users[au]
             })
             if i == len(self.auto_users):
                 message += "and USER %d: %s PSWD: %s " % (i, au, password)
             else:
                 message += "USER %d: %s PSWD: %s, " % (i, au, password)
         try:
             # Test logging in with the user and password
             sql = '''select passWord from %s''' % r['data']['key']
             password_hash = self.client.command(
                 sql)[0].oRecordData['passWord']
             r = check_password_hash(password_hash, password)
             if not r:
                 click.echo(
                     '[%s_UserServer_init] ERROR with user creation %s' %
                     (get_datetime(), str(e)))
         except Exception as e:
             click.echo('[%s_UserServer_init] ERROR with user creation %s' %
                        (get_datetime(), str(e)))
         i += 1
     # Auto confirm the users
     self.client.command('''update User set confirmed = true''')
     message += "Save the passwords for future reference."
     return message
Ejemplo n.º 3
0
    def logout(self, request):
        """
        Look up a session and update the endDate with getTime
        Blacklist the token by creating a blacklist object with the token data
        :param request:
        :return:
        """
        # Look up the session and update the endDate with new getTime
        # Blacklist the token and associate with the Session

        r = request.form.to_dict(flat=True)
        dLOGOUT = get_datetime()
        self.update(class_name="Session",
                    var="endDate",
                    val=dLOGOUT,
                    key=int(request.headers['SESSIONID']))
        blackListNode = self.create_node(
            class_name="Blacklist",
            createtDate=dLOGOUT,
            token=request.headers['AUTHORIZATION'],
            user=r['userName'],
            session=request.headers['SESSIONID'],
            icon=self.ICON_BLACKLIST)

        self.create_edge(edgeType="ClosedSession",
                         fromNode=blackListNode['data']['key'],
                         toNode=request.headers['SESSIONID'])

        return "User {userName} logged out from session {session} at {date}".format(
            userName=r['userName'],
            session=request.headers['SESSIONID'],
            date=dLOGOUT)
Ejemplo n.º 4
0
    def create_user(self, form):
        """
        If a user does not exist, encrypt the password for storage and create the user
        Send an email to the user email provided for confirmation process

        :param form:
        :return:
        """
        if not self.get_user(userName=form['userName'], email=form['email']):
            passWord = self.encrypt_password(form['passWord'])
            if "icon" in form.keys():
                icon = form['icon']
            else:
                icon = self.ICON_USER

            userNode = self.create_node(class_name="User",
                                        passWord=passWord,
                                        userName=form['userName'],
                                        email=form['email'],
                                        createDate=get_datetime(),
                                        icon=icon,
                                        confirmed="False")
            if userNode and form['userName'] not in self.auto_users.keys():
                self.confirm_user_email(userName=form['userName'],
                                        email=form['email'])
                return {
                    "message":
                    "%s, confirm the registration process by using the link sent to %s"
                    % (form['userName'], form['email']),
                    "data":
                    userNode
                }
            elif form['userName'] in self.auto_users.keys():
                return userNode
Ejemplo n.º 5
0
    def read_message(self, **kwargs):
        """
        Update a message as read by the receiver with a new edge from the UserKey to the MessageKey
        Return an updated list of messages to refresh the inbox
        :param kwargs:
        :return:
        """
        data = {"data": []}
        sql = '''
        create edge {edgeType} from 
        (select from {fromClass} where key = {fromNode}) to 
        (select from {toClass} where key = {toNode}) set DTG = '{DTG}'
        '''.format(edgeType="Read",
                   fromNode=kwargs['userKey'],
                   toNode=kwargs['msgKey'],
                   fromClass="User",
                   toClass="Message",
                   DTG=get_datetime())
        try:
            self.client.command(sql)
        except Exception as e:
            click.echo("Error reading message %s" % str(e))

        data['message'] = "Message %s read" % (kwargs['msgKey'])
        return data
Ejemplo n.º 6
0
    def create_session(self, form, ip_address, token):
        """
        Create an object to track the activities of a user
        :param form:
        :param ip_address:
        :param token:
        :return:
        """
        session = self.create_node(class_name="Session",
                                   startDate=get_datetime(),
                                   ipAddress=ip_address,
                                   token=token,
                                   createDate=get_datetime(),
                                   user=form['userName'],
                                   icon=self.ICON_SESSION)

        return session
Ejemplo n.º 7
0
    def create_user(self, form):
        """
        If a user does not exist, encrypt the password for storage and create the user

        :param form:
        :return:
        """
        if not self.get_user(userName=form['userName'], email=form['email']):
            passWord = self.encrypt_password(form['passWord'])
            return self.create_node(class_name="User",
                                    passWord=passWord,
                                    userName=form['userName'],
                                    email=form['email'],
                                    createDate=get_datetime(),
                                    icon=self.ICON_USER)
Ejemplo n.º 8
0
    def send_message(self, request):
        """
        Create a message and then wire relationships as following
        Session to message for Logging
        Sender to message for Activity of user
        Message to Receiver for Alerting
        :param request:
        :return:
        """
        if str(type(request)) == "<class 'werkzeug.local.LocalProxy'>":
            form = request.form.to_dict()
            sessionId = request.headers['SESSIONID']
        else:  # For internal requests not coming from HTTP
            form = request
            sessionId = request['sessionId']

        msg = self.create_node(class_name="Message",
                               text=form['text'],
                               title=form['title'],
                               sender=form['sender'],
                               receiver=form['receiver'],
                               createDate=get_datetime(),
                               icon=self.ICON_POST)

        # create relations from sender to post and post to receiver
        senderKey = self.get_user(
            userName=form['sender'])[0].oRecordData['key']
        receiverKey = self.get_user(
            userName=form['receiver'])[0].oRecordData['key']
        msgKey = msg['data']['key']
        self.create_edge(fromNode=sessionId, toNode=msgKey, edgeType="Logged")
        self.create_edge(fromNode=senderKey, toNode=msgKey, edgeType="Sent")
        self.create_edge(fromNode=msgKey,
                         toNode=receiverKey,
                         edgeType="SentTo")
        # for tag in tags create a new node and relate it
        return msg
Ejemplo n.º 9
0
from flask import jsonify, Blueprint, request
from apiserver.blueprints.users.models import userDB
from apiserver.blueprints.home.models import get_datetime
from apiserver.utils import get_request_payload
from flask_cors import CORS
import click

# Application Route specific object instantiation
users = Blueprint('users', __name__)
CORS(users)
# Case where no DB has been established from which the message returned should let the user know to run the setup API

odbserver = userDB()
init_required = odbserver.open_db()
if init_required:
    click.echo("[%s_User_init] %s" % (get_datetime(), init_required))
else:
    odbserver.open_db()
    click.echo('[%s_UserServer_init] Complete' % (get_datetime()))


@users.route('/users/db_init', methods=['GET'])
def db_init():
    """
    API endpoint used when the DB has not been created
    :return:
    """
    result = odbserver.create_db()
    if not result:
        return jsonify({
            "status": 200,
Ejemplo n.º 10
0
    def confirm(self, **kwargs):
        """
        Use the token sent from the confirm_user_email process to confirm the user
        If the user name is confirmed,
        1) Blacklist the token
        2) Update the user's confirmed statys
        3) Sign the user in through the email link with a new token

        :param kwargs:
        :return:
        """

        userName = self.deserialize_token(token=kwargs['token'])
        if userName not in [DB_ERROR, BLACK_LISTED, None, SIGNATURE_EXPIRED]:
            # Blacklist the token
            blackListNode = self.create_node(
                class_name="Blacklist",
                createtDate=get_datetime(),
                token=kwargs['token'],
                user=userName[0].oRecordData['userName'],
                session='Email confirmation',
                icon=self.ICON_BLACKLIST)
            self.create_edge_new(
                edgeType="ConfirmedEmail",
                fromNode=blackListNode['data']['key'],
                toNode=userName[0].oRecordData['rid'].get_hash())

            # Update user data with confirmed
            self.update(var="confirmed",
                        val=True,
                        key=userName[0].oRecordData['rid'].get_hash())

            # Log user in with a new token
            token = self.serialize_token(userName[0].oRecordData['userName'])
            session = self.create_session(
                {"userName": userName[0].oRecordData['userName']}, 'Email',
                token)
            self.create_edge_new(
                fromNode=userName[0].oRecordData['rid'].get_hash(),
                toNode=session['data']['key'],
                edgeType="UserSession")

            return {
                "status":
                200,
                "token":
                token,
                "session":
                session,
                "activityGraph":
                self.get_activity(
                    userName=userName[0].oRecordData['userName']),
                "message":
                "User %s confirmed email %s and logged in" %
                (userName[0].oRecordData['userName'],
                 userName[0].oRecordData['email'])
            }

        elif not userName:
            return {"status": 204, "token": None, "message": "User not found"}
        else:
            return {"status": 204, "token": None, "message": userName}