示例#1
0
    def put(self, id):
        """
        generate new secret
        """
        secret = ClientsBusiness.generate_new_secret(id)
        if not secret:
            raise InternalServerError('Error generate secret!')

        return {"new_secret": secret}
示例#2
0
    def delete(self, client_id):
        """
        delete client
        """
        status = ClientsBusiness.delete(client_id)
        if not status:
            raise NotFound("Client not Found!")

        return {"message": "Deleted client!"}
示例#3
0
    def get(self, client_id):
        """
        list information from an active app/client
        """
        client = ClientsBusiness.get_by_id(client_id)
        if not client:
            raise NotFound("Client not Found!")

        return marshal(client, get_client_serializer(True)), 200
示例#4
0
文件: business.py 项目: mzaglia/oauth
    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))
        }
示例#5
0
    def put(self, client_id):
        """
        update client
        """
        data, status = validate(request.json, 'client_base')
        if status is False:
            raise BadRequest(json.dumps(data))

        client = ClientsBusiness.update(client_id, data)
        if not client:
            raise InternalServerError('Error updating client!')

        return {"message": "Updated Client!"}
示例#6
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')
        }
示例#7
0
    def post(self):
        user_id = request.id
        """
        create new client
        """
        data, status = validate(request.json, 'client_create')
        if status is False:
            raise BadRequest(json.dumps(data))

        client = ClientsBusiness.create(user_id, data)
        if not client:
            raise InternalServerError('Error creating client!')

        return marshal(client, get_client_serializer()), 201
示例#8
0
    def put(self, id, action):
        """
        enable or disable a client
        """

        if action.lower() not in ['enable', 'disable']:
            raise BadRequest('Action not found. Set "enable or disable"!')

        data = {}
        if action == 'enable':
            data, status = validate(request.json, 'date_expiration')
            if status is False:
                raise BadRequest(json.dumps(data))

        status = ClientsBusiness.update_date_expiration(
            id, action, data.get('expired_at', None))
        if not status:
            raise NotFound("Client not Found!")

        return {"message": "Updated client!"}
示例#9
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!')
示例#10
0
 def get(self):
     """
     list clients that are not expired
     """
     clients = ClientsBusiness.get_all()
     return marshal({"clients": clients}, get_clients_serializer())
示例#11
0
 def delete(self, client_id, user_id):
     """
     remove author in client/application
     """
     _ = ClientsBusiness.delete_author(client_id, user_id)
     return {"message": "Updated client!"}
示例#12
0
 def post(self, client_id, user_id):
     """
     add new author in client/application
     """
     _ = ClientsBusiness.add_author(client_id, user_id)
     return {"message": "Updated client!"}
示例#13
0
 def get(self, id):
     """
     list clients by a user (if the user is an admin of the app)
     """
     clients = ClientsBusiness.list_by_userid(id)
     return marshal({"clients": clients}, get_clients_serializer(True))
示例#14
0
 def get(self, user_id):
     """
     list clients created by a user
     """
     clients = ClientsBusiness.list_by_userid(user_id)
     return marshal({"clients": clients}, get_clients_serializer())