Exemplo n.º 1
0
def user_chemail():
    form = ChangeEmailForm(request.form)

    if request.method == 'POST' and form.validate():
        old = form.old_email.data
        new = form.new_email.data
        pwd = form.password.data

        if None in [old,new] or old == new:
            raise ResponseError()

        if old != g.user.email or not g.user.verify_pass(pwd):
            raise ResponseError(403, 'Wrong email or password', 'Please provide your original email and current password.')

        token = g.user.create_reset_token(
                app.config['SECRET'], app.config['RESET_TIMEOUT'], which='email',
                extra={'new_email':new}
                )

        if not token:
            raise ResponseError()

        # email user

        g.user.inactivate()
        delattr(g, 'user')
        resp = template('email_sent.html')
        resp = set_auth_cookie(resp, 'null', current_date())

        return resp

    return template('change_email.html', dict(form=form))
Exemplo n.º 2
0
Arquivo: models.py Projeto: vixus0/apd
 def ban(self):
     '''Ban this user.'''
     if not self.banned:
         self.expire_sessions()
         self.banned = True
         self.banned_date = current_date()
         self.save()
Exemplo n.º 3
0
Arquivo: models.py Projeto: vixus0/apd
    def available_items(cls, user, resource):
        items = cls\
                .select(
                    cls.resource_id,
                    )\
                .where(
                    cls.user == user,
                    cls.resource == resource,
                    cls.expires >= current_date(),
                    )

        return items
Exemplo n.º 4
0
def admin_subs(user_id, resource=None, res_id=None):
    try:
        user = ApdUser.get(ApdUser.keyfield() == user_id)
    except ApdUser.NotFound:
        raise ResponseError(404, 'No such user')

    if request.method == 'GET':
        # Return user's subscriptions
        sub_rows = Subscription.select().where(
                (Subscription.user == user) &
                (Subscription.resource << sub_resources)
                )

        subs = {res:{'all':False,'idx':[]} for res in sub_resources}
        min_id = {res:0 for res in sub_resources}

        for row in sub_rows:
            min_id[row.resource] = min(min_id[row.resource], row.resource_id)
            days_left = max(0, (row.expires - current_date()).days)
            subs[row.resource]['idx'].append({
                'id' : row.resource_id,
                'expires_in' : days_left
                })

        for res in sub_resources:
            subs[res]['all'] = min_id[res] == -1

        return jsonify(subscriptions=subs)

    elif request.method == 'PUT':
        # Update user's subscriptions
        dat = request.get_json(silent=True)

        if dat:
            ret = Subscription.change(user, dat['subscriptions'], dat['extend_days'])

            if ret:
                return jsonify(updated=ret)
            else:
                raise ResponseError()

        else:
            raise ResponseError()
Exemplo n.º 5
0
Arquivo: models.py Projeto: vixus0/apd
    def create_session(self, secret, timeout, location):
        '''Create a new session for this user.'''
        if not self.is_active:
            return None

        currt = current_date()
        endt = currt + timedelta(seconds=timeout)

        self.expire_sessions()

        session = Session.create(user=self,
                                 location=location,
                                 start_time=currt,
                                 end_time=endt)

        data = {'session': session.id}
        token = create_token(data, secret, salt='session', timeout=timeout)

        return token, endt
Exemplo n.º 6
0
Arquivo: models.py Projeto: vixus0/apd
    def change(cls, user, res_idx, days=30):
        '''Update subscriptions for the given user.'''
        cdate = current_date()
        expires_at = cdate + timedelta(days=days)
        updated = {}

        with db.atomic():
            for res, idx in res_idx.items():
                flt = (cls.user == user) & (cls.resource == res)

                # Delete rows if not in idx
                dq = cls.delete().where(flt & (cls.resource_id.not_in(idx)))
                dq.execute()

                # Select remaining rows
                sq = cls.select(cls.resource_id).where(flt).tuples()
                sq = [i[0] for i in sq]

                # Update expiry time
                uq = cls.update(expires=expires_at).where(flt).execute()

                # Insert new rows
                data_src = []
                upd_idx = []

                for id in idx:
                    id = int(id)
                    if id not in sq:
                        data_src.append({
                            'user': user,
                            'resource': res,
                            'resource_id': id,
                            'expires': expires_at
                        })
                        upd_idx.append(id)

                if len(data_src) > 0:
                    cls.insert_many(data_src).execute()

                updated[res] = upd_idx

        return updated
Exemplo n.º 7
0
Arquivo: models.py Projeto: vixus0/apd
    def refresh_session(self, secret, timeout):
        '''Extend the current active session.'''
        if not (self.active_session and self.is_active):
            return None

        currt = current_date()
        endt = currt + timedelta(seconds=timeout)

        active_session = self.active_session

        if currt >= active_session.end_time:
            return None

        data = {'session': active_session.id}
        token = create_token(data, secret, salt='session', timeout=timeout)

        active_session.end_time = endt
        active_session.save()

        return token, endt
Exemplo n.º 8
0
def user_chpass():
    form = ChangePwdForm(request.form)

    if request.method == 'POST' and form.validate():
        old = form.old_password.data
        new = form.new_password.data

        if None in [old,new] or old == new:
            raise ResponseError()

        if not g.user.verify_pass(old):
            raise ResponseError(403, 'Wrong password', 'Please provide your original password.')

        g.user.set_pass(new)
        g.user.expire_sessions()
        delattr(g, 'user')
        resp = redirect(url_for('user_login'))
        resp = set_auth_cookie(resp, 'null', current_date())

        return resp

    return template('change_password.html', dict(form=form))
Exemplo n.º 9
0
def user_logout():
    user = g.get('user', None)

    if request.method == 'GET':
        if user:
            if not user.is_authenticated:
                raise redirect(url_for('index'))
        else:
            return redirect(url_for('index'))
        return template('logout.html')

    elif request.method == 'POST':
        value = request.form.get('confirm')
        next = request.form.get('next')
        next = check_url(next) or url_for('index')

        if value == 'accept':
            g.user.expire_sessions()
            delattr(g, 'user')
            resp = redirect(url_for('index'))
            resp = set_auth_cookie(resp, 'null', current_date())
            return resp
        else:
            return redirect(next)
Exemplo n.º 10
0
Arquivo: models.py Projeto: vixus0/apd
 def expire_sessions(self):
     '''Expire all previous sessions.'''
     currt = current_date()
     query = Session.update(active = False, end_time = currt)\
                    .where((Session.user == self) & (Session.active == True))
     query.execute()