예제 #1
0
class TaskRedundancyForm(Form):
    n_answers = IntegerField(lazy_gettext('Redundancy'),
                             [validators.Required(),
                              validators.NumberRange(
                                  min=1, max=1000,
                                  message=lazy_gettext('Number of answers should be a \
                                                       value between 1 and 1,000'))])
예제 #2
0
    def respond_csv(ty):
        # Export Task(/Runs) to CSV
        types = {
            "task": (
                model.Task, handle_task,
                (lambda x: True),
                lazy_gettext(
                    "Oops, the application does not have tasks to \
                           export, if you are the owner add some tasks")),
            "task_run": (
                model.TaskRun, handle_task_run,
                (lambda x: type(x.info) == dict),
                lazy_gettext(
                    "Oops, there are no Task Runs yet to export, invite \
                           some users to participate"))}
        try:
            table, handle_row, test, msg = types[ty]
        except KeyError:
            return abort(404)

        out = StringIO()
        writer = UnicodeWriter(out)
        t = db.session.query(table)\
            .filter_by(app_id=app.id)\
            .first()
        if t is not None:
            if test(t):
                writer.writerow(t.info.keys())

            return Response(get_csv(out, writer, table, handle_row),
                            mimetype='text/csv')
        else:
            flash(msg, 'info')
            return respond()
예제 #3
0
파일: forms.py 프로젝트: yeahlol/gifpad
class Regifform(Form):
    board = SelectField(
        lazy_gettext(u"Choose a Board:"),
        validators=[Required(lazy_gettext(u"Enter boardname"))],
        coerce=int)
    description = TextAreaField(
        lazy_gettext(u"Description(optional):"),
        validators=[
            Optional(),
            Length(min=0,
                   max=200,
                   message=lazy_gettext(
                       u"Field must be between 0 and 200 characters long"))
        ])

    def validate_tags(self, tags):
        if len(tags) > 5 or len(tags) == 0:
            self.errors["tag_items"] = lazy_gettext(
                u"Please don't use more than 6 tags"
            ) if len(tags) > 5 else lazy_gettext(u"Enter tag")
            return False
        else:
            for tag in tags:  # 単一のタグが21文字以上で構成されている場合はerror分岐
                if len(tag) == 0 or len(tag) >= 21:
                    self.errors["tag_length"] = lazy_gettext(
                        u"Tag must be between 1 and 20 characters long")
                    return False
            for tag in tags:  # 単一のタグがひらカナ漢字, 半角英字, 半角全角数字アンダースコアハイフン以外で構成されている場合はerror分岐
                if not re.compile(u"^([a-zA-Z0-9_-]|[0-9ぁ-ん_ー]|[ァ-ヴ]|[一-龠])+$"
                                  ).search(tag):
                    self.errors["tag_re"] = lazy_gettext(
                        u"Letters and numbers only")
                    return False
        return True
예제 #4
0
파일: account.py 프로젝트: epiraces/pybossa
def reset_password():
    key = request.args.get('key')
    if key is None:
        abort(403)
    userdict = {}
    try:
        userdict = signer.loads(key, max_age=3600, salt='password-reset')
    except BadData:
        abort(403)
    username = userdict.get('user')
    if not username or not userdict.get('password'):
        abort(403)
    user = model.User.query.filter_by(name=username).first_or_404()
    if user.passwd_hash != userdict.get('password'):
        abort(403)
    form = ChangePasswordForm(request.form)
    if form.validate_on_submit():
        user.set_password(form.new_password.data)
        db.session.add(user)
        db.session.commit()
        login_user(user)
        flash(lazy_gettext('You reset your password successfully!'), 'success')
        return redirect(url_for('.profile'))
    if request.method == 'POST' and not form.validate():
        flash(lazy_gettext('Please correct the errors'), 'error')
    return render_template('/account/password_reset.html', form=form)
예제 #5
0
def task_scheduler(short_name):
    app = app_by_shortname(short_name)
    title = app_title(app, lazy_gettext('Scheduler'))
    form = TaskSchedulerForm()
    try:
        require.app.read(app)
        require.app.update(app)
        if request.method == 'GET':
            if app.info.get('sched'):
                for s in form.sched.choices:
                    if app.info['sched'] == s[0]:
                        form.sched.data = s[0]
                        break
            return render_template('/applications/task_scheduler.html',
                                   title=title,
                                   form=form,
                                   app=app)
        elif request.method == 'POST' and form.validate():
            if form.sched.data:
                app.info['sched'] = form.sched.data
            cached_apps.reset()
            db.session.add(app)
            db.session.commit()
            msg = lazy_gettext("Application Task Scheduler updated!")
            flash(msg, 'success')
            return redirect(url_for('.tasks', short_name=app.short_name))
        else:
            flash(lazy_gettext('Please correct the errors'), 'error')
            return render_template('/applications/task_scheduler.html',
                                   title=title,
                                   form=form,
                                   app=app)
    except:
        return abort(403)
예제 #6
0
def task_n_answers(short_name):
    app = app_by_shortname(short_name)
    title = app_title(app, lazy_gettext('Redundancy'))
    form = TaskRedundancyForm()
    try:
        require.app.read(app)
        require.app.update(app)
        if request.method == 'GET':
            return render_template('/applications/task_n_answers.html',
                                   title=title,
                                   form=form,
                                   app=app)
        elif request.method == 'POST' and form.validate():
            sql = text('''UPDATE task SET n_answers=:n_answers WHERE app_id=:app_id''')
            db.engine.execute(sql, n_answers=form.n_answers.data, app_id=app.id)
            msg = lazy_gettext('Redundancy of Tasks updated!')
            flash(msg, 'success')
            return redirect(url_for('.tasks', short_name=app.short_name))
        else:
            flash(lazy_gettext('Please correct the errors'), 'error')
            return render_template('/applications/task_n_answers.html',
                                   title=title,
                                   form=form,
                                   app=app)
    except:
        return abort(403)
예제 #7
0
def task_n_answers(short_name):
    app = app_by_shortname(short_name)
    title = app_title(app, lazy_gettext('Redundancy'))
    form = TaskRedundancyForm()
    try:
        require.app.read(app)
        require.app.update(app)
        if request.method == 'GET':
            return render_template('/applications/task_n_answers.html',
                                   title=title,
                                   form=form,
                                   app=app)
        elif request.method == 'POST' and form.validate():
            sql = text('''UPDATE task SET n_answers=:n_answers WHERE app_id=:app_id''')
            db.engine.execute(sql, n_answers=form.n_answers.data, app_id=app.id)
            msg = lazy_gettext('Redundancy of Tasks updated!')
            flash(msg, 'success')
            return redirect(url_for('.tasks', short_name=app.short_name))
        else:
            flash(lazy_gettext('Please correct the errors'), 'error')
            return render_template('/applications/task_n_answers.html',
                                   title=title,
                                   form=form,
                                   app=app)
    except:
        return abort(403)
예제 #8
0
파일: admin.py 프로젝트: jikimlucas/pybossa
def del_category(id):
    """Deletes a category"""
    try:
        category = db.session.query(model.Category).get(id)
        if category:
            if len(cached_cat.get_all()) > 1:
                require.category.delete(category)
                if request.method == 'GET':
                    return render_template('admin/del_category.html',
                                           title=lazy_gettext('Delete Category'),
                                           category=category)
                if request.method == 'POST':
                    db.session.delete(category)
                    db.session.commit()
                    msg = lazy_gettext("Category deleted")
                    flash(msg, 'success')
                    cached_cat.reset()
                    return redirect(url_for(".categories"))
            else:
                msg = lazy_gettext('Sorry, it is not possible to delete the only \
                                   available category. You can modify it, click the \
                                   edit button')
                flash(msg, 'warning')
                return redirect(url_for('.categories'))
        else:
            return abort(404)
    except HTTPException:
        return abort(403)
    except Exception as e:
        current_app.logger.error(e)
        return abort(500)
예제 #9
0
def reset_password():
    key = request.args.get('key')
    if key is None:
        abort(403)
    userdict = {}
    try:
        userdict = signer.loads(key, max_age=3600, salt='password-reset')
    except BadData:
        abort(403)
    username = userdict.get('user')
    if not username or not userdict.get('password'):
        abort(403)
    user = model.User.query.filter_by(name=username).first_or_404()
    if user.passwd_hash != userdict.get('password'):
        abort(403)
    form = ChangePasswordForm(request.form)
    if form.validate_on_submit():
        user.set_password(form.new_password.data)
        db.session.add(user)
        db.session.commit()
        login_user(user)
        flash(lazy_gettext('You reset your password successfully!'), 'success')
        return redirect(url_for('.profile'))
    if request.method == 'POST' and not form.validate():
        flash(lazy_gettext('Please correct the errors'), 'error')
    return render_template('/account/password_reset.html', form=form)
예제 #10
0
class BulkTaskEpiCollectPlusImportForm(BulkTaskImportForm):
    msg_required = lazy_gettext("You must provide an EpiCollect Plus "
                                "project name")
    msg_form_required = lazy_gettext("You must provide a Form name "
                                     "for the project")
    epicollect_project = TextField(lazy_gettext('Project Name'),
                                   [validators.Required(message=msg_required)])
    epicollect_form = TextField(lazy_gettext('Form name'),
                                [validators.Required(message=msg_required)])
    template_id = "epicollect"
    form_id = "epiform"
    form_detector = "epicollect_project"

    def import_epicollect_tasks(self, data):
        for d in data:
            yield {"info": d}

    def get_data_url(self, form):
        return 'http://plus.epicollect.net/%s/%s.json' % \
            (form.epicollect_project.data, form.epicollect_form.data)

    def get_epicollect_data_from_request(self, r):
        if r.status_code == 403:
            msg = "Oops! It looks like you don't have permission to access" \
                " the EpiCollect Plus project"
            raise BulkImportException(lazy_gettext(msg), 'error')
        if not 'application/json' in r.headers['content-type']:
            msg = "Oops! That project and form do not look like the right one."
            raise BulkImportException(lazy_gettext(msg), 'error')
        return self.import_epicollect_tasks(json.loads(r.text))

    def tasks(self, form):
        dataurl = self.get_data_url(form)
        r = requests.get(dataurl)
        return self.get_epicollect_data_from_request(r)
예제 #11
0
def update_profile():
    form = UpdateProfileForm(obj=current_user)
    form.set_locales(current_app.config['LOCALES'])
    form.populate_obj(current_user)
    if request.method == 'GET':
        title_msg = "Update your profile: %s" % current_user.fullname
        return render_template('account/update.html',
                               title=title_msg,
                               form=form)
    else:
        form = UpdateProfileForm(request.form)
        form.set_locales(current_app.config['LOCALES'])
        if form.validate():
            new_profile = model.User(id=form.id.data,
                                     fullname=form.fullname.data,
                                     name=form.name.data,
                                     email_addr=form.email_addr.data,
                                     locale=form.locale.data,
                                     ckan_api=form.ckan_api.data)
            db.session.query(model.User)\
              .filter(model.User.id == current_user.id)\
              .first()
            db.session.merge(new_profile)
            db.session.commit()
            flash(lazy_gettext('Your profile has been updated!'), 'success')
            return redirect(url_for('.profile'))
        else:
            flash(lazy_gettext('Please correct the errors'), 'error')
            title_msg = 'Update your profile: %s' % current_user.fullname
            return render_template('/account/update.html',
                                   form=form,
                                   title=title_msg)
예제 #12
0
    def respond_csv(ty):
        # Export Task(/Runs) to CSV
        types = {
            "task":
            (model.Task, handle_task, (lambda x: True),
             lazy_gettext("Oops, the application does not have tasks to \
                           export, if you are the owner add some tasks")),
            "task_run":
            (model.TaskRun, handle_task_run, (lambda x: type(x.info) == dict),
             lazy_gettext("Oops, there are no Task Runs yet to export, invite \
                           some users to participate"))
        }
        try:
            table, handle_row, test, msg = types[ty]
        except KeyError:
            return abort(404)

        out = StringIO()
        writer = UnicodeWriter(out)
        t = db.session.query(table)\
            .filter_by(app_id=app.id)\
            .first()
        if t is not None:
            if test(t):
                writer.writerow(t.info.keys())

            return Response(get_csv(out, writer, table, handle_row),
                            mimetype='text/csv')
        else:
            flash(msg, 'info')
            return render_template('/applications/export.html',
                                   title=title,
                                   app=app)
예제 #13
0
파일: account.py 프로젝트: epiraces/pybossa
def update_profile():
    form = UpdateProfileForm(obj=current_user)
    form.set_locales(current_app.config['LOCALES'])
    form.populate_obj(current_user)
    if request.method == 'GET':
        title_msg = "Update your profile: %s" % current_user.fullname
        return render_template('account/update.html',
                               title=title_msg,
                               form=form)
    else:
        form = UpdateProfileForm(request.form)
        form.set_locales(current_app.config['LOCALES'])
        if form.validate():
            new_profile = model.User(id=form.id.data,
                                     fullname=form.fullname.data,
                                     name=form.name.data,
                                     email_addr=form.email_addr.data,
                                     locale=form.locale.data,
                                     ckan_api=form.ckan_api.data)
            db.session.query(model.User)\
              .filter(model.User.id == current_user.id)\
              .first()
            db.session.merge(new_profile)
            db.session.commit()
            flash(lazy_gettext('Your profile has been updated!'), 'success')
            return redirect(url_for('.profile'))
        else:
            flash(lazy_gettext('Please correct the errors'), 'error')
            title_msg = 'Update your profile: %s' % current_user.fullname
            return render_template('/account/update.html', form=form,
                                   title=title_msg)
예제 #14
0
파일: admin.py 프로젝트: jikimlucas/pybossa
def users(user_id=None):
    """Manage users of PyBossa"""
    try:
        form = SearchForm(request.form)
        users = db.session.query(model.User)\
                  .filter(model.User.admin == True)\
                  .filter(model.User.id != current_user.id)\
                  .all()

        if request.method == 'POST' and form.user.data:
            query = '%' + form.user.data.lower() + '%'
            found = db.session.query(model.User)\
                      .filter(or_(func.lower(model.User.name).like(query),
                                  func.lower(model.User.fullname).like(query)))\
                      .filter(model.User.id != current_user.id)\
                      .all()
            require.user.update(found)
            if not found:
                flash("<strong>Ooops!</strong> We didn't find a user "
                      "matching your query: <strong>%s</strong>" % form.user.data)
            return render_template('/admin/users.html', found=found, users=users,
                                   title=lazy_gettext("Manage Admin Users"),
                                   form=form)

        return render_template('/admin/users.html', found=[], users=users,
                               title=lazy_gettext("Manage Admin Users"), form=form)
    except HTTPException:
        return abort(403)
    except Exception as e:
        current_app.logger.error(e)
        return abort(500)
예제 #15
0
class ResetPasswordForm(Form):
    err_msg = lazy_gettext("Password cannot be empty")
    err_msg_2 = lazy_gettext("Passwords must match")
    new_password = PasswordField(lazy_gettext('New Password'), [
        validators.Required(err_msg),
        validators.EqualTo('confirm', err_msg_2)
    ])
    confirm = PasswordField(lazy_gettext('Repeat Password'))
예제 #16
0
class ImportVectorEdit(Form):
    file_name = SelectField(lazy_gettext('file name'), validators=[Required()])
    srs = SRSSelectField(lazy_gettext('srs'),
                         validators=[Required()],
                         default='EPSG:25832')
    layers = SelectField(lazy_gettext('select existing layer'),
                         validators=[Optional()])
    name = TextField(lazy_gettext('new layer'), validators=[Optional()])
예제 #17
0
파일: admin.py 프로젝트: jikimlucas/pybossa
class CategoryForm(Form):
    id = IntegerField(label=None, widget=HiddenInput())
    name = TextField(lazy_gettext('Name'),
                     [validators.Required(),
                      pb_validator.Unique(db.session, model.Category, model.Category.name,
                                          message="Name is already taken.")])
    description = TextField(lazy_gettext('Description'),
                            [validators.Required()])
예제 #18
0
class TaskSchedulerForm(Form):
    sched = SelectField(
        lazy_gettext('Task Scheduler'),
        choices=[('default', lazy_gettext('Default')),
                 ('breadth_first', lazy_gettext('Breadth First')),
                 ('depth_first', lazy_gettext('Depth First')),
                 ('random', lazy_gettext('Random'))],
    )
예제 #19
0
파일: forms.py 프로젝트: kaiCu/gbi-client
class ImportProjectEdit(ProjectEdit):
    start_level = SelectField(lazy_gettext('start level'), coerce=int)
    end_level = SelectField(lazy_gettext('end level'), coerce=int)
    raster_source = QuerySelectField(lazy_gettext('raster_source'),
                                     query_factory=get_external_wmts_source,
                                     get_label='title')
    update_tiles = BooleanField(lazy_gettext('update_tiles'))
    coverage = HiddenField()
    download_size = HiddenField()
예제 #20
0
 def get_epicollect_data_from_request(self, r):
     if r.status_code == 403:
         msg = "Oops! It looks like you don't have permission to access" \
             " the EpiCollect Plus project"
         raise BulkImportException(lazy_gettext(msg), 'error')
     if not 'application/json' in r.headers['content-type']:
         msg = "Oops! That project and form do not look like the right one."
         raise BulkImportException(lazy_gettext(msg), 'error')
     return self.import_epicollect_tasks(json.loads(r.text))
예제 #21
0
class LoginForm(Form):
    email = TextField(
        lazy_gettext('E-mail'),
        [validators.Required(message=lazy_gettext("The e-mail is required"))])

    password = PasswordField(lazy_gettext('Password'), [
        validators.Required(
            message=lazy_gettext("You must provide a password"))
    ])
예제 #22
0
 def get_epicollect_data_from_request(self, r):
     if r.status_code == 403:
         msg = "Oops! It looks like you don't have permission to access" \
             " the EpiCollect Plus project"
         raise BulkImportException(lazy_gettext(msg), 'error')
     if not 'application/json' in r.headers['content-type']:
         msg = "Oops! That project and form do not look like the right one."
         raise BulkImportException(lazy_gettext(msg), 'error')
     return self.import_epicollect_tasks(json.loads(r.text))
예제 #23
0
파일: account.py 프로젝트: epiraces/pybossa
 def set_locales(self, locales):
     """Fill the locale.choices"""
     choices = []
     for locale in locales:
         if locale == 'en':
             lang = lazy_gettext("English")
         if locale == 'es':
             lang = lazy_gettext("Spanish")
         choices.append((locale, lang))
     self.locale.choices = choices
예제 #24
0
class GMLUploadForm(Form):
    upload_file = FileField(lazy_gettext('Choose gml'),
                            validators=[Required()])
    srs = SRSSelectField(label=lazy_gettext('srs'),
                         validators=[Required()],
                         default='EPSG:25832')

    def validate_upload_file(form, field):
        if field.data and re.match('.*\.xml', field.data.filename) is None:
            raise ValidationError(lazy_gettext('only xml files allowed'))
예제 #25
0
 def set_locales(self, locales):
     """Fill the locale.choices"""
     choices = []
     for locale in locales:
         if locale == 'en':
             lang = lazy_gettext("English")
         if locale == 'es':
             lang = lazy_gettext("Spanish")
         choices.append((locale, lang))
     self.locale.choices = choices
예제 #26
0
파일: forms.py 프로젝트: yeahlol/gifpad
class ResetPwform(Form):
    newpassword = PasswordField(
        lazy_gettext(u'New Password'),
        validators=[
            Required(lazy_gettext(u'Enter New Password')),
            Length(min=8,
                   max=30,
                   message=lazy_gettext(
                       u"Field must be between 8 and 30 characters long")),
            Regexp("^[a-zA-Z0-9]+$",
                   message=lazy_gettext(u"Letters and numbers only")),
            EqualTo('verifypassword',
                    message=lazy_gettext(u"Passwords must match"))
        ])

    verifypassword = PasswordField(
        lazy_gettext(u'Verify Password'),
        validators=[
            Required(lazy_gettext(u'Enter New Password')),
            Length(min=8,
                   max=30,
                   message=lazy_gettext(
                       u"Field must be between 8 and 30 characters long")),
            Regexp("^[a-zA-Z0-9]+$",
                   message=lazy_gettext(u"Letters and numbers only"))
        ])
예제 #27
0
def task_presenter(short_name, task_id):
    app = app_by_shortname(short_name)
    task = Task.query.filter_by(id=task_id).first_or_404()

    if current_user.is_anonymous():
        if not app.allow_anonymous_contributors:
            msg = ("Oops! You have to sign in to participate in "
                   "<strong>%s</strong>"
                   "application" % app.name)
            flash(lazy_gettext(msg), 'warning')
            return redirect(url_for('account.signin',
                                    next=url_for('.presenter',
                                                 short_name=app.short_name)))
        else:
            msg_1 = lazy_gettext(
                "Ooops! You are an anonymous user and will not "
                "get any credit"
                " for your contributions.")
            next_url = url_for(
                'app.task_presenter',
                short_name=short_name,
                task_id=task_id)
            url = url_for(
                'account.signin',
                next=next_url)
            flash(msg_1 + "<a href=\"" + url + "\">Sign in now!</a>", "warning")

    title = app_title(app, "Contribute")
    template_args = {"app": app, "title": title}

    def respond(tmpl):
        return render_template(tmpl, **template_args)

    if not (task.app_id == app.id):
        return respond('/applications/task/wrong.html')

    #return render_template('/applications/presenter.html', app = app)
    # Check if the user has submitted a task before

    tr_search = db.session.query(model.TaskRun)\
                  .filter(model.TaskRun.task_id == task_id)\
                  .filter(model.TaskRun.app_id == app.id)

    if current_user.is_anonymous():
        remote_addr = request.remote_addr or "127.0.0.1"
        tr = tr_search.filter(model.TaskRun.user_ip == remote_addr)
    else:
        tr = tr_search.filter(model.TaskRun.user_id == current_user.id)

    tr_first = tr.first()
    if tr_first is None:
        return respond('/applications/presenter.html')
    else:
        return respond('/applications/task/done.html')
예제 #28
0
def task_presenter(short_name, task_id):
    app = app_by_shortname(short_name)
    task = Task.query.filter_by(id=task_id).first_or_404()

    if current_user.is_anonymous():
        if not app.allow_anonymous_contributors:
            msg = ("Oops! You have to sign in to participate in "
                   "<strong>%s</strong>"
                   "application" % app.name)
            flash(lazy_gettext(msg), 'warning')
            return redirect(url_for('account.signin',
                                    next=url_for('.presenter',
                                                 short_name=app.short_name)))
        else:
            msg_1 = lazy_gettext(
                "Ooops! You are an anonymous user and will not "
                "get any credit"
                " for your contributions.")
            next_url = url_for(
                'app.task_presenter',
                short_name=short_name,
                task_id=task_id)
            url = url_for(
                'account.signin',
                next=next_url)
            flash(msg_1 + "<a href=\"" + url + "\">Sign in now!</a>", "warning")

    title = app_title(app, "Contribute")
    template_args = {"app": app, "title": title}

    def respond(tmpl):
        return render_template(tmpl, **template_args)

    if not (task.app_id == app.id):
        return respond('/applications/task/wrong.html')

    #return render_template('/applications/presenter.html', app = app)
    # Check if the user has submitted a task before

    tr_search = db.session.query(model.TaskRun)\
                  .filter(model.TaskRun.task_id == task_id)\
                  .filter(model.TaskRun.app_id == app.id)

    if current_user.is_anonymous():
        remote_addr = request.remote_addr or "127.0.0.1"
        tr = tr_search.filter(model.TaskRun.user_ip == remote_addr)
    else:
        tr = tr_search.filter(model.TaskRun.user_id == current_user.id)

    tr_first = tr.first()
    if tr_first is None:
        return respond('/applications/presenter.html')
    else:
        return respond('/applications/task/done.html')
예제 #29
0
파일: forms.py 프로젝트: yeahlol/gifpad
class Passwordform(Form):
    username = TextField(
        lazy_gettext(u'Username:'******'Enter Username')),
            Length(min=2,
                   max=25,
                   message=lazy_gettext(
                       u"Field must be between 2 and 25 characters long")),
            Regexp("^[a-zA-Z0-9_]+$",
                   message=lazy_gettext(
                       u"Letters and numbers and underscore only"))
        ])
예제 #30
0
def forgot_password():
    form = ForgotPasswordForm(request.form)
    if form.validate_on_submit():
        user = model.User.query\
                    .filter_by(email_addr=form.email_addr.data)\
                    .first()
        if user and user.email_addr:
            msg = Message(subject='Account Recovery',
                          recipients=[user.email_addr])
            if user.twitter_user_id:
                msg.body = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user,
                    account_name='Twitter')
            elif user.facebook_user_id:
                msg.body = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user,
                    account_name='Facebook')
            elif user.google_user_id:
                msg.body = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user,
                    account_name='Google')
            else:
                userdict = {'user': user.name, 'password': user.passwd_hash}
                key = signer.dumps(userdict, salt='password-reset')
                recovery_url = url_for('.reset_password',
                                       key=key,
                                       _external=True)
                msg.body = render_template('/account/email/forgot_password.md',
                                           user=user,
                                           recovery_url=recovery_url)
            msg.html = markdown(msg.body)
            mail.send(msg)
            flash(
                lazy_gettext(
                    "We've send you email with account recovery instructions!"
                ), 'success')
        else:
            flash(
                lazy_gettext(
                    "We don't have this email in our records. You may have"
                    " signed up with a different email or used Twitter, "
                    "Facebook, or Google to sign-in"), 'error')
    if request.method == 'POST' and not form.validate():
        flash(
            lazy_gettext(
                'Something went wrong, please correct the errors on the '
                'form'), 'error')
    return render_template('/account/password_forgot.html', form=form)
예제 #31
0
    def get_csv_data_from_request(self, r):
        if r.status_code == 403:
            msg = "Oops! It looks like you don't have permission to access" \
                " that file"
            raise BulkImportException(lazy_gettext(msg), 'error')
        if ((not 'text/plain' in r.headers['content-type']) and
            (not 'text/csv' in r.headers['content-type'])):
            msg = lazy_gettext(
                "Oops! That file doesn't look like the right file.")
            raise BulkImportException(msg, 'error')

        csvcontent = StringIO(r.text)
        csvreader = unicode_csv_reader(csvcontent)
        return self.import_csv_tasks(csvreader)
예제 #32
0
    def get_csv_data_from_request(self, r):
        if r.status_code == 403:
            msg = "Oops! It looks like you don't have permission to access" \
                " that file"
            raise BulkImportException(lazy_gettext(msg), 'error')
        if ((not 'text/plain' in r.headers['content-type'])
                and (not 'text/csv' in r.headers['content-type'])):
            msg = lazy_gettext(
                "Oops! That file doesn't look like the right file.")
            raise BulkImportException(msg, 'error')

        csvcontent = StringIO(r.text)
        csvreader = unicode_csv_reader(csvcontent)
        return self.import_csv_tasks(csvreader)
예제 #33
0
def new():
    if not require.app.create():
        abort(403)
    form = AppForm(request.form)
    categories = db.session.query(model.Category).all()
    form.category_id.choices = [(c.id, c.name) for c in categories]

    def respond(errors):
        return render_template('applications/new.html',
                               title=lazy_gettext("Create an Application"),
                               form=form,
                               errors=errors)

    if request.method != 'POST':
        return respond(False)

    if not form.validate():
        flash(lazy_gettext('Please correct the errors'), 'error')
        return respond(True)

    info = {}
    # Add the info items
    if form.thumbnail.data:
        info['thumbnail'] = form.thumbnail.data

    app = model.App(
        name=form.name.data,
        short_name=form.short_name.data,
        description=form.description.data,
        long_description=form.long_description.data,
        category_id=form.category_id.data,
        allow_anonymous_contributors=form.allow_anonymous_contributors.data,
        hidden=int(form.hidden.data),
        owner_id=current_user.id,
        info=info,
    )

    cached_apps.reset()
    db.session.add(app)
    db.session.commit()
    # Clean cache
    msg_1 = lazy_gettext('Application created!')
    flash('<i class="icon-ok"></i> ' + msg_1, 'success')
    flash(
        '<i class="icon-bullhorn"></i> ' + lazy_gettext('You can check the ') +
        '<strong><a href="https://docs.pybossa.com">' +
        lazy_gettext('Guide and Documentation') + '</a></strong> ' +
        lazy_gettext('for adding tasks, a thumbnail, using PyBossa.JS, etc.'),
        'info')
    return redirect(url_for('.settings', short_name=app.short_name))
예제 #34
0
파일: forms.py 프로젝트: yeahlol/gifpad
 def validate_tags(self, tags):
   if len(tags) > 5 or len(tags) == 0:
     self.errors["tag_items"] = lazy_gettext(u"Please don't use more than 6 tags") if len(tags) > 5 else lazy_gettext(u"Enter tag")
     return False
   else:
     for tag in tags:  # 単一のタグが21文字以上で構成されている場合はerror分岐
       if len(tag) == 0 or len(tag) >= 21:
         self.errors["tag_length"] = lazy_gettext(u"Tag must be between 1 and 20 characters long")
         return False
     for tag in tags:  # 単一のタグがひらカナ漢字, 半角英字, 半角全角数字アンダースコアハイフン以外で構成されている場合はerror分岐
       if not re.compile(u"^([a-zA-Z0-9_-]|[0-9ぁ-ん_ー]|[ァ-ヴ]|[一-龠])+$").search(tag):
         self.errors["tag_re"] = lazy_gettext(u"Letters and numbers only")
         return False
   return True 
예제 #35
0
파일: forms.py 프로젝트: yeahlol/gifpad
class Sign_upform(Form):
    username = TextField(
        lazy_gettext(u'Username'),
        validators=[
            Required(lazy_gettext(u'Enter Username')),
            Length(min=2,
                   max=25,
                   message=lazy_gettext(
                       u"Field must be between 2 and 25 characters long")),
            Regexp("^[a-zA-Z0-9_]+$",
                   message=lazy_gettext(
                       u"Letters and numbers and underscore only"))
        ])

    password = PasswordField(
        lazy_gettext(u'Password'),
        validators=[
            Required(lazy_gettext(u'Enter Password')),
            Length(min=8,
                   max=30,
                   message=lazy_gettext(
                       u"Field must be between 8 and 30 characters long")),
            Regexp("^[a-zA-Z0-9]+$",
                   message=lazy_gettext(u"Letters and numbers only"))
        ])

    email = TextField(
        u'Email(optional)',
        validators=[
            Optional(),
            Length(min=2,
                   max=50,
                   message=lazy_gettext(
                       u"Field must be between 2 and 50 characters long")),
            Regexp("^\w[\w\.\-\_]*[^\.]@\w[\w\-]*(\.[\w\-]{1,})+[^\.]$",
                   message=lazy_gettext(u"Invalid Email"))
        ])

    def validate_banned_username(self):
        banned_usernames = [
            'user', 'gif', 'submit', 'board', 'upload', 'tag', 'page',
            'gif_delete', 'comment', 'password', 'resetpassword', 'authorize',
            'oauth'
        ]
        for banned_username in banned_usernames:
            if self.username.data == banned_username:
                return u"username"
        return False
예제 #36
0
def new():
    if not require.app.create():
        abort(403)
    form = AppForm(request.form)
    categories = db.session.query(model.Category).all()
    form.category_id.choices = [(c.id, c.name) for c in categories]

    def respond(errors):
        return render_template('applications/new.html',
                               title=lazy_gettext("Create an Application"),
                               form=form, errors=errors)

    if request.method != 'POST':
        return respond(False)

    if not form.validate():
        flash(lazy_gettext('Please correct the errors'), 'error')
        return respond(True)

    info = {}
    # Add the info items
    if form.thumbnail.data:
        info['thumbnail'] = form.thumbnail.data

    app = model.App(name=form.name.data,
                    short_name=form.short_name.data,
                    description=form.description.data,
                    long_description=form.long_description.data,
                    category_id=form.category_id.data,
                    allow_anonymous_contributors=form.allow_anonymous_contributors.data,
                    hidden=int(form.hidden.data),
                    owner_id=current_user.id,
                    info=info,)

    cached_apps.reset()
    db.session.add(app)
    db.session.commit()
    # Clean cache
    msg_1 = lazy_gettext('Application created!')
    flash('<i class="icon-ok"></i> ' + msg_1, 'success')
    flash('<i class="icon-bullhorn"></i> ' +
          lazy_gettext('You can check the ') +
          '<strong><a href="https://docs.pybossa.com">' +
          lazy_gettext('Guide and Documentation') +
          '</a></strong> ' +
          lazy_gettext('for adding tasks, a thumbnail, using PyBossa.JS, etc.'),
          'info')
    return redirect(url_for('.settings', short_name=app.short_name))
예제 #37
0
파일: web.py 프로젝트: hsenot/pybossa
def global_template_context():
    if current_user.is_authenticated():
        if current_user.email_addr == current_user.name or current_user.email_addr == "None":
            flash(
                lazy_gettext("Please update your e-mail address in your profile page," " right now it is empty!"),
                "error",
            )

    # Announcement sections
    if app.config.get("ANNOUNCEMENT"):
        announcement = app.config["ANNOUNCEMENT"]
        if current_user.is_authenticated():
            for key in announcement.keys():
                if key == "admin" and current_user.admin:
                    flash(announcement[key], "info")
                if key == "owner" and len(current_user.apps) != 0:
                    flash(announcement[key], "info")
                if key == "user":
                    flash(announcement[key], "info")

    return dict(
        brand=app.config["BRAND"],
        title=app.config["TITLE"],
        logo=app.config["LOGO"],
        copyright=app.config["COPYRIGHT"],
        description=app.config["DESCRIPTION"],
        terms_of_use=app.config["TERMSOFUSE"],
        data_use=app.config["DATAUSE"],
        enforce_privacy=app.config["ENFORCE_PRIVACY"],
        version=pybossa.__version__,
        current_user=current_user,
    )
예제 #38
0
def update(short_name):
    app = app_by_shortname(short_name)

    def handle_valid_form(form):
        hidden = int(form.hidden.data)

        new_info = {}
        # Add the info items
        app = app_by_shortname(short_name)
        if form.thumbnail.data:
            new_info['thumbnail'] = form.thumbnail.data
        #if form.sched.data:
        #    new_info['sched'] = form.sched.data

        # Merge info object
        info = dict(app.info.items() + new_info.items())

        new_application = model.App(
            id=form.id.data,
            name=form.name.data,
            short_name=form.short_name.data,
            description=form.description.data,
            long_description=form.long_description.data,
            hidden=hidden,
            info=info,
            owner_id=app.owner_id,
            allow_anonymous_contributors=form.allow_anonymous_contributors.data)

        app = app_by_shortname(short_name)
        db.session.merge(new_application)
        db.session.commit()
        flash(lazy_gettext('Application updated!'), 'success')
        return redirect(url_for('.details',
                                short_name=new_application.short_name))

    if not require.app.update(app):
        abort(403)

    title = app_title(app, "Update")
    if request.method == 'GET':
        form = AppForm(obj=app)
        form.populate_obj(app)
        if app.info.get('thumbnail'):
            form.thumbnail.data = app.info['thumbnail']
        #if app.info.get('sched'):
        #    for s in form.sched.choices:
        #        if app.info['sched'] == s[0]:
        #            form.sched.data = s[0]
        #            break

    if request.method == 'POST':
        form = AppForm(request.form)
        if form.validate():
            return handle_valid_form(form)
        flash(lazy_gettext('Please correct the errors'), 'error')

    return render_template('/applications/update.html',
                           form=form,
                           title=title,
                           app=app)
예제 #39
0
def presenter(short_name):
    app = app_by_shortname(short_name)
    title = app_title(app, "Contribute")
    template_args = {"app": app, "title": title}

    if not app.allow_anonymous_contributors and current_user.is_anonymous():
        msg = "Oops! You have to sign in to participate in <strong>%s</strong> \
               application" % app.name
        flash(lazy_gettext(msg), 'warning')
        return redirect(url_for('account.signin',
                        next=url_for('.presenter', short_name=app.short_name)))

    msg = "Ooops! You are an anonymous user and will not \
           get any credit for your contributions. Sign in \
           now!"

    def respond(tmpl):
        if (current_user.is_anonymous()):
            msg_1 = lazy_gettext(msg)
            flash(msg_1, "warning")
        resp = make_response(render_template(tmpl, **template_args))
        return resp

    if app.info.get("tutorial") and \
            request.cookies.get(app.short_name + "tutorial") is None:
        resp = respond('/applications/tutorial.html')
        resp.set_cookie(app.short_name + 'tutorial', 'seen')
        return resp
    else:
        return respond('/applications/presenter.html')
예제 #40
0
    def handle_valid_form(form):
        hidden = int(form.hidden.data)

        new_info = {}
        # Add the info items
        app = app_by_shortname(short_name)
        if form.thumbnail.data:
            new_info['thumbnail'] = form.thumbnail.data
        if form.sched.data:
            new_info['sched'] = form.sched.data

        # Merge info object
        info = dict(app.info.items() + new_info.items())

        new_application = model.App(
            id=form.id.data,
            name=form.name.data,
            short_name=form.short_name.data,
            description=form.description.data,
            long_description=form.long_description.data,
            hidden=hidden,
            info=info,
            owner_id=app.owner_id,
            allow_anonymous_contributors=form.allow_anonymous_contributors.data
        )

        app = app_by_shortname(short_name)
        db.session.merge(new_application)
        db.session.commit()
        flash(lazy_gettext('Application updated!'), 'success')
        return redirect(
            url_for('.details', short_name=new_application.short_name))
예제 #41
0
    def handle_valid_form(form):
        hidden = int(form.hidden.data)

        new_info = {}
        # Add the info items
        app = app_by_shortname(short_name)
        if form.thumbnail.data:
            new_info['thumbnail'] = form.thumbnail.data
        #if form.sched.data:
        #    new_info['sched'] = form.sched.data

        # Merge info object
        info = dict(app.info.items() + new_info.items())

        new_application = model.App(
            id=form.id.data,
            name=form.name.data,
            short_name=form.short_name.data,
            description=form.description.data,
            long_description=form.long_description.data,
            hidden=hidden,
            info=info,
            owner_id=app.owner_id,
            allow_anonymous_contributors=form.allow_anonymous_contributors.data,
            category_id=form.category_id.data)

        app = app_by_shortname(short_name)
        db.session.merge(new_application)
        db.session.commit()
        cached_apps.reset()
        cached_cat.reset()
        flash(lazy_gettext('Application updated!'), 'success')
        return redirect(url_for('.details',
                                short_name=new_application.short_name))
예제 #42
0
class ExportVectorLayer(Base):
    __tablename__ = 'layers_vector_export'
    layer_type = lazy_gettext('vector export')

    id = sa.Column(sa.Integer, primary_key=True)
    project_id = sa.Column(sa.Integer, sa.ForeignKey('projects.id'))
    file_name = sa.Column(sa.String())
예제 #43
0
    def import_csv_tasks(self, csvreader):
        headers = []
        fields = set(['state', 'quorum', 'calibration', 'priority_0',
                      'n_answers'])
        field_header_index = []

        for row in csvreader:
            print row
            if not headers:
                headers = row
                if len(headers) != len(set(headers)):
                    msg = lazy_gettext('The file you uploaded has '
                                       'two headers with the same name.')
                    raise BulkImportException(msg)
                field_headers = set(headers) & fields
                for field in field_headers:
                    field_header_index.append(headers.index(field))
            else:
                task_data = {"info": {}}
                for idx, cell in enumerate(row):
                    if idx in field_header_index:
                        task_data[headers[idx]] = cell
                    else:
                        task_data["info"][headers[idx]] = cell
                yield task_data
예제 #44
0
파일: account.py 프로젝트: epiraces/pybossa
def applications():
    user = User.query.get_or_404(current_user.id)
    apps_published = []
    apps_draft = []

    sql = text('''
               SELECT app.name, app.short_name, app.description,
               app.info, count(task.app_id) as n_tasks
               FROM app LEFT OUTER JOIN task ON (task.app_id=app.id)
               WHERE app.owner_id=:user_id GROUP BY app.name, app.short_name,
               app.description,
               app.info;''')

    results = db.engine.execute(sql, user_id=user.id)
    for row in results:
        app = dict(name=row.name, short_name=row.short_name,
                   description=row.description,
                   info=json.loads(row.info), n_tasks=row.n_tasks,
                  )
        if app['n_tasks'] > 0:
            apps_published.append(app)
        else:
            apps_draft.append(app)

    return render_template('account/applications.html',
                           title=lazy_gettext("Applications"),
                           apps_published=apps_published,
                           apps_draft=apps_draft)
예제 #45
0
파일: challenge.py 프로젝트: feroda/sagenb
    def html(self, **kwargs):
        """
        Returns a suggestion to inform the Notebook server's
        administrator about the misconfigured challenge.

        INPUT:

        - ``conf`` - a :class:`ServerConfiguration`; an instance of the
          server's configuration

        - ``kwargs`` - a dictionary of keyword arguments

        OUTPUT:

        - a string

        TESTS::

            sage: from sagenb.notebook.challenge import NotConfiguredChallenge
            sage: tmp = tmp_dir() + '.sagenb'
            sage: import sagenb.notebook.notebook as n
            sage: nb = n.Notebook(tmp)
            sage: chal = NotConfiguredChallenge(nb.conf())
            sage: print chal.html()
            Please ask the server administrator to configure a challenge!

        """
        return lazy_gettext("Please ask the server administrator to configure a challenge!")
예제 #46
0
def presenter(short_name):
    app = app_by_shortname(short_name)
    title = app_title(app, "Contribute")
    template_args = {"app": app, "title": title}

    if not app.allow_anonymous_contributors and current_user.is_anonymous():
        msg = "Oops! You have to sign in to participate in <strong>%s</strong> \
               application" % app.name
        flash(lazy_gettext(msg), 'warning')
        return redirect(
            url_for('account.signin',
                    next=url_for('.presenter', short_name=app.short_name)))

    msg = "Ooops! You are an anonymous user and will not \
           get any credit for your contributions. Sign in \
           now!"

    def respond(tmpl):
        if (current_user.is_anonymous()):
            msg_1 = lazy_gettext(msg)
            flash(msg_1, "warning")
        resp = make_response(render_template(tmpl, **template_args))
        return resp

    if app.info.get("tutorial") and \
            request.cookies.get(app.short_name + "tutorial") is None:
        resp = respond('/applications/tutorial.html')
        resp.set_cookie(app.short_name + 'tutorial', 'seen')
        return resp
    else:
        return respond('/applications/presenter.html')
예제 #47
0
 def __init__(self, session, model, field, message=None):
     self.session = session
     self.model = model
     self.field = field
     if not message:
         message = lazy_gettext(u'This item already exists')
     self.message = message
예제 #48
0
파일: account.py 프로젝트: epiraces/pybossa
def change_password():
    form = ChangePasswordForm(request.form)
    if form.validate_on_submit():
        user = db.session.query(model.User).get(current_user.id)
        if user.check_password(form.current_password.data):
            user.set_password(form.new_password.data)
            db.session.add(user)
            db.session.commit()
            flash(lazy_gettext('Yay, you changed your password succesfully!'), 'success')
            return redirect(url_for('.profile'))
        else:
            msg = lazy_gettext("Your current password doesn't match the one in our records")
            flash(msg, 'error')
    if request.method == 'POST' and not form.validate():
        flash(lazy_gettext('Please correct the errors'), 'error')
    return render_template('/account/password.html', form=form)
예제 #49
0
파일: validator.py 프로젝트: hsenot/pybossa
 def __init__(self, session, model, field, message=None):
     self.session = session
     self.model = model
     self.field = field
     if not message:
         message = lazy_gettext(u"This item already exists")
     self.message = message
예제 #50
0
파일: web.py 프로젝트: jikimlucas/pybossa
def global_template_context():
    if current_user.is_authenticated():
        if (current_user.email_addr == current_user.name or
                current_user.email_addr == "None"):
            flash(lazy_gettext("Please update your e-mail address in your profile page,"
                  " right now it is empty!"), 'error')

    # Announcement sections
    if app.config.get('ANNOUNCEMENT'):
        announcement = app.config['ANNOUNCEMENT']
        if current_user.is_authenticated():
            for key in announcement.keys():
                if key == 'admin' and current_user.admin:
                    flash(announcement[key], 'info')
                if key == 'owner' and len(current_user.apps) != 0:
                    flash(announcement[key], 'info')
                if key == 'user':
                    flash(announcement[key], 'info')

    return dict(
        brand=app.config['BRAND'],
        title=app.config['TITLE'],
        logo=app.config['LOGO'],
        copyright=app.config['COPYRIGHT'],
        description=app.config['DESCRIPTION'],
        terms_of_use=app.config['TERMSOFUSE'],
        data_use=app.config['DATAUSE'],
        enforce_privacy=app.config['ENFORCE_PRIVACY'],
        version=pybossa.__version__,
        current_user=current_user)
예제 #51
0
def _import_task(app, handler, form, render_forms):
    try:
        empty = True
        for task_data in handler.tasks(form):
            task = model.Task(app=app)
            print task_data
            [setattr(task, k, v) for k, v in task_data.iteritems()]
            db.session.add(task)
            db.session.commit()
            empty = False
        if empty:
            raise importer.BulkImportException(
                lazy_gettext('Oops! It looks like the file is empty.'))
        flash(lazy_gettext('Tasks imported successfully!'), 'success')
        return redirect(url_for('.tasks', short_name=app.short_name))
    except importer.BulkImportException, err_msg:
        flash(err_msg, 'error')
예제 #52
0
def raster_source_label(external_source):
    server_title = lazy_gettext('local')
    if external_source.gbi_server is not None:
        server_title = external_source.gbi_server.title

    return '%s (%s)' % (
        external_source.title,
        server_title
    )
예제 #53
0
파일: account.py 프로젝트: epiraces/pybossa
def register():
    # TODO: re-enable csrf
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        account = model.User(fullname=form.fullname.data,
                             name=form.username.data,
                             email_addr=form.email_addr.data)
        account.set_password(form.password.data)
        account.locale = get_locale()
        db.session.add(account)
        db.session.commit()
        login_user(account, remember=True)
        flash(lazy_gettext('Thanks for signing-up'), 'success')
        return redirect(url_for('home'))
    if request.method == 'POST' and not form.validate():
        flash(lazy_gettext('Please correct the errors'), 'error')
    return render_template('account/register.html',
                           title=lazy_gettext("Register"), form=form)
예제 #54
0
 def test_lazy_gettext(self):
     app = flask.Flask(__name__)
     b = babel.Babel(app, default_locale='de_DE')
     yes = lazy_gettext(u'Yes')
     with app.test_request_context():
         assert unicode(yes) == 'Ja'
     app.config['BABEL_DEFAULT_LOCALE'] = 'en_US'
     with app.test_request_context():
         assert unicode(yes) == 'Yes'
예제 #55
0
파일: tests.py 프로젝트: sm6xmm/flask-babel
 def test_lazy_gettext(self):
     app = flask.Flask(__name__)
     b = babel.Babel(app, default_locale="de_DE")
     yes = lazy_gettext(u"Yes")
     with app.test_request_context():
         assert unicode(yes) == "Ja"
     app.config["BABEL_DEFAULT_LOCALE"] = "en_US"
     with app.test_request_context():
         assert unicode(yes) == "Yes"
예제 #56
0
파일: account.py 프로젝트: epiraces/pybossa
def signin():
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        password = form.password.data
        email = form.email.data
        user = model.User.query.filter_by(email_addr=email).first()
        if user and user.check_password(password):
            login_user(user, remember=True)
            msg_1 = lazy_gettext("Welcome back") + " " + user.fullname
            flash(msg_1, 'success')
            return redirect(request.args.get("next") or url_for("home"))
        elif user:
            msg, method = get_user_signup_method(user)
            if method == 'local':
                msg = lazy_gettext("Ooops, Incorrect email/password")
                flash(msg, 'error')
            else:
                flash(msg, 'info')
        else:
            msg = lazy_gettext("Ooops, we didn't find you in the system, \
                               did you sign in?")
            flash(msg, 'info')

    if request.method == 'POST' and not form.validate():
        flash(lazy_gettext('Please correct the errors'), 'error')
    auth = {'twitter': False, 'facebook': False, 'google': False}
    if current_user.is_anonymous():
        # If Twitter is enabled in config, show the Twitter Sign in button
        if ('twitter' in current_app.blueprints):
            auth['twitter'] = True
        if ('facebook' in current_app.blueprints):
            auth['facebook'] = True
        if ('google' in current_app.blueprints):
            auth['google'] = True
        return render_template('account/signin.html',
                               title="Sign in",
                               form=form, auth=auth,
                               next=request.args.get('next'))
    else:
        # User already signed in, so redirect to home page
        return redirect(url_for("home"))
예제 #57
0
파일: account.py 프로젝트: epiraces/pybossa
def forgot_password():
    form = ForgotPasswordForm(request.form)
    if form.validate_on_submit():
        user = model.User.query\
                    .filter_by(email_addr=form.email_addr.data)\
                    .first()
        if user and user.email_addr:
            msg = Message(subject='Account Recovery',
                          recipients=[user.email_addr])
            if user.twitter_user_id:
                msg.body = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user, account_name='Twitter')
            elif user.facebook_user_id:
                msg.body = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user, account_name='Facebook')
            elif user.google_user_id:
                msg.body = render_template(
                    '/account/email/forgot_password_openid.md',
                    user=user, account_name='Google')
            else:
                userdict = {'user': user.name, 'password': user.passwd_hash}
                key = signer.dumps(userdict, salt='password-reset')
                recovery_url = url_for('.reset_password',
                                       key=key, _external=True)
                msg.body = render_template(
                    '/account/email/forgot_password.md',
                    user=user, recovery_url=recovery_url)
            msg.html = markdown(msg.body)
            mail.send(msg)
            flash(lazy_gettext("We've send you email with account recovery instructions!"),
                  'success')
        else:
            flash(lazy_gettext("We don't have this email in our records. You may have"
                  " signed up with a different email or used Twitter, "
                  "Facebook, or Google to sign-in"), 'error')
    if request.method == 'POST' and not form.validate():
        flash(lazy_gettext('Something went wrong, please correct the errors on the '
              'form'), 'error')
    return render_template('/account/password_forgot.html', form=form)