コード例 #1
0
ファイル: users.py プロジェクト: CyberIntelMafia/aleph
def add():

    if not current_user.is_admin:
        abort(401)

    form = NewUserForm()

    if form.validate_on_submit():

        user = User(
            login=form.login.data,
            email=form.email.data,
            password = hash_password(form.login.data, form.password.data)
        )

        user.active = form.active.data
        user.account_type = form.account_type.data

        user.locale = form.locale.data
        user.timezone = form.timezone.data

        user.first_name = form.first_name.data
        user.last_name = form.last_name.data

        db.session.add(user)
        db.session.commit()

        flash(gettext(u'User added successfully'))

        return redirect(url_for('users.index'))
    else:
        form.timezone.data = str(get_timezone())
        form.locale.data = str(get_locale())

    return render_template('users/new.html', form=form)
コード例 #2
0
ファイル: __init__.py プロジェクト: keios/PyRfK
def before_request():
    if request.method == 'GET':
        if request.args.get(
                'lang') is not None and request.args.get('lang') != '':
            current_user.locale = request.args.get('lang')
            g.current_locale = request.args.get('lang')

            @after_this_request
            def remember_locale(response):
                response.set_cookie('locale',
                                    current_user.locale,
                                    expires=datetime.datetime.utcnow() +
                                    datetime.timedelta(days=365))
                return response
        if request.args.get('tz') is not None and \
                        request.args.get('tz') in pytz.common_timezones:
            current_user.timezone = request.args.get('tz')
            g.current_timezone = request.args.get('tz')

            @after_this_request
            def remember_timezone(response):
                response.set_cookie('timezone', current_user.timezone)
                return response

    refresh()
    request.current_locale = get_locale()
    request.current_timezone = str(get_timezone())
コード例 #3
0
def add():

    if not current_user.is_admin:
        abort(401)

    form = NewUserForm()

    if form.validate_on_submit():

        user = User(login=form.login.data,
                    email=form.email.data,
                    password=hash_password(form.login.data,
                                           form.password.data))

        user.active = form.active.data
        user.account_type = form.account_type.data

        user.locale = form.locale.data
        user.timezone = form.timezone.data

        user.first_name = form.first_name.data
        user.last_name = form.last_name.data

        db.session.add(user)
        db.session.commit()

        flash(gettext(u'User added successfully'))

        return redirect(url_for('users.index'))
    else:
        form.timezone.data = str(get_timezone())
        form.locale.data = str(get_locale())

    return render_template('users/new.html', form=form)
コード例 #4
0
def show_edit(show):
    if 'begin' in request.form and \
                    'description' in request.form and \
                    'duration' in request.form and \
                    'title' in request.form:
        if int(request.form['duration']) < 30:
            return emit_error(6, 'Duration too short')
        if int(request.form['duration']) > 1440:
            return emit_error(5, 'Duration too long')
        if len(request.form['title']) < 3:
            return emit_error(4, 'Title too short')
        if len(request.form['description']) == 0:
            return emit_error(3, 'Description is empty')
        show = Show.query.get(show)
        if show is None:
            return emit_error(7, 'Whoop, invalid show!')
        if show.get_usershow(current_user) is None:
            return emit_error(8, 'Trying to edit another user\'s show, eh?!')
        begin = to_utc(get_timezone().localize(datetime.utcfromtimestamp(int(request.form['begin']))))
        begin = begin.replace(second=0)
        if begin < now():
            return jsonify({'success': False, 'error': 'You cannot enter a past date!'})
        end = begin + timedelta(minutes=int(request.form['duration']))
        if Show.query.filter(Show.end > begin, Show.begin < end, Show.show != show.show).count() > 0:
            return emit_error(1, 'Your show collides with other shows')
        show.begin = begin
        show.end = end
        _set_show_info(show, request.form)
        rfk.database.session.commit()
    else:
        return emit_error(0, 'Wait a second, are you trying to trick me again?!')
    return jsonify({'success': True, 'data': None})
コード例 #5
0
ファイル: site.py プロジェクト: AlexCherkashin/PyRfK
def show_edit(show):
    if 'begin' in request.form and \
                    'description' in request.form and \
                    'duration' in request.form and \
                    'title' in request.form:
        if int(request.form['duration']) < 30:
            return emit_error(6, 'Duration too short')
        if int(request.form['duration']) > 1440:
            return emit_error(5, 'Duration too long')
        if len(request.form['title']) < 3:
            return emit_error(4, 'Title too short')
        if len(request.form['description']) == 0:
            return emit_error(3, 'Description is empty')
        show = Show.query.get(show)
        if show is None:
            return emit_error(7, 'Whoop, invalid show!')
        if show.get_usershow(current_user) is None:
            return emit_error(8, 'Trying to edit another user\'s show, eh?!')
        begin = to_utc(get_timezone().localize(datetime.utcfromtimestamp(int(request.form['begin']))))
        begin = begin.replace(second=0)
        if begin < now():
            return jsonify({'success': False, 'error': 'You cannot enter a past date!'})
        end = begin + timedelta(minutes=int(request.form['duration']))
        if Show.query.filter(Show.end > begin, Show.begin < end, Show.show != show.show).count() > 0:
            return emit_error(1, 'Your show collides with other shows')
        show.begin = begin
        show.end = end
        _set_show_info(show, request.form)
        rfk.database.session.commit()
    else:
        return emit_error(0, 'Wait a second, are you trying to trick me again?!')
    return jsonify({'success': True, 'data': None})
コード例 #6
0
ファイル: app.py プロジェクト: vbatoufflet/plume
def settings(page=None):
    if not session.get("uid"):
        return redirect(url_for("signin", next=get_path(request)))

    if page not in ("identity", "regional", "password"):
        return redirect(url_for("settings", page="identity"))

    if request.method == "POST":
        if request.form.get("validate"):
            if page == "password":
                backend = UserBackend()

                if not backend.authenticate(session.get("login"), request.form.get("password-current")):
                    flash(_("Current password is invalid."), "error")
                elif request.form.get("password-new") != request.form.get("password-repeat"):
                    flash(_("Passwords don't match."), "error")
                else:
                    try:
                        backend.set(modify=True, login=session.get("login"), password=request.form.get("password-new"))
                        flash(_("Password successfuly changed."), "info")
                    except PasswordTooShort:
                        flash(
                            _(
                                "Password is too short. Must be a least %(length)d characters long.",
                                length=PASSWORD_MIN_LENGTH,
                            ),
                            "error",
                        )
            else:
                settings = dict((x, request.form.get(x)) for x in SETTINGS_LIST if x in request.form)

                if settings:
                    user = UserBackend().set(modify=True, login=session.get("login"), **settings)

                    session.update(
                        {
                            "name": user.fullname,
                            "avatar": "//gravatar.com/avatar/%s" % hashlib.md5(user.email.lower()).hexdigest(),
                        }
                    )

                    if "locale" in settings:
                        g.user.locale = settings.get("locale")

                    flash(_("Settings successfuly saved."), "info")

        return redirect(url_for("settings", page=page))

    locales = [(x.language, x.display_name.capitalize()) for x in app.babel_instance.list_translations()]

    return render_template(
        "settings.html",
        page=page,
        locales=locales,
        timezones=common_timezones,
        current_locale=get_locale().language,
        current_timezone=get_timezone().zone,
    )
コード例 #7
0
ファイル: users.py プロジェクト: CyberIntelMafia/aleph
def register():

    if not app.config.get('ALLOW_REGISTRATIONS'):
        abort(404)

    form = NewUserForm()

    if form.validate_on_submit():

        try:
            exists = User.query.filter(User.email == form.email.data).first()

            if exists:
                flash(gettext('Email address already registered'))
            else:
                user = User(
                    login=form.login.data,
                    email=form.email.data,
                    password = hash_password(form.login.data, form.password.data),
                    active = ACCOUNT_DISABLED
                )

                user.first_name = form.first_name.data
                user.last_name = form.last_name.data

                user.locale = str(get_locale())
                user.timezone = str(get_timezone())

                db.session.add(user)
                db.session.commit()

                # Send email
                sent = send_email(
                    gettext('Welcome to %(appname)s', appname = app.config.get('APP_TITLE')),
                    app.config.get('MAIL_SENDER'),
                    [form.email.data],
                    render_template('users/mail_register.txt', user=user),
                    render_template('users/mail_register.html', user=user),
                )

                if sent:
                    flash(gettext('Account created successfully. Please check your email for instructions on activating your account'))
                else:
                    flash(gettext('Account created successfully but there were server-side errors while sending the email activation code. Your account needs to be manually activated.'))

                return redirect(url_for('users.login'))

        except OperationalError:
            if app.config.get('DEBUG'):
                flash(gettext('Error creating user. Database not set'))
                return redirect(url_for('users.login'))
            else:
                abort(500)

    return render_template('users/register.html', form=form, hide_sidebar=True, hide_header=True, class_body='bg-black', class_html ='bg-black')
コード例 #8
0
def show_add():
    try:
        if 'begin' in request.form and \
                        'description' in request.form and \
                        'duration' in request.form and \
                        'title' in request.form:
            if int(request.form['duration']) < 30:
                return emit_error(6, 'Duration too short')
            if int(request.form['duration']) > 1440:
                return emit_error(5, 'Duration too long')
            if len(request.form['title']) < 3:
                return emit_error(4, 'Title too short')
            if len(request.form['description']) == 0:
                return emit_error(3, 'Description is empty')

            begin = to_utc(get_timezone().localize(
                datetime.utcfromtimestamp(int(request.form['begin']))))
            begin = begin.replace(second=0)
            end = begin + timedelta(minutes=int(request.form['duration']))
            if begin < now():
                return emit_error(2, 'You cannot enter a past date!')
            if Show.query.filter(Show.end > begin,
                                 Show.begin < end).count() > 0:
                return emit_error(1, 'Your show collides with other shows')
            show = Show(begin=begin,
                        end=end,
                        name=request.form['title'],
                        description=request.form['description'],
                        flags=Show.FLAGS.PLANNED)
            rfk.database.session.add(show)
            show.add_user(current_user)
            _set_show_info(show, request.form)
            rfk.database.session.commit()
            return jsonify({'success': True, 'data': None})
        else:
            return emit_error(
                0, 'Wait a second, are you trying to trick me again?!')
    except Exception as e:
        from rfk.site import app

        app.logger.error(e)
        return emit_error(0, 'something went horribly wrong')
コード例 #9
0
ファイル: fields.py プロジェクト: mmariani/abilian-core
  def process_formdata(self, valuelist):
    if valuelist:
      date_str = ' '.join(valuelist)
      locale = get_locale()
      date_fmt = locale.date_formats['short']
      date_fmt = babel2datetime(date_fmt)
      date_fmt = date_fmt.replace('%B', '%m')\
                         .replace('%b', '%m')  # force numerical months

      time_fmt = locale.time_formats['short']
      time_fmt = babel2datetime(time_fmt)

      datetime_fmt = u'{} | {}'.format(date_fmt, time_fmt)
      try:
        self.data = datetime.datetime.strptime(date_str, datetime_fmt)
        if not self.data.tzinfo:
          self.data = utc_dt(get_timezone().localize(self.data))
      except ValueError:
        self.data = None
        raise ValueError(self.gettext('Not a valid datetime value'))
コード例 #10
0
ファイル: __init__.py プロジェクト: alphabernd/PyRfK
def before_request():
    if request.method == 'GET': 
        if request.args.get('lang') is not None and request.args.get('lang') != '':
            current_user.locale = request.args.get('lang')
            g.current_locale = request.args.get('lang')
            @after_this_request
            def remember_locale(response):
                response.set_cookie('locale', current_user.locale, expires=datetime.datetime.utcnow()+datetime.timedelta(days=365))
                return response
        if request.args.get('tz') is not None and\
           request.args.get('tz') in pytz.common_timezones:
            current_user.timezone = request.args.get('tz')
            g.current_timezone = request.args.get('tz')
            @after_this_request
            def remember_timezone(response):
                response.set_cookie('timezone', current_user.timezone)
                return response
    refresh()
    request.current_locale = get_locale()
    request.current_timezone = str(get_timezone())
コード例 #11
0
ファイル: site.py プロジェクト: AlexCherkashin/PyRfK
def show_add():
    try:
        if 'begin' in request.form and \
                        'description' in request.form and \
                        'duration' in request.form and \
                        'title' in request.form:
            if int(request.form['duration']) < 30:
                return emit_error(6, 'Duration too short')
            if int(request.form['duration']) > 1440:
                return emit_error(5, 'Duration too long')
            if len(request.form['title']) < 3:
                return emit_error(4, 'Title too short')
            if len(request.form['description']) == 0:
                return emit_error(3, 'Description is empty')

            begin = to_utc(get_timezone().localize(datetime.utcfromtimestamp(int(request.form['begin']))))
            begin = begin.replace(second=0)
            end = begin + timedelta(minutes=int(request.form['duration']))
            if begin < now():
                return emit_error(2, 'You cannot enter a past date!')
            if Show.query.filter(Show.end > begin, Show.begin < end).count() > 0:
                return emit_error(1, 'Your show collides with other shows')
            show = Show(begin=begin,
                        end=end,
                        name=request.form['title'],
                        description=request.form['description'],
                        flags=Show.FLAGS.PLANNED)
            rfk.database.session.add(show)
            show.add_user(current_user)
            _set_show_info(show, request.form)
            rfk.database.session.commit()
            return jsonify({'success': True, 'data': None})
        else:
            return emit_error(0, 'Wait a second, are you trying to trick me again?!')
    except Exception as e:
        from rfk.site import app

        app.logger.error(e)
        return emit_error(0, 'something went horribly wrong')
コード例 #12
0
def register():

    if not app.config.get('ALLOW_REGISTRATIONS'):
        abort(404)

    form = NewUserForm()

    if form.validate_on_submit():

        try:
            exists = User.query.filter(User.email == form.email.data).first()

            if exists:
                flash(gettext('Email address already registered'))
            else:
                user = User(login=form.login.data,
                            email=form.email.data,
                            password=hash_password(form.login.data,
                                                   form.password.data),
                            active=ACCOUNT_DISABLED)

                user.first_name = form.first_name.data
                user.last_name = form.last_name.data

                user.locale = str(get_locale())
                user.timezone = str(get_timezone())

                db.session.add(user)
                db.session.commit()

                # Send email
                sent = send_email(
                    gettext('Welcome to %(appname)s',
                            appname=app.config.get('APP_TITLE')),
                    app.config.get('MAIL_SENDER'),
                    [form.email.data],
                    render_template('users/mail_register.txt', user=user),
                    render_template('users/mail_register.html', user=user),
                )

                if sent:
                    flash(
                        gettext(
                            'Account created successfully. Please check your email for instructions on activating your account'
                        ))
                else:
                    flash(
                        gettext(
                            'Account created successfully but there were server-side errors while sending the email activation code. Your account needs to be manually activated.'
                        ))

                return redirect(url_for('users.login'))

        except OperationalError:
            if app.config.get('DEBUG'):
                flash(gettext('Error creating user. Database not set'))
                return redirect(url_for('users.login'))
            else:
                abort(500)

    return render_template('users/register.html',
                           form=form,
                           hide_sidebar=True,
                           hide_header=True,
                           class_body='bg-black',
                           class_html='bg-black')