Example #1
0
    def prepare(self):
        """Override the prepare RequestHandler method.
        Check if the Client send correct token and if the token need refresh.
        Support the Authorization Header check or the GET access_token.
        if the Client don't send a Token or the token is incorrect this method flush a 403 HTTP Error."""

        token = None
        #frst we check if the authentication token is send by the Autorization header
        if 'Authorization' in self.request.headers:
            auth_header = self.request.headers['Authorization']
            #the authentication token is send like Bearer <token>
            #we need to split the string and obtain the token
            header_parts = auth_header.split(' ')
            token = header_parts[1]
        elif self.get_argument('access_token'):
            token = self.get_argument('access_token')
        else:
            raise tornado.web.HTTPError(403,"not authorized, no token send")

        #check if the token is correct
        try:
            grant = Grant()
            results = grant.get(token=token)
        except ObjectDoesNotExist, e:
            raise tornado.web.HTTPError(403,"invalid authorization token incorrect")
Example #2
0
    def post(self):
        """POST action to authorize the Client Application.
        To authorize will be send a POST with 'grant' parameter set to true, to deny 'parameter' set to false."""
        grant = self.get_argument("grant")
        client_id = self.get_argument("client_id")
        response_type = self.get_argument("response_type")
        redirect_uri = self.get_argument("redirect_uri")
        scope = self.get_argument("scope")
        # the client send correct paramenters, we need to check if the client id exist and we
        # create the relation between the user-agent and the client
        if grant == "true":
            try:
                #check if the client exist
                client = Client()
                exist = client.get(client_id=client_id)
                if exist['redirect_uri'] != redirect_uri:
                    #have an error, return a 403
                    raise tornado.web.HTTPError(403,"redirect uri problem")
            except ObjectDoesNotExist, e:
                raise tornado.web.HTTPError(403,"the client id not correspond to any Client")

            grant = Grant()
            try:
                #we accept the grant for the user
                grant.is_already_authorized(client_id,self.get_current_user())
                grant.update(client_id,self.get_current_user())
            except ObjectDoesNotExist, e:
                grant.add(client_id,self.get_current_user())
Example #3
0
def save_grant(client_id, code, request, *args, **kwargs):
    # decide the expires time yourself
    expires = datetime.utcnow() + timedelta(seconds=1000)
    client = Client.query.filter_by(client_id=client_id).first()
    grant = Grant(client_id=client_id,
                  code=code['code'],
                  redirect_uri=request.redirect_uri,
                  _scopes=' '.join(request.scopes),
                  user=client.user_id,
                  expires=expires)
    db.session.add(grant)
    db.session.commit()
    return grant
Example #4
0
def prepare_db():
    client1 = Client(
        name='dev', client_id='dev', client_secret='dev',
        _redirect_uris=(
            'http://localhost:8000/authorized '
            'http://localhost/authorized '
            'http://127.0.0.1:8000/authorized'
        ),
    )

    client2 = Client(
        name='confidential', client_id='confidential',
        client_secret='confidential', client_type='confidential',
        _redirect_uris=(
            'http://localhost:8000/authorized '
            'http://localhost/authorized '
            'http://127.0.0.1:8000/authorized'
        ),
    )

    user = User(username='******', password='******')

    temp_grant = Grant(
        user_id=1, client_id='confidential',
        code='12345', scope='email',
        expires=datetime.utcnow() + timedelta(seconds=100)
    )

    access_token = Token(
        user_id=1, client_id='dev', access_token='expired', expires_in=5
    )

    access_token2 = Token(
        user_id=1, client_id='dev', access_token='expired', expires_in=1
    )

    try:
        db.session.add(client1)
        db.session.add(client2)
        db.session.add(user)
        db.session.add(temp_grant)
        db.session.add(access_token)
        db.session.add(access_token2)
        db.session.commit()
    except:
        db.session.rollback()
Example #5
0
def modal_add():
    form = ModalForm()
    print 111111111111111
    print form.data

    if form.validate_on_submit():
        data = form.data
        modal_data = Grant(
            myrole=data["myrole"],
            authip=data["authip"],
        )
        print 22222222
        print data["myrole"]
        db.session.add(modal_data)
        db.session.commit()
        flash("添加数据库权限成功", "ok")
        return redirect(url_for("admin.grant_list", page=1))
    return render_template("admin/modal.html")
def connect_finance(connections, ftype):
    if connections:
        for finance in connections:
            try:
                source = Entity.query.filter_by(id=old_to_new[finance['source']]).first()
                target = Entity.query.filter_by(id=old_to_new[finance['target']]).first()
                if ftype == 'funding':
                    grant = Grant(finance['amount'], finance['year'])
                    # Odd civic.json convention of source/target "received"
                    source.grants_received.append(grant)
                    target.grants_given.append(grant)
                elif ftype == 'investment':
                    investment = Investment(finance['amount'], finance['year'])
                    # Odd civic.json convention of source/target "received"
                    source.investments_received.append(investment)
                    target.investments_made.append(investment)
            except KeyError as e:
                # Some IDs in civic.json aren't rendered... 
                # Point to them manually.
                print "Failed to find ID: ", e
Example #7
0
def modal_list(page=None):
    form = ModalForm()
    if page is None:
        page = 1
    modal_data = Mysqluser.query.paginate(page=page, per_page=2)
    if request.method == "POST":
        data = form.data
        print data
        modal = Grant(
            myrole=data["myrole"],
            authip=data["authip"],
        )
        db.session.add(modal)
        db.session.commit()
        flash("添加数据库权限成功", "ok")
        return redirect(url_for("admin.modal_list", page=1))
    return render_template("admin/modal.html",
                           modal_data=modal_data,
                           url="admin.modal_list",
                           page=page,
                           form=form)
Example #8
0
    def update_fundingconnections(connections, ftype, direction):
        # Delete and connections that have been removed.
        new_connections = [
            connection['id'] for connection in connections if connection['id']
        ]
        # TODO: See if you can make this generic to handle any set of connections for simplicity.
        # TODO: Maybe list comprehensions in stead depending on how cascade='delete-orphan' works.
        if ftype is 'investment':
            if direction is 'given':
                for connection in entity.investments_made:
                    if connection.id not in new_connections:
                        db.delete(connection)
            elif direction is 'received':
                for connection in entity.investments_received:
                    if connection.id not in new_connections:
                        db.delete(connection)
        elif ftype is 'grant':
            if direction is 'given':
                for connection in entity.grants_given:
                    if connection.id not in new_connections:
                        db.delete(connection)
            elif direction is 'received':
                for connection in entity.grants_received:
                    if connection.id not in new_connections:
                        db.delete(connection)
        db.commit()

        for connection in connections:
            if connection['id']:
                # Connection exists, update amount and year.
                oldconnection = Fundingconnection.query.get(connection['id'])
                if oldconnection.amount != connection['amount']:
                    oldconnection.amount = connection['amount']
                    app.logger.debug('UPDATING ' + ftype + ' AMOUNT: ' +
                                     str(oldconnection.amount))
                if oldconnection.year != connection['year']:
                    oldconnection.year = connection['year']
                    app.logger.debug('UPDATING ' + ftype + ' YEAR: ' +
                                     str(oldconnection.year))
            elif 'entity_id' in connection:
                # Connection doesn't exist, create it connect entities.
                otherentity = Entity.query.get(connection['entity_id'])
                if ftype is 'investment':
                    newconnection = Investment(connection['amount'],
                                               connection['year'])
                    if direction is 'given':
                        entity.investments_made.append(newconnection)
                        otherentity.investments_received.append(newconnection)
                    elif direction is 'received':
                        entity.investments_received.append(newconnection)
                        otherentity.investments_made.append(newconnection)
                elif ftype is 'grant':
                    newconnection = Grant(connection['amount'],
                                          connection['year'])
                    if direction is 'given':
                        entity.grants_given.append(newconnection)
                        otherentity.grants_received.append(newconnection)
                    elif direction is 'received':
                        entity.grants_received.append(newconnection)
                        otherentity.grants_given.append(newconnection)
        db.commit()
Example #9
0
            except ObjectDoesNotExist, e:
                self.set_status(204)
                self.write_result({},"call")


    def post(self):
        """Method POST to add a new call on ongoing status."""

        try:
            call_app = Call()
            call_app.check_allowed_calls(self._grant_token,MAXIMUM_ONGOING_CALL)
        except RestMaxCallError, e:
            raise tornado.web.HTTPError(409,"maximum ongoin calls reached")

        number = self.get_argument("number")
        grant_app = Grant()
        grant_id = grant_app.get(token=self._grant_token)
        call_start = Call()
        token_call = call_start.start_call(grant_id['id'],number)
        self.set_status(201)
        self.set_header("Location",DOMAIN_REST+"/call?token_call="+token_call)
        self.write("")

    def put(self):
        """PUT method to udpate the status of the call, in this case is stop the call and actualize the end time and the duration"""
        token_call = self.get_argument("token_call")
        call_stop = Call()
        returned_call = call_stop.get(token=token_call)
        if returned_call['duration'] is None:
            call_stop.update(token_call)
        self.set_status(200)