Пример #1
0
def setUp():
    cleanUp()

    user_admin = dict(**USER_BASE, email='*****@*****.**')
    user_admin_info = UsersBusiness.create(user_admin, admin=True)
    user = dict(**USER_BASE, email='*****@*****.**')
    user_info = UsersBusiness.create(user, admin=False)
    return user_admin_info, user_info
Пример #2
0
    def post(self):
        """
        create new user
        """
        data, status = validate(request.json,
                                'user_create',
                                validate_password=True)
        if status is False:
            raise BadRequest(json.dumps(data))

        admin = data.get('admin', False)

        # Only admin users can create.
        if admin:
            user_id, grants, _ = get_userinfo_by_token()

            if 'admin' not in grants:
                raise Forbidden('You need to be an administrator!')

        user = UsersBusiness.create(data, admin=admin)

        if not user:
            raise InternalServerError('Error creating user!')

        return marshal(user, get_user_serializer()), 200
Пример #3
0
    def authorize_revoke_client(cls, action, user_id, client_id, scope=[]):
        model = UsersBusiness.init_infos()['model']

        user = UsersBusiness.get_by_id(user_id)
        if not user:
            raise NotFound('User not Found!')

        new_list = []
        if action == 'authorize':
            ''' Authorize client '''
            has_client = False
            for client in user['clients_authorized']:
                if str(client['id']) == str(client_id):
                    client['scope'] = client['scope'] + scope
                    has_client = True
                    break

            if not has_client:
                user['clients_authorized'].append({
                    "id": ObjectId(client_id),
                    "scope": scope
                })
            new_list = user['clients_authorized']

        else:
            ''' Revoke client '''
            for client in user['clients_authorized']:
                if str(client['id']) == client_id:
                    new_list.append({
                        'id':
                        client['id'],
                        'scope': [
                            item for item in client['scope']
                            if item not in scope
                        ]
                    })
                else:
                    new_list.append(client)

        try:
            model.update_one({"_id": ObjectId(user_id)},
                             {"$set": {
                                 "clients_authorized": list(new_list)
                             }})
            return True
        except Exception:
            return False
Пример #4
0
    def get(self, id):
        """
        list all authorized clients of a specific user
        """
        clients = UsersBusiness.list_clients_authorized(id)
        clients = clients[0]['clients'] if len(clients) else []

        return marshal({"clients": clients}, get_clients_serializer())
Пример #5
0
    def delete(self, id):
        """
        apply soft_delete in user (disable)
        """
        status = UsersBusiness.delete(id)
        if not status:
            NotFound("User not Found!")

        return {"message": "Deleted user!"}
Пример #6
0
    def get(self, id):
        """
        user informations by id
        """
        user = UsersBusiness.get_by_id(id)
        if not user:
            raise NotFound("User not Found!")

        return marshal(user, get_user_serializer())
Пример #7
0
    def token(cls, user_id, service, scope=''):
        client_infos = ClientsBusiness.get_by_name(service)
        if not client_infos:
            raise Forbidden('Client not found!')
        user = UsersBusiness.get_by_id(user_id)

        client = list(
            filter(lambda c: c['id'] == client_infos['_id'], user['clients_authorized']))
        if len(client) <= 0:
            raise Forbidden('Not authorized!')

        authorized = False if scope else True
        typ = ''
        name = ''
        actions = []

        ''' filter and valid scope '''
        if scope:
            params = scope.lower().split(':')
            if len(params) != 3:
                raise BadRequest('Invalid scope!')

            typ = params[0]
            name = params[1]
            actions = params[2].split(',')

            for user_scope in client[0]['scope']:
                if not user_scope:
                    raise Forbidden('Not authorized!')
                typ_scope, name_scope, actions_scope = user_scope.lower().split(':')

                if typ_scope == typ:
                    if name_scope == name or name_scope == '*':
                        has_actions = True
                        for action in actions:
                            if action not in actions_scope.split(',') and '*' not in actions_scope:
                                has_actions = False
                        if has_actions:
                            authorized = True
                            break
            if not authorized:
                raise Forbidden('Not authorized!')

        ''' generate client token '''
        token_client = cls.encode_client_token(
            service, typ, name, actions, user, client_infos)

        expired_date = time.mktime(time.localtime(
            int(time.time()) + int(Config.EXPIRES_IN_CLIENT)))
        return {
            "user_id": user_id,
            "callback": client_infos['redirect_uri'],
            "token": token_client.decode('utf8'),
            "access_token": token_client.decode('utf8'),
            "expired_date": time.strftime("%Y-%m-%d %H:%M:%S",
                                          time.localtime(expired_date))
        }
Пример #8
0
    def put(self, id):
        """
        update a user's information
        """
        data, status = validate(request.json, 'user_update')
        if status is False:
            raise BadRequest(json.dumps(data))

        user = UsersBusiness.update(id, data)
        if not user:
            raise InternalServerError('Error updating user!')

        return {"message": "User updated!"}
Пример #9
0
    def token(cls, user_id, service, scope=''):
        client_infos = ClientsBusiness.get_by_name(service)
        user = UsersBusiness.get_by_id(user_id)

        client = list(
            filter(lambda c: c['id'] == client_infos['_id'],
                   user['clients_authorized']))
        if len(client) <= 0:
            raise Forbidden('Not authorized!')

        authorized = False if scope else True
        typ = ''
        name = ''
        actions = []
        ''' filter and valid scope '''
        if scope:
            params = scope.split(':')
            if len(params) != 3:
                return BadRequest('Invalid scope!')

            typ = params[0]
            name = params[1]
            actions = params[2].split(',')

            for user_scope in client[0]['scope']:
                if not user_scope:
                    raise Forbidden('Not authorized!')
                typ_scope, name_scope, actions_scope = user_scope.split(':')

                if typ_scope == typ:
                    if name_scope == name or name_scope == '*':
                        has_actions = True
                        for action in actions:
                            if action not in actions_scope.split(
                                    ',') and '*' not in actions_scope:
                                has_actions = False
                        if has_actions:
                            authorized = True
                            break
            if not authorized:
                raise Forbidden('Not authorized!')
        ''' generate client token '''
        token_client = cls.encode_client_token(service, typ, name, actions,
                                               user, client_infos)

        return {
            "user_id": user_id,
            "callback": client_infos['redirect_uri'],
            "token": token_client.decode('utf8'),
            "access_token": token_client.decode('utf8')
        }
Пример #10
0
def setUp():
    cleanUp()

    user_admin = dict(
        **USER_BASE,
        email='*****@*****.**'
    )
    user_admin_info = UsersBusiness.create(user_admin, admin=True)
    user = dict(
        **USER_BASE,
        email='*****@*****.**'
    )
    user_info = UsersBusiness.create(user, admin=False)

    app_1_info = dict(
        client_name='test',
        client_uri='http://localhost:8080/test',
        redirect_uri='http://localhost:8080/test/test',
        type_secret='string',
        client_secret='abc',
        user_id=[user_admin_info['_id']],
        created_at=datetime.now(),
        expired_at=None,
        _id=ObjectId('5e59557579da4ec3ff04a682')
    )
    app_2_info = dict(
        client_name='registry',
        client_uri='http://localhost:8080/registry',
        redirect_uri='http://localhost:8080/registry/test',
        type_secret='file',
        client_secret='/data/home/key',
        user_id=[user_info['_id']],
        created_at=datetime.now(),
        expired_at=None,
        _id=ObjectId('5e59557579da4ec3ff04a683')
    )
    mongo.db.clients.insert_many([app_1_info, app_2_info])
    return user_admin_info, user_info
Пример #11
0
    def put(self):
        """
        change user password by secret token
        """
        data, status = validate(request.json,
                                'user_reset_password',
                                validate_password=True)
        if status is False:
            raise BadRequest(json.dumps(data))

        status = UsersBusiness.reset_password(data['password'], data['token'])
        if not status:
            raise InternalServerError('Error updating user password!')

        return {"message": "Password updated!"}
Пример #12
0
    def post(self):
        """
        send email to enable function to change user password
        """
        data, status = validate(request.json, 'user_send_password')
        if status is False:
            raise BadRequest(json.dumps(data))

        user = UsersBusiness.send_token_password(**data)
        if not user:
            raise InternalServerError('Error in send email!')

        return {
            "email": user['email'],
            "message": "We send a link to your email!"
        }
Пример #13
0
    def put(self, id):
        """
        change user password
        """
        data, status = validate(request.json,
                                'user_change_password',
                                validate_password=True)
        if status is False:
            raise BadRequest(json.dumps(data))

        user = UsersBusiness.change_password(id, data['old_password'],
                                             data['password'])
        if not user:
            raise InternalServerError('Error updating user password!')

        return {"message": "Password updated!"}
Пример #14
0
    def login(cls, username, password):
        model = UsersBusiness.init_infos()['model']

        user = model.find_one({
            "credential.username": username,
            "deleted_at": None
        })
        if not user:
            raise NotFound('User not found!')

        if check_password_hash(user['credential']['password'],
                               password) is False:
            raise BadRequest('Incorrect password!')

        user_id = str(user['_id'])
        token = cls.encode_auth_token(user_id, user['credential']['grants'],
                                      'user')
        result = {
            "user_id": user_id,
            "access_token": token.decode('utf8').replace("'", '"')
        }
        return result
Пример #15
0
def get_userinfo_by_token(client_id=False):
    try:
        bearer, authorization = request.headers['Authorization'].split()
        if 'bearer' not in bearer.lower():
            raise Forbidden('Invalid token!')
    except Exception:
        raise Forbidden('Token is required!')

    if authorization:
        result, status = AuthBusiness.decode_auth_token(authorization)
        if status:
            user = UsersBusiness.get_by_id(result["id"])
            if user:
                if client_id:
                    client = ClientsBusiness.get_by_id(client_id)
                    if not client:
                        raise NotFound('Client not Found!')
                    return str(user['_id']), user['credential']['grants'], client
                return str(user['_id']), user['credential']['grants'], False

            raise NotFound('User not found')
        raise Unauthorized(str(result))
    raise Forbidden('Token is required!')
Пример #16
0
    def create(cls, user_id, client_infos):
        model = cls.init_infos()['model']

        user = UsersBusiness.get_by_id(user_id)
        if not user:
            raise NotFound('User not Found!')
        """
        check if client name is already registered
        """
        client = model.find_one({
            "client_name":
            client_infos['client_name'],
            "$or": [{
                "expired_at": {
                    "$gt": datetime.now()
                }
            }, {
                "expired_at": None
            }]
        })
        if client:
            raise Conflict('A client with this name already exists')
        """
        create client credentials
        """
        client_infos['user_id'] = user['_id']
        client_infos['created_at'] = datetime.now()
        client_infos['expired_at'] = client_infos.get('expired_at', None)
        """
        save in mongodb
        """
        try:
            model.insert_one(client_infos)
            return client_infos

        except Exception:
            return False
Пример #17
0
    def login(cls, username, password):
        model = UsersBusiness.init_infos()['model']

        user = model.find_one(
            {"credential.username": username, "deleted_at": None})
        if not user:
            raise NotFound('User not found!')

        if check_password_hash(user['credential']['password'], password) is False:
            raise BadRequest('Incorrect password!')

        user_id = str(user['_id'])
        token = cls.encode_auth_token(
            user_id, user['credential']['grants'], 'user')
        expired_date = time.mktime(time.localtime(
            int(time.time()) + int(Config.EXPIRES_IN_AUTH)))
        result = {
            "user_id": user_id,
            "grants": user['credential']['grants'],
            "access_token": token.decode('utf8').replace("'", '"'),
            "expired_date": time.strftime("%Y-%m-%d %H:%M:%S",
                                          time.localtime(expired_date))
        }
        return result
Пример #18
0
 def get(self, client_id):
     """
     list users authorized (with scope) by app/client
     """
     users = UsersBusiness.get_all_by_client(client_id)
     return marshal({"users": users}, get_users_serializer())
Пример #19
0
 def post(self, token):
     status = UsersBusiness.valid_token_password(token)
     if not status:
         raise InternalServerError('Token not found or expired!')
     return {"status": bool(status), "message": "Successfully!"}
Пример #20
0
 def get(self):
     """
     user list
     """
     users = UsersBusiness.get_all()
     return marshal({"users": users}, get_users_serializer())