Ejemplo n.º 1
0
def invalidatetoken(client=None, user=None, **kwargs):
    """Invalidate a token.
    Provide at least a client or a user

    client   client_id or client_secret of an existing client
    user     username or email of an existing user
    """
    if not client and not user:
        helpers.abort("""Provide at least a client (client_id or client_secret)
             or a user (username or email)""")
    if user:
        user_inst = User.first((User.username == user) | (User.email == user))
        if not user_inst:
            return reporter.error('User not found', user)
        where_clause = (Session.user_id == user_inst.pk)
    else:
        client_inst = Client.first((Client.client_id == client)
                                   | (Client.client_secret == client))
        if not client_inst:
            return reporter.error('Client not found', user)
        where_clause = (Session.client_id == client_inst.pk)

    tokens = Token.select().join(Session).where(where_clause).where(
        Token.expires > utcnow())
    for token in tokens:
        token.expires = utcnow()
        token.save()
    reporter.notice('Invalidate {} tokens'.format(len(tokens)), tokens)
Ejemplo n.º 2
0
def tokengetter(access_token=None):
    if access_token:
        token = models.Token.first(models.Token.access_token == access_token)
        if token:
            if token.expires > utcnow(
            ) and token.expires < utcnow() + timedelta(minutes=30):
                token.expires = token.expires + timedelta(hours=1)
                token.save()
            context.set('session', token.session)
            # We use TZ aware datetime while Flask Oauthlib wants naive ones.
            token.expires = token.expires.replace(tzinfo=None)
            return token
Ejemplo n.º 3
0
 def mark_deleted(self):
     if self.deleted_at:
         raise ValueError("Resource already marked as deleted")
     self.ensure_no_reverse_relation()
     self.deleted_at = utcnow()
     self.increment_version()
     self.save()
Ejemplo n.º 4
0
 def mark_deleted(self):
     if self.deleted_at:
         raise ValueError('Resource already marked as deleted')
     self.ensure_no_reverse_relation()
     self.deleted_at = utcnow()
     self.increment_version()
     self.save()
Ejemplo n.º 5
0
def test_cannot_change_deleted_at_with_put(put):
    municipality = MunicipalityFactory()
    data = municipality.serialize({'*': {}})
    data['deleted_at'] = utcnow().isoformat()
    data['version'] = 2
    resp = put('/municipality/{}'.format(municipality.id), data=data)
    assert resp.status_code == 200
    assert not models.Municipality.get(
        models.Municipality.pk == municipality.pk).deleted_at
Ejemplo n.º 6
0
def test_cannot_change_deleted_at_with_put(put):
    municipality = MunicipalityFactory()
    data = municipality.serialize({'*': {}})
    data['deleted_at'] = utcnow().isoformat()
    data['version'] = 2
    resp = put('/municipality/{}'.format(municipality.id), data=data)
    assert resp.status_code == 200
    assert not models.Municipality.get(
        models.Municipality.pk == municipality.pk).deleted_at
Ejemplo n.º 7
0
class TokenFactory(BaseTestModel):
    session = factory.SubFactory(SessionFactory)
    token_type = 'password'
    access_token = FuzzyText(length=50)
    refresh_token = FuzzyText(length=50)
    scope = 'contrib'
    expires = factory.LazyAttribute(lambda x: utcnow() + timedelta(minutes=50))

    class Meta:
        model = auth_models.Token
Ejemplo n.º 8
0
 def update_meta(self):
     session = context.get('session')
     if session:
         if not self.created_by:
             self.created_by = session
         self.modified_by = session
     now = utcnow()
     if not self.created_at:
         self.created_at = now
     self.modified_at = now
Ejemplo n.º 9
0
class VersionFactory(BaseTestModel):
    model_name = 'resource'
    model_pk = FuzzyInteger(1, 97000)
    sequential = 1
    data = '{"nom":"factory"}'
    period = [
        utcnow(),
    ]

    class Meta:
        model = versioning.Version
Ejemplo n.º 10
0
 def update_meta(self):
     session = context.get('session')
     if session:  # TODO remove this if, session should be mandatory.
         try:
             getattr(self, 'created_by', None)
         except Session.DoesNotExist:
             # Field is not nullable, we can't access it when it's not yet
             # defined.
             self.created_by = session
         self.modified_by = session
     now = utcnow()
     if not self.created_at:
         self.created_at = now
     self.modified_at = now
Ejemplo n.º 11
0
 def update_meta(self):
     session = context.get('session')
     if session:  # TODO remove this if, session should be mandatory.
         try:
             getattr(self, 'created_by', None)
         except Session.DoesNotExist:
             # Field is not nullable, we can't access it when it's not yet
             # defined.
             self.created_by = session
         self.modified_by = session
     now = utcnow()
     if not self.created_at:
         self.created_at = now
     self.modified_at = now
Ejemplo n.º 12
0
def test_invalidate_token_with_client(capsys):
    client = factories.ClientFactory()
    session = factories.SessionFactory(client=client)
    valid_client = factories.ClientFactory()
    valid_session = factories.SessionFactory(client=valid_client)
    token = factories.TokenFactory(session=session)
    valid_token = factories.TokenFactory(session=valid_session)
    invalidatetoken(client=client.client_id)

    out, err = capsys.readouterr()
    assert 'Invalidate 1 token' in out
    updated_token = amodels.Token.first(amodels.Token.pk == token.pk)
    updated_valid_token = amodels.Token.first(
        amodels.Token.pk == valid_token.pk)
    assert utcnow().date() >= updated_token.expires.date()
    assert updated_token.is_expired
    assert updated_valid_token.is_valid()
Ejemplo n.º 13
0
 def is_expired(self):
     """
     Check token expiration with timezone awareness
     """
     return utcnow() >= self.expires
Ejemplo n.º 14
0
 def __init__(self, **kwargs):
     expires_in = kwargs.pop('expires_in', 60 * 60)
     kwargs['expires'] = utcnow() + timedelta(seconds=expires_in)
     super().__init__(**kwargs)
Ejemplo n.º 15
0
 def save(self, *args, **kwargs):
     if not self.created_at:
         self.created_at = utcnow()
     super().save(*args, **kwargs)
Ejemplo n.º 16
0
 def save(self, *args, **kwargs):
     if not self.created_at:
         self.created_at = utcnow()
     super().save(*args, **kwargs)
Ejemplo n.º 17
0
 def __init__(self, **kwargs):
     expires_in = kwargs.pop('expires_in', 60 * 60)
     kwargs['expires'] = utcnow() + timedelta(seconds=expires_in)
     super().__init__(**kwargs)
Ejemplo n.º 18
0
 def is_expired(self):
     """
     Check token expiration with timezone awareness
     """
     return utcnow() >= self.expires