Ejemplo n.º 1
0
def feed_atom(request):
    "Phnom Penh events of the day"
    today = helpers.today()
    return  render_to_response(request, 'ladypenh/atom.xml',
                               dict(events=helpers.get_events(today),
                                    today=today),
                               mimetype='application/atom+xml; charset=utf8')
Ejemplo n.º 2
0
def view(sqlsession, id):
    id = int(id)
    active = 'users'
    user = None
    if id > 0:
        user = sqlsession.query(models.User).filter_by(id=int(id)).first()

    permissions = None
    if user:
        print('actual', user.level)
        print('needed', OVER_NINETHOUSAND)
        permissions = [
            user.level & CAN_LOGIN,
            user.level & MANIPULATE_USERS,
            user.level & MANIPULATE_TOKENS,
            user.level & MANIPULATE_DEVICES,
            user.level & OVER_NINETHOUSAND
        ]

    users = sqlsession.query(models.User).filter_by().order_by(models.User.name.asc()).all()
    return render_template(
        'user.html',
        active=active,
        date=helpers.today(),
        id=id,
        user=user,
        users=users,
        permissions=permissions,
        previous=dict(request.args.items(multi=False))
    )
Ejemplo n.º 3
0
def view(sqlsession, id):
    id = int(id)
    active = 'users'

    user = None
    if id > 0:
        user = sqlsession.query(models.User).filter_by(id=int(id)).first()

    permissions = None
    if user:
        permissions = [
            user.level & CAN_LOGIN,
            user.level & MANIPULATE_USERS,
            user.level & MANIPULATE_TOKENS,
            user.level & MANIPULATE_DEVICES,
            user.level & OVER_NINETHOUSAND
        ]

    users = sqlsession.query(models.User).filter_by().order_by(models.User.name.asc()).all()
    return render_template(
        'user.html',
        active=active,
        date=helpers.today(),
        id=id,
        user=user,
        users=users,
        permissions=permissions,
        previous=dict(request.args.items(multi=False))
    )
Ejemplo n.º 4
0
def events(request, date=None):
    today = day = datetime.now().date()
    try:
        reqday = datetime.strptime(date, "%Y-%m-%d").date()
        if request.user.is_authenticated() or (reqday - day).days in range(7):
            day = reqday
    except:
        # just use today date
        pass
    days = helpers.get_days(0)
    daylabels = [(days[0], 'Today'), (days[1], 'Tomorrow')]
    for d in days[2:]:
        daylabels.append((d, d.strftime('%A')))
    article, tags = None, []
    show_edit_links = False
    if request.user.is_authenticated():
        show_edit_links = True
    article,tags=helpers.get_article(today)
    return  render_to_response(request, 'ladypenh/day.html',
                               dict(theme_name=helpers.get_theme(helpers.today()),
                                    day=day,                               
                                    daylabels=daylabels,
                                    highlights=helpers.get_highlights(days),
                                    events=helpers.get_events(day),
                                    reminders=helpers.get_reminders(day),
                                    show_edit_links=show_edit_links,
                                    article=article,
                                    tags=tags
                                    ))
Ejemplo n.º 5
0
def article(request, nid):
    article, tags = helpers.get_article_by_id(nid)
    return  render_to_response(request, 'ladypenh/article.html',
                               dict(theme_name=helpers.get_theme(helpers.today()),
                                    article=article,
                                    tags=tags,
                                    ads=helpers.get_ads()))
Ejemplo n.º 6
0
def search(sqlsession, type, id):
    id = int(id)
    active = 'search'

    user = None
    if id > 0:
        user = sqlsession.query(models.User).filter_by(id=int(id)).first()

    device = None
    if id > 0:
        device = sqlsession.query(models.Device).filter_by(id=id).first()

    users = sqlsession.query(models.User).filter(models.User.name.like('%' + request.args.get('q') + '%')).all()
    devices = sqlsession.query(models.Device).filter(models.Device.name.like('%' + request.args.get('q') + '%')).all()
    return render_template(
        'search.html',
        active=active,
        date=helpers.today(),
        id=id,
        q=request.args.get('q'),
        type=type,
        user=user,
        users=users,
        device=device,
        devices=devices
    )
Ejemplo n.º 7
0
def search(sqlsession, type, id):
    id = int(id)
    active = 'search'

    user = None
    if id > 0:
        user = sqlsession.query(models.User).filter_by(id=int(id)).first()

    device = None
    if id > 0:
        device = sqlsession.query(models.Device).filter_by(id=id).first()

    users = sqlsession.query(models.User).filter(
        or_(models.User.name.like('%' + request.args.get('q') + '%'),
            models.User.username.like('%' + request.args.get('q') +
                                      '%'))).all()
    devices = sqlsession.query(models.Device).filter(
        models.Device.name.like('%' + request.args.get('q') + '%')).all()
    return render_template('search.html',
                           active=active,
                           date=helpers.today(),
                           id=id,
                           q=request.args.get('q'),
                           type=type,
                           user=user,
                           users=users,
                           device=device,
                           devices=devices)
Ejemplo n.º 8
0
def venue(request, key):
    days = helpers.get_days()
    key = db.Key(key)
    return render_to_response(request, 'ladypenh/venue.html',
                              dict(theme_name=helpers.get_theme(helpers.today()),
                                   events=helpers.get_venue_events(days, key),
                                   files=helpers.get_venue_files(days, key),
                                   venue=helpers.get_venue_by_key(key)))
Ejemplo n.º 9
0
def lpvenue(request, venue):
    days = helpers.get_days()
    venue = helpers.get_venue_by_name(venue)
    return render_to_response(request, 'ladypenh/venue.html',
                              dict(theme_name=helpers.get_theme(helpers.today()),
                                   events=helpers.get_venue_events(days, venue.key()),
                                   files=helpers.get_venue_files(days, venue.key()),
                                   venue=venue))
Ejemplo n.º 10
0
    def add(sqlsession, **kwargs):
        error = False
        errors = []
        name = None
        description = None
        expiry_date = None
        owner = None

        for attribute in kwargs:
            if attribute == 'owner':
                if type(kwargs[attribute]) == int:
                    owner = sqlsession.query(
                        models.User).filter_by(id=owner).first()

                if not owner:
                    if 'owner_name' in kwargs:
                        owner_query = sqlsession.query(
                            models.User).filter_by(name=kwargs['owner_name'])
                        if owner_query.count() == 1:
                            owner = owner_query.first()
                        else:
                            errors.append(('owner', 'User was not found.'))
                    else:
                        errors.append(('owner', 'User was not found.'))

            elif attribute == 'expiry_date':
                try:
                    expiry_date = helpers.str_to_date(kwargs[attribute])
                except BaseException:
                    error = True
                    errors.append((
                        'expiry_date',
                        'Expiry date has a bad format. It should be YYYY-mm-dd.'
                    ))

            elif attribute == 'name':
                name = kwargs[attribute]

            elif attribute == 'description':
                description = kwargs[attribute]

            else:
                pass

        if not error:
            token = models.Token(name=name,
                                 value=helpers.generate_token(),
                                 description=description,
                                 owner=owner,
                                 flashed=False,
                                 expiry_date=expiry_date,
                                 creation_date=helpers.today())
            sqlsession.add(token)
            sqlsession.commit()
            return token.id, None

        else:
            return False, errors
Ejemplo n.º 11
0
    def add(sqlsession, **kwargs):
        error = False
        errors = []
        name = None
        description = None
        expiry_date = None
        owner = None

        for attribute in kwargs:
            if attribute == 'owner':
                if type(kwargs[attribute]) == int:
                    owner = sqlsession.query(models.User).filter_by(id=owner).first()

                if not owner:
                    if 'owner_name' in kwargs:
                        owner_query = sqlsession.query(models.User).filter_by(name=kwargs['owner_name'])
                        if owner_query.count() == 1:
                            owner = owner_query.first()
                        else:
                            errors.append(('owner', 'User was not found.'))
                    else:
                        errors.append(('owner', 'User was not found.'))

            elif attribute == 'expiry_date':
                try:
                    expiry_date = helpers.str_to_date(kwargs[attribute])
                except BaseException:
                    error = True
                    errors.append(('expiry_date', 'Expiry date has a bad format. It should be YYYY-mm-dd.'))

            elif attribute == 'name':
                name = kwargs[attribute]

            elif attribute == 'description':
                description = kwargs[attribute]

            else:
                pass

        if not error:
            token = models.Token(
                name=name,
                value=helpers.generate_token(),
                description=description,
                owner=owner,
                flashed=False,
                expiry_date=expiry_date,
                creation_date=helpers.today()
            )
            sqlsession.add(token)
            sqlsession.commit()
            return token.id, None

        else:
            return False, errors
Ejemplo n.º 12
0
def revoke(sqlsession):
    token = sqlsession.query(models.Token).filter_by(id=request.form['token_id']).first()

    if token:
        token.expiry_date = helpers.today() - datetime.timedelta(days=1)
        flash('Token with id %d was has successfully been revoked' % token.id, 'success')

    else:
        flash('Token with id %d was not found.' % request.form['token_id'], 'danger')

    return redirect(request.referrer)
Ejemplo n.º 13
0
def tokens(sqlsession):
    active = 'profile'

    user = sqlsession.query(
        models.User).filter_by(username=session['username']).first()

    return render_template('profile_tokens.html',
                           active=active,
                           category='tokens',
                           user=user,
                           date=helpers.today())
Ejemplo n.º 14
0
    def activate(sqlsession, token):
        if type(token) == int:
            token = sqlsession.query(models.Token).filter_by(id=token).first()

        if token:
            for date in config('semester_end_dates'):
                date = helpers.str_to_date(date)
                if date <= helpers.today():
                    continue
                token.expiry_date = date
                return date
        return False
Ejemplo n.º 15
0
    def activate(sqlsession, token):
        if type(token) == int:
            token = sqlsession.query(models.Token).filter_by(id=token).first()

        if token:
            for date in config('semester_end_dates'):
                date = helpers.str_to_date(date)
                if date <= helpers.today():
                    continue
                token.expiry_date = date
                return date
        return False
Ejemplo n.º 16
0
def view(sqlsession, id):
    id = int(id)
    active = 'tokens'
    tokens = sqlsession.query(models.Token).filter_by().all()
    token = sqlsession.query(models.Token).filter_by(id=id).first()

    return render_template('token.html',
                           active=active,
                           date=helpers.today(),
                           id=id,
                           token=token,
                           tokens=tokens,
                           previous=dict(request.args.items(multi=False)))
Ejemplo n.º 17
0
def view(sqlsession, id):
    id = int(id)
    active = 'devices'
    device = None
    if id > 0:
        device = sqlsession.query(models.Device).filter_by(id=id).first()
    devices = sqlsession.query(models.Device).filter_by().all()

    return render_template('device.html',
                           active=active,
                           date=helpers.today(),
                           id=id,
                           device=device,
                           devices=devices,
                           previous=dict(request.args.items(multi=False)))
Ejemplo n.º 18
0
def view(sqlsession, id):
    id = int(id)
    active = 'devices'
    device = None
    if id > 0:
        device = sqlsession.query(models.Device).filter_by(id=id).first()
    devices = sqlsession.query(models.Device).filter_by().all()

    return render_template(
        'device.html',
        active=active,
        date=helpers.today(),
        id=id,
        device=device,
        devices=devices,
        previous=dict(request.args.items(multi=False))
    )
Ejemplo n.º 19
0
def add(sqlsession):
    error = False

    if not error:
        device = models.Device(name=request.form['add_device_name'],
                               pubkey=request.form['add_device_pubkey'],
                               creation_date=helpers.today())
        sqlsession.add(device)
        sqlsession.commit()
        flash('New device was created successfully', 'success')
        return redirect(url_for('device.view', id=device.id))

    else:
        return redirect(
            url_for('device.view',
                    device_name=request.form['add_device_name'],
                    device_pubkey=request.form['add_device_pubkey']))
Ejemplo n.º 20
0
    def handle_query(session, self, query):
        response = Query()
        self.logger.debug('Handle query:')
        self.logger.debug(query.query)
        if query.method == 'ACCESS':
            token = session.query(Token).filter_by(value=query.params[0]).first()
            device = session.query(Device).filter_by(pubkey_device=query.token).first()
            if len(query.params) == 1:
                if token in device.tokens and token.expiry_date >= helpers.today():
                    response.create_grant(config.server_token, query.params[0])
                    self.logger.info('Granted access to token %s at device %s' % (query.params[0], query.token))
                else:
                    response.create_deny(config.server_token, query.params[0])
                    self.logger.info('Denied access to token %s at device %s' % (query.params[0], query.token))

                self.issue_query(query.token, response)
            else:
                self.logger.debug('Broken query. Expected exactly 1 parameter.')

        elif query.method == 'FLASH':
            self.logger.info('Requested flash of token %s at device %s' % (query.params[0], query.params[1]))
            if len(query.params) == 2:
                if query.token in self.connection_manager.webuis:
                    response.create_flash(config.server_token, query.params[0])
                    self.issue_query(query.params[1], response)
                else:
                    self.logger.info('Requested flash came from a non webui or an unregistered one. It was discarded.')
            else:
                self.logger.debug('Broken query. Expected exactly 2 parameters.')

        elif query.method == 'FLASHED':
            if len(query.params) == 1:
                session.query(Token).filter_by(value=query.params[0]).first().flashed = True
                self.logger.debug('Token %s was flashed' % query.params[0])
            self.logger.debug('Broken query. Expected exactly 1 parameter.')

        elif query.method == 'OPEN':
            if len(query.params) == 1:
                if query.token in self.connection_manager.webuis:
                    response.create_open(config.server_token)
                    self.issue_query(query.params[0], response)
                    self.logger.debug('Sent OPEN to device with token %s.' % query.params[0])
                else:
                    self.logger.info('Requested flash came from a non webui or an unregistered one. It was discarded.')
            self.logger.debug('Broken query. Expected exactly 1 parameter.')
Ejemplo n.º 21
0
def query_access(sqlsession, backdoor, query):
    response = Query(service=__service_name__)
    if len(query.params) == 1:
        token = sqlsession.query(Token).filter_by(
            value=query.params[0]).first()
        device = sqlsession.query(Device).filter_by(pubkey=query.token).first()
        if token in device.tokens and token.expiry_date >= helpers.today():
            response.create_grant(config.server_token, query.params[0])
            response.query['cmd']['name'] = token.owner.name
            backdoor.logger.info('Granted access to token %s at device %s' %
                                 (query.params[0], query.token))
        else:
            response.create_deny(config.server_token, query.params[0])
            backdoor.logger.info('Denied access to token %s at device %s' %
                                 (query.params[0], query.token))

        backdoor.issue_query(query.token, response)
    else:
        backdoor.logger.debug('Broken query. Expected exactly 1 parameter.')
Ejemplo n.º 22
0
def add(sqlsession):
    error = False

    if not error:
        device = models.Device(
            name=request.form['add_device_name'],
            pubkey=request.form['add_device_pubkey'],
            creation_date=helpers.today()
        )
        sqlsession.add(device)
        sqlsession.commit()
        flash('New device was created successfully', 'success')
        return redirect(url_for('device.view', id=device.id))

    else:
        return redirect(url_for(
            'device.view',
            device_name=request.form['add_device_name'],
            device_pubkey=request.form['add_device_pubkey']
        ))
Ejemplo n.º 23
0
def query_info(sqlsession, backdoor, query):
    response = Query(service=__service_name__)
    if query.query['cmd']['ask']:
        token = sqlsession.query(Token).filter_by(
            value=query.query['cmd']['token']).first()
        device = sqlsession.query(Device).filter_by(pubkey=query.token).first()
        if token in device.tokens and token.expiry_date >= helpers.today():
            response.create_info(config.server_token,
                                 query.query['cmd']['token'], False,
                                 token.user)
            backdoor.logger.info('Granted info for token %s to device %s' %
                                 (query.query['cmd']['token'], query.token))
        else:
            response.create_info(config.server_token,
                                 query.query['cmd']['token'], False, None)
            backdoor.logger.info('Denied info for token %s to device %s' %
                                 (query.query['cmd']['token'], query.token))

        backdoor.issue_query(query.token, response)
    else:
        backdoor.logger.debug('Broken query. Expected an ask.')
Ejemplo n.º 24
0
def query_sound_request(sqlsession, backdoor, query):
    response = Query(service=__service_name__)
    if query.query['cmd']['ask']:
        token = sqlsession.query(Token).filter_by(
            value=query.query['cmd']['token']).first()
        device = sqlsession.query(Device).filter_by(pubkey=query.token).first()
        if token in device.tokens and token.expiry_date >= helpers.today():
            path = sqlsession.query(User).filter_by(user=token.owner,
                                                    device=device).first().path
            response.create_sound_request(config.server_token,
                                          query.query['cmd']['token'], False,
                                          path)
            backdoor.logger.info('Granted sound id for token %s to device %s' %
                                 (query.query['cmd']['token'], query.token))
        else:
            response.create_sound_request(config.server_token,
                                          query.query['cmd']['token'], False,
                                          None)
            backdoor.logger.info('Denied sound id for token %s to device %s' %
                                 (query.query['cmd']['token'], query.token))

        backdoor.issue_query(query.token, response)
    else:
        backdoor.logger.debug('Broken query. Expected exactly 1 parameter.')
Ejemplo n.º 25
0
    def add(sqlsession, **kwargs):
        error = False
        errors = []
        username = None
        password = None
        level = None
        name = None
        email = None
        nethzid = None

        for attribute in kwargs:

            if attribute == 'username':
                existing_user = sqlsession.query(User).filter_by(username=kwargs[attribute].lower()).first()
                if existing_user:
                    error = True
                    errors.append(('username', 'Username is already taken.'))
                else:
                    username = kwargs[attribute]

            elif attribute == 'password':
                if len(kwargs[attribute]) < 8:
                    error = True
                    errors.append(('password', 'Please enter a password of at least 8 signs.'))
                else:
                    password = hashlib.sha256(kwargs[attribute].encode('utf-8'))

            elif attribute == 'level':
                if kwargs[attribute] == 'over 9000' or kwargs[attribute] == '> 9000' or kwargs[attribute] == 'over ninethousand':
                    kwargs[attribute] = 16384
                if kwargs[attribute] == '':
                    kwargs[attribute] = 0
                try:
                    kwargs[attribute] = int(kwargs[attribute])
                except Exception:
                    pass
                if type(kwargs[attribute]) != int:
                    error = True
                    errors.append(('level', 'Please enter a valid number as the userlevel.'))
                else:
                    level = kwargs[attribute]

            elif attribute == 'name':
                name = kwargs[attribute]

            elif attribute == 'email':
                if not re.match(r'[\w.-]+@[\w.-]+.\w+', kwargs[attribute]):
                    error = True
                    errors.append(('email', 'Please enter a valid email address.'))
                else:
                    email = kwargs[attribute]

            elif attribute == 'nethzid':
                nethzid = kwargs[attribute]

            else:
                pass

        if not error:
            if (((username and password and (level & (permission_flags.OVER_NINETHOUSAND\
            | permission_flags.CAN_LOGIN)) > 0)) or name) and (email or nethzid):
                user = User(
                    creation_date=helpers.today(),
                    username=username,
                    password=password.hexdigest(),
                    name=name,
                    level=level,
                    email=email,
                    nethzid=nethzid
                )
                sqlsession.add(user)
                sqlsession.commit()
                return user.id, None
            else:
                errors.append(('general', 'Failed to create user. You need to at least fill a name and (an email and or a nethzid).'))
        return False, errors
Ejemplo n.º 26
0
    def add(sqlsession, **kwargs):
        error = False
        errors = []
        username = None
        password = None
        level = None
        name = None
        email = None
        nethzid = None

        for attribute in kwargs:

            if attribute == 'username':
                existing_user = sqlsession.query(User).filter_by(
                    username=kwargs[attribute].lower()).first()
                if existing_user:
                    error = True
                    errors.append(('username', 'Username is already taken.'))
                else:
                    username = kwargs[attribute]

            elif attribute == 'password':
                if len(kwargs[attribute]) < 8:
                    error = True
                    errors.append(
                        ('password',
                         'Please enter a password of at least 8 signs.'))
                else:
                    password = hashlib.sha256(
                        kwargs[attribute].encode('utf-8'))

            elif attribute == 'level':
                if kwargs[attribute] == 'over 9000' or kwargs[
                        attribute] == '> 9000' or kwargs[
                            attribute] == 'over ninethousand':
                    kwargs[attribute] = 16384
                if kwargs[attribute] == '':
                    kwargs[attribute] = 0
                try:
                    kwargs[attribute] = int(kwargs[attribute])
                except Exception:
                    pass
                if type(kwargs[attribute]) != int:
                    error = True
                    errors.append(
                        ('level',
                         'Please enter a valid number as the userlevel.'))
                else:
                    level = kwargs[attribute]

            elif attribute == 'name':
                name = kwargs[attribute]

            elif attribute == 'email':
                if not re.match(r'[\w.-]+@[\w.-]+.\w+', kwargs[attribute]):
                    error = True
                    errors.append(
                        ('email', 'Please enter a valid email address.'))
                else:
                    email = kwargs[attribute]

            elif attribute == 'nethzid':
                nethzid = kwargs[attribute]

            else:
                pass

        if not error:
            if (((username and password and (level & (permission_flags.OVER_NINETHOUSAND\
            | permission_flags.CAN_LOGIN)) > 0)) or name) and (email or nethzid):
                user = User(creation_date=helpers.today(),
                            username=username,
                            password=password.hexdigest(),
                            name=name,
                            level=level,
                            email=email,
                            nethzid=nethzid)
                sqlsession.add(user)
                sqlsession.commit()
                return user.id, None
            else:
                errors.append((
                    'general',
                    'Failed to create user. You need to at least fill a name and (an email and or a nethzid).'
                ))
        return False, errors
Ejemplo n.º 27
0
def archives(request, tag=None):
    return render_to_response(request, 'ladypenh/archives.html',
                              dict(theme_name=helpers.get_theme(helpers.today()),
                                   articles=helpers.get_articles(helpers.today(), tag),
                                   tags=helpers.get_tags()))
Ejemplo n.º 28
0
def about(request):
    return  render_to_response(request, 'ladypenh/about.html',
                               dict(theme_name=helpers.get_theme(helpers.today())))
Ejemplo n.º 29
0
def friends(request):
    friends = helpers.get_friends()
    return  render_to_response(request, 'ladypenh/friends.html',
                               dict(friends=friends,
                                    theme_name=helpers.get_theme(helpers.today())))