Beispiel #1
0
    def post(self):
        """
        POST /authorities
        { 'name': 'Test Authority', 'shortname': 'test_authority' }
        :return:
        """

        if not self.request.body:
            self.userError("empty request")
            return

        try:
            data = escape.json_decode(self.request.body)
        except json.decoder.JSONDecodeError as e:
            self.userError("Malformed request", e)
            return
        except Exception as e:
            self.userError("Malformed request", e)
            return

        if data.get('authority', None) is None:
            data['authority'] = self.get_root_auth()
            if not data['authority']:
                self.userError("authority must be specified")
                return

        if data.get('name', None) is None:
            self.userError("Authority name must be specified")
            return

        if data.get('shortname', None) is None:
            self.userError("Authority shortname must be specified")
            return

        if not self.get_current_user() and 'users' not in data:
            self.userError("users of the new Authority must be specified")
            return

        # if new users are specified to be added to the authority
        if len(data.get('users', [])) > 0:
            for u in data['users']:
                if not isinstance(u, dict):
                    self.userError(
                        "New user properties under a new authority must be sent as dict"
                    )
                    return
                if u.get('first_name', None) is None:
                    self.userError("User first_name must be specified")
                    return
                if u.get('last_name', None) is None:
                    self.userError("User last_name must be specified")
                    return
                if u.get('password', None) is None:
                    self.userError("User password must be specified")
                    return
                if len(u['password']) < 8:
                    self.userError("Password must be at least 8 characters")
                    return
                # password must be encrypted before storing into DB
                u['password'] = crypt_password(u['password'])
                if u.get('email', None) is None:
                    self.userError("User email must be specified")
                    return
                if not self.isEmail(u['email']):
                    self.userError("Wrong Email address")
                    return
                if u.get('terms', False) is False:
                    self.userError("User must accept terms and conditions")
                    return

        # if pi_users are specified to manage the authority
        if len(data.get('pi_users', [])) > 0:
            for u in data['pi_users']:
                # if pi_user is a New User we need at least his/her email
                if isinstance(u, dict):
                    if u.get('email', None) is None:
                        self.userError(
                            "email of a new pi_user must be specified")
                        return
                    if not self.isEmail(u['email']):
                        self.userError("Wrong Email address")
                        return
                    if not any([
                            user['email'] == u['email']
                            for user in data['users']
                    ]):
                        self.userError(
                            "email %s of pi_user is not among new users" %
                            u['email'])
                        return

        if not self.get_current_user():
            # authority registration for new user
            current_user_id = None
        else:
            # admin create user directly
            current_user_id = self.get_current_user()['id']

        try:
            event = Event({
                'action': EventAction.CREATE,
                'user': current_user_id,
                'object': {
                    'type': ObjectType.AUTHORITY,
                    'id': None
                },
                'data': data
            })
        except Exception as e:
            self.userError("Can't create request", e.message)
            return
        else:
            result = yield dispatch(self.dbconnection, event)
            self.write(
                json.dumps(
                    {
                        "result": "success",
                        "events": result["generated_keys"],
                        "error": None,
                        "debug": None
                    },
                    cls=myJSONEncoder))
Beispiel #2
0
    def post(self, hashing=None):
        """
        POST /password[/<hashing>]
        :return:
        """
        if not self.request.body:
            self.userError("empty request")
            return

        try:
            data = escape.json_decode(self.request.body)
        except json.decoder.JSONDecodeError as e:
            self.userError("Malformed request", e)
            return
        except Exception as e:
            self.userError("Malformed request", e)
            return

        try:
            # NEW Event UPDATE PASSWORD
            if not hashing:
                if not 'email' in data:
                    self.userError("Email not specified")
                    return

                if not 'hashing' in data:
                    data['hashing'] = str(uuid.uuid4())

                user = None
                cursor = yield r.table('users').filter({
                    'email': data['email']
                }).run(self.dbconnection)
                while (yield cursor.fetch_next()):
                    user = yield cursor.next()
                if not user:
                    self.userError("no user found or permission denied")
                    return
                event = Event({
                    'action': EventAction.CREATE,
                    'user': None,
                    'object': {
                        'type': ObjectType.PASSWORD,
                        'id': user['id']
                    },
                    'data': data
                })

            # APPROVE Event UPDATE PASSWORD
            else:
                if not 'password' in data:
                    self.userError("Password not specified")
                    return

                # Find the Event based on the hashing
                cursor = yield r.table('activity').filter(
                    lambda ev: ev["data"]["hashing"] == hashing).run(
                        self.application.dbconnection)
                while (yield cursor.fetch_next()):
                    ev = yield cursor.next()
                event = Event(ev)

                user = None
                cursor = yield r.table('users').filter({
                    'email':
                    event.data['email']
                }).run(self.dbconnection)
                while (yield cursor.fetch_next()):
                    user = yield cursor.next()
                if not user:
                    self.userError("user not found or permission denied")
                    return

                #user = User(user)
                # Crypt password
                new_password = crypt_password(data['password'])
                event.data['password'] = new_password
                event.setApproved()

        except Exception as e:
            self.userError("Can't create request", e)
            return
        else:
            result = yield dispatch(self.dbconnection, event)
            self.write(
                json.dumps({
                    "result": "success",
                    "error": None,
                    "debug": None
                },
                           cls=myJSONEncoder))
Beispiel #3
0
    def put(self):
        """
        PUT /password
        :return:
        """
        if not self.request.body:
            self.userError("empty request")
            return

        try:
            data = escape.json_decode(self.request.body)
        except json.decoder.JSONDecodeError as e:
            self.userError("Malformed request", e)
            return
        except Exception as e:
            self.userError("Malformed request", e)
            return

        if 'old_password' in data:
            p = bytes(data['old_password'], 'latin-1')

            if not check_password(data['old_password'], user['password']):
                self.userError("password does not match")
                return

        if not data['new_password']:
            self.userError("Malformed request")
            return

        user_id = self.get_current_user()['id']
        try:
            user = yield r.table('users').get(user_id).run(
                self.application.dbconnection)
        except Exception as e:
            self.userError("User does not exists")
            return

        # Directly modify the database, no need to go through Events
        user['password'] = crypt_password(data['new_password'])
        yield r.table('users').get(user_id).update(user).run(self.dbconnection)

        #event = Event({
        #    'action': EventAction.UPDATE,
        #    'user': user_id,
        #    'object': {
        #        'type': ObjectType.USER,
        #        'id': user_id
        #    },
        #    'data': {
        #        "password": crypt_password(data['new_password']),
        #        "generate_keys": False
        #    }
        #})
        #yield dispatch(self.dbconnection, event)

        self.write(
            json.dumps({
                "result": "success",
                "error": None,
                "debug": None
            },
                       cls=myJSONEncoder))
Beispiel #4
0
    def put(self, id=None, o=None):
        """
        PUT /users/<id>
        :return:
        """

        response = []
        current_user = self.get_current_user()

        if not current_user:
            self.userError('permission denied')
            return

        if not self.request.body:
            self.userError("empty request")
            return

        try:
            data = escape.json_decode(self.request.body)
        except json.decoder.JSONDecodeError as e:
            self.userError("malformed request", e.message)
            return

        # user id from DB
        user = None
        cursor = yield r.table('users') \
            .filter({'id': id}) \
            .run(self.dbconnection)
        while (yield cursor.fetch_next()):
            user = yield cursor.next()

        if not user:
            self.userError("this user %s does NOT exist" % id)
            return
        # If password changed, encrypt the new one
        if "password" in data and user["password"] != crypt_password(data["password"]):
            data["password"] = crypt_password(data["password"])

        # handle authority as dict
        if "authority" in data and type(data["authority"]) is dict:
            data["authority"] = data["authority"]["id"]

        # User's Slices are managed through the Projects Service
        # handle slices as dict
        if "slices" in data and type(data["slices"]) is dict:
            data["slices"] = data["slices"]["id"]

        # Update user's data
        try:
            event = Event({
                'action': EventAction.UPDATE,
                'user': current_user['id'],
                'object': {
                    'type': ObjectType.USER,
                    'id': id
                },
                'data': data
            })
        except Exception as e:
            self.userError("Can't create request", e.message)
            return
        else:
            result = yield dispatch(self.dbconnection, event)
            response = response + result["generated_keys"]

        # handle project as dict
        if all(isinstance(n, dict) for n in data['projects']):
            data['projects'] = [x['id'] for x in data['projects']]

        # Check the list of projects in data sent
        for p in data['projects']:
            # if the project is not in the list of the user's projects in the DB, user is a new pi
            if p not in user['projects']:
                # dispatch event add pi to project
                try:
                    event = Event({
                        'action': EventAction.ADD,
                        'user': current_user['id'],
                        'object': {
                            'type': ObjectType.PROJECT,
                            'id': p,
                        },
                        'data': {
                            'type' : DataType.PI,
                            'values' : [id]
                        }
                    })
                except AttributeError as e:
                    self.userError("Can't create request", e)
                    return
                except Exception as e:
                    self.userError("Can't create request", e)
                    return
                else:
                    result = yield dispatch(self.dbconnection, event)
                    response = response + result["generated_keys"]

        # Check user's projects in DB
        for p in user['projects']:
            # If the project is not in the data sent, remove the user from the project's pis
            if p not in data['projects']:
                # dispatch event add pi to project
                try:
                    event = Event({
                        'action': EventAction.REMOVE,
                        'user': current_user['id'],
                        'object': {
                            'type': ObjectType.PROJECT,
                            'id': p,
                        },
                        'data': {
                            'type' : DataType.PI,
                            'values' : [id]
                        }
                    })
                except AttributeError as e:
                    self.userError("Can't create request", e)
                    return
                except Exception as e:
                    self.userError("Can't create request", e)
                    return
                else:
                    result = yield dispatch(self.dbconnection, event)
                    response = response + result["generated_keys"]
        # handle authority as dict
        if all(isinstance(n, dict) for n in data['pi_authorities']):
            data['pi_authorities'] = [x['id'] for x in data['pi_authorities']]
        # Check the list of pi_authorities in data sent
        for a in data['pi_authorities']:
            # if the authority is not in the list of the user's pi_authorities in the DB, user is a new pi
            # XXX pi_authorities contains also projects, to be changed in myslicelib
            if a not in user['pi_authorities'] and len(a.split('+')[1].split(':'))<3:
                # dispatch event add pi to authority
                try:
                    event = Event({
                        'action': EventAction.ADD,
                        'user': current_user['id'],
                        'object': {
                            'type': ObjectType.AUTHORITY,
                            'id': a,
                        },
                        'data': {
                            'type' : DataType.PI,
                            'values' : [id]
                        }
                    })
                except AttributeError as e:
                    self.userError("Can't create request", e)
                    return
                except Exception as e:
                    self.userError("Can't create request", e)
                    return
                else:
                    result = yield dispatch(self.dbconnection, event)
                    response = response + result["generated_keys"]

        # Check user's pi_authorities in DB
        for a in user['pi_authorities']:
            # If the authority is not in the data sent, remove the user from the authority pis
            # XXX pi_authorities contains also projects, to be changed in myslicelib
            if a not in data['pi_authorities'] and len(a.split('+')[1].split(':'))<3:
                # dispatch event add pi to project
                try:
                    event = Event({
                        'action': EventAction.REMOVE,
                        'user': current_user['id'],
                        'object': {
                            'type': ObjectType.AUTHORITY,
                            'id': a,
                        },
                        'data': {
                            'type' : DataType.PI,
                            'values' : [id]
                        }
                    })
                except AttributeError as e:
                    self.userError("Can't create request", e)
                    return
                except Exception as e:
                    self.userError("Can't create request", e)
                    return
                else:
                    result = yield dispatch(self.dbconnection, event)
                    response = response + result["generated_keys"]

        self.write(json.dumps(
            {
                "result": "success",
                "events": response,
                "error": None,
                "debug": None
             }, cls=myJSONEncoder))
Beispiel #5
0
    def post(self):
        """
        POST /users
        :return:
        """

        if not self.request.body:
            self.userError("empty request")
            return

        try:
            data = escape.json_decode(self.request.body)
        except json.decoder.JSONDecodeError as e:
            self.userError("Malformed request", e)
            return
        except Exception as e:
            self.userError("Malformed request", e)
            return

        if data.get('authority', None) is None:
            self.userError("authority must be specified")
            return

        if data.get('first_name', None) is None:
            self.userError("first_name must be specified")
            return

        if data.get('last_name', None) is None:
            self.userError("last_name must be specified")
            return

        if data.get('email', None) is None:
            self.userError("email must be specified")
            return

        if not self.isEmail(data['email']):
            self.userError("Wrong Email address format")
            return

        user = None
        cursor = yield r.table('users') \
                .filter({'email':data['email']}) \
                .run(self.dbconnection)
        while (yield cursor.fetch_next()):
            user = yield cursor.next()
        if user:
            self.userError("This email is already registered")
            return

        if data.get('password', None) is None:
            self.userError("Password must be specified")
            return

        if len(data['password'])<8:
            self.userError("Password must be at least 8 characters")
            return

        # password must be encrypted before storing into DB
        data['password'] = crypt_password(data['password'])

        if data.get('terms', False) is False:
            self.userError("Please read and accept the terms and conditions.")
            return

        if not self.get_current_user():
            # usr registration
            current_user_id = None
        else:
            # admin create user directly
            current_user_id = self.get_current_user()['id']

        try:
            event = Event({
                'action': EventAction.CREATE,
                'user': current_user_id,
                'object': {
                    'type': ObjectType.USER,
                    'id': None
                },
                'data': data,
                'notify': True,
            })
        except Exception as e:
            self.userError("Can't create request", e.message)
            return
        else:
            result = yield dispatch(self.dbconnection, event)
            self.write(json.dumps(
                {
                    "result": "success",
                    "events": result["generated_keys"],
                    "error": None,
                    "debug": None
                 }, cls=myJSONEncoder))
Beispiel #6
0
def main(argv):
    try:
        opts, args = getopt.getopt(
            argv, "he:P:k:p:s",
            ["email=", "password="******"private_key=", "public_key=", "sync="])
    except getopt.GetoptError:
        print(
            'init_user.py -e <email> -P <password> -k <private_key path> -p <public_key path> -s <synchronize with Registry>'
        )
        sys.exit(2)
    if (len(opts) < 4):
        print('Missing parameters:')
        print(
            'init_user.py -e <email> -P <password> -k <private_key path> -p <public_key path> -s <synchronize with Registry>'
        )
        sys.exit(2)

    sync = False

    for opt, arg in opts:
        if opt == '-h':
            print(
                'init_user.py -e <email> -P <password> -k <private_key path> -p <public_key path> -s <synchronize with Registry>'
            )
            sys.exit()
        elif opt in ("-e", "--email"):
            email = arg
        elif opt in ("-P", "--password"):
            password = crypt_password(arg)
        elif opt in ("-k", "--private_key"):
            f = open(arg, 'r')
            private_key = f.read()
        elif opt in ("-p", "--public_key"):
            f = open(arg, 'r')
            public_key = f.read()
        elif opt in ("-s", "--sync"):
            if arg.lower() in ["true", "yes", "y"]:
                sync = True

    dbconnection = db.connect()

    lock = threading.Lock()
    # Synchronize the users from SFA Registry into the DB
    if sync:
        print("sync user %s" % email)
        syncUsers(lock, email=email, job=False)
    else:
        try:
            # Get the user from SFA Registry
            print("get user %s from SFA Reg" % email)
            remote_user = q(User).filter('email', email).get().first()
            pprint(remote_user)
            # merge fields from script with remote_user
            remote_user.setAttribute('password', password)
            remote_user.setAttribute('private_key', private_key)
            remote_user.setAttribute('generate_keys', False)
            remote_user.setAttribute('public_key', public_key)
            remote_user.setAttribute('keys', [public_key])
            r.db('myslice').table('users').insert(
                remote_user.dict()).run(dbconnection)
            result = r.db('myslice').table('users').get(
                remote_user.id).run(dbconnection)
            #result = remote_user.save(dbconnection)
            if result:
                print("User saved")
            else:
                print("Error during save")
                pprint(result)
            # if user has private key
            # update its Credentials
            #if 'private_key' in updated_user:
            #    updated_user = update_credentials(updated_user)
        except Exception as e:
            import traceback
            traceback.print_exc()