def validate(email, token): user = User.query.filter_by(email=email).first() if controller.validate_user(user, token): flash(_(u"You have been validated, {}").format(user.username), 'success') else: flash(_(u"I wasn't able to validate you"), 'error') return redirect(url_for('home'))
def configure_extensions(app): # Flask-Babel babel.init_app(app) @babel.localeselector def get_locale(): accept_languages = app.config.get('ACCEPT_LANGUAGES') return request.accept_languages.best_match(accept_languages) # Flask-SQLAlchemy db.init_app(app) # Flask-Mail mail.init_app(app) # Flask-Login #login_manager.anonymous_user = Anonymous TODO #login_manager.login_view = "session.login" login_manager.login_message = _(u"Please log in to access this page.") login_manager.refresh_view = "account.reauth" login_manager.needs_refresh_message = ( _(u"To protect your account, please reauthenticate to access this page.") ) @login_manager.user_loader def load_user(id): return User.query.get(int(id)) login_manager.setup_app(app)
def age(dt, now=None): # Fail silently for now XXX if not dt: return "" if not now: now = datetime.utcnow() age = now - dt if age.days == 0: if age.seconds < 120: age_str = _("a minute ago") elif age.seconds < 3600: age_str = _("%(num)d minutes ago", num=age.seconds / 60) elif age.seconds < 7200: age_str = _("an hour ago") else: age_str = _("%(num)d hours ago", num=age.seconds / 3600) else: if age.days == 1: age_str = _("yesterday") elif age.days <= 31: age_str = _("%(num)d days ago", num=age.days) elif age.days <= 72: age_str = _("a month ago") elif age.days <= 365: age_str = _("%(num)d months ago", num=age.days / 30) elif age.days <= 2*365: age_str = _("last year") else: age_str = _("%(num)d years ago", num=age.days / 365) return age_str
def refresh_context(): if reload_context_document(current_app.config.geobox_state, session['username'], request.form['password']): flash(_('load context document successful'), 'sucess') else: flash(_('password not correct'), 'error') return redirect(url_for('.admin'))
def send_message(user_id): user = User.query.get_or_404(user_id) user.permissions.send_message.test(403) form = MessageForm() if form.validate_on_submit(): body = render_template("emails/send_message.html", user=user, subject=form.subject.data, message=form.message.data) subject = _("You have received a message from %(name)s", name=g.user.username) message = Message(subject=subject, body=body, recipients=[user.email]) mail.send(message) flash(_("Your message has been sent to %(name)s", name=user.username), "success") return redirect(url_for("user.posts", username=user.username)) return render_template("user/send_message.html", user=user, form=form)
def edit_profile(): if g.user is None: abort(401) form = UpdateProfileForm( #email=g.user.email, blog=g.user.blog, github=g.user.github, brief=g.user.brief, ) if form.validate_on_submit(): if form.delete.data: # TODO delete relational data g.user.remove() session.pop('openid', None) flash(_('Profile deleted'), 'success') return redirect(url_for('home.index')) flash(_('Profile Updated'), 'success') form.populate_obj(g.user) g.user.save() return redirect(url_for('edit_profile')) return render_template('account/edit_profile.html', form=form)
class TemplateForm(Form): html = TextAreaField(_("HTML"), validators=[required(message=_("HTML required"))]) submit = SubmitField(_("Save")) cancel = SubmitField(_("Cancel"))
def is_valid_shapefile(shape_file, mapping): with collection(shape_file, 'r') as source: if source.schema['geometry'] not in ('Polygon', 'MultiPolygon'): raise ConvertError(_('invalid geometry type') + ': ' + source.schema['geometry']) elif source.schema['geometry'] != mapping.geom_type and mapping.geom_type != '*': raise ConvertError(_('invalid mapping')) return True
def import_json(box_name, id): layer = request.form.get('layers', False) new_layer = request.form.get('name', False) file_name = request.form.get('file_name', False) title = None if (layer and new_layer) or (not layer and not new_layer): flash(_('please select new layer or current layer to import'), 'error') return redirect(url_for('.files', box_name=box_name)) if layer: layer = layer else: title = new_layer layer = 'local_vector_' + re.sub(r'[^a-z0-9]*', '', new_layer.lower()) if layer == 'local_vector_': flash(_('None of the characters used for the layer is allowed')) return redirect(url_for('.files', box_name=box_name)) task = VectorImportTask( db_name=layer, title=title, file_name=file_name, type_ = 'geojson', source = get_couch_box_db(box_name) ) g.db.add(task) g.db.commit() flash(_("file will be imported"), 'success') return redirect(url_for('tasks.list'))
def register(): form = SignupForm() if form.validate_on_submit(): user = User() form.populate_obj(user) user.activation_key = str(uuid.uuid4()) db.session.add(user) db.session.commit() body = render_template("emails/register.html", user=user) message = Message(subject=_(u"TZOS: Activate your account"), body=body, recipients=[user.email]) mail.send(message) flash(_(u"Please check your email for instructions on " "how to activate your account."), "success") return redirect(url_for("frontend.index")) return render_template('account/register.html', form=form)
def index(): if not current_user.is_authenticated(): abort(403) if current_user.is_admin(): vms = VM.query.filter().all() else: vms = VM.query.filter(VM.owner_id == current_user.id).all() form = AddVMForm(next=request.args.get('next')) form.template_id.choices = Template.get_templates_choices() if form.validate_on_submit(): vm = VM() form.populate_obj(vm) # validate VM name here if VM.query.filter(db.and_(VM.owner_id == current_user.id, VM.name == vm.name)).first() is not None: flash(_("VM Name %(name)s is taken.", name = vm.name), "error") return redirect(form.next.data or url_for('user.index')) vm.owner_id = current_user.id create_vm(vm) return redirect(form.next.data or url_for('vm.index')) elif form.is_submitted(): flash(_("Failed to add VM"), "error") return render_template('vm/index.html', vms=vms, form=form, active=_("VirtualMachines"))
def index(): if not current_user.is_authenticated(): abort(403) if current_user.is_admin(): vms = VM.query.filter().all() else: vms = VM.query.filter(VM.owner_id == current_user.id).all() form = AddVMForm(next=request.args.get('next')) form.template_id.choices = Template.get_templates_choices() if form.validate_on_submit(): vm = VM() form.populate_obj(vm) # validate VM name here if VM.query.filter( db.and_(VM.owner_id == current_user.id, VM.name == vm.name)).first() is not None: flash(_("VM Name %(name)s is taken.", name=vm.name), "error") return redirect(form.next.data or url_for('user.index')) vm.owner_id = current_user.id create_vm(vm) return redirect(form.next.data or url_for('vm.index')) elif form.is_submitted(): flash(_("Failed to add VM"), "error") return render_template('vm/index.html', vms=vms, form=form, active=_("VirtualMachines"))
def edit_origin(id): origin = TermOrigin.query.get_or_404(id) form = _gen_origins_form(EditTermOriginForm, obj=origin) if form and form.validate_on_submit(): # Make sure it's safe to move the current origin if origin.can_move_to(form.parent_id.data): form.populate_obj(origin) if form.parent_id.data < 0: origin.parent_id = None db.session.commit() # Invalidate cache cache.delete_memoized('get_origins_dropdown') flash(_(u"Term origin ‘%(origin)s’ has been edited.", origin=origin.name), "success") return redirect(url_for("admin.settings")) else: flash(_(u"Couldn't move origin ‘%(origin)s’ to that location.", origin=origin.name), "error") return render_template("admin/edit_origin.html", form=form, origin=origin)
def languages(): form = AddLanguagesForm() if form and form.validate_on_submit(): qs = ''' let $lang := collection($collection)/TBXXCS/languages/langInfo[langCode[string()="{0}"]] let $xml := <langInfo> <langCode>{0}</langCode><langName>{1}</langName> </langInfo> return if (empty($lang)) then insert node $xml as last into collection($collection)/TBXXCS/languages else replace node $lang with $xml '''.format(form.code.data.encode('utf-8'), form.name.data.encode('utf-8')) if dbxml.session.insert_raw(qs): # Invalidate cache cache.delete_memoized('get_dict_langs') flash(_(u"Language ‘%(lang)s’ has been added.", lang=form.name.data), "success") else: flash(_(u"Error while adding language. Check the inserted " "values are correct."), "error") return redirect(url_for("admin.settings"))
def forgot_password(): form = RecoverPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: flash(_("Please see your email for instructions on " "how to access your account"), "success") user.activation_key = str(uuid.uuid4()) db.session.commit() body = render_template("emails/recover_password.html", user=user) message = Message(subject=_("Recover your password"), body=body, recipients=[user.email]) mail.send(message) return redirect(url_for("frontend.index")) else: flash(_("Sorry, no user found for that email address"), "error") return render_template("account/recover_password.html", form=form)
class LoginForm(Form): next = HiddenField() remember = BooleanField(_('Remember me')) login = TextField(_('Username or email address'), [required()]) password = PasswordField(_('Password'), [required(), length(min=6, max=16)]) submit = SubmitField(_('Login'))
def updateGameScripts(id): """更新单个游戏脚本""" gs = master.appMap.get(id) if gs is None: return render_template("script.html", gs=gs, errorMsg=_("serverNotExist")) else: if request.method == "GET": return render_template("script.html", gs=gs) else: f = request.files["script"] if not f: return render_template("script.html", gs=gs, errorMsg=_("noFileUploaded")) else: basePath = appPath path = os.path.join(basePath, "uploads") os.chdir(path) folder = datetime.datetime.now().strftime("script_%Y%m%d_%H%M%S") os.mkdir(folder) path = os.path.join(path, folder) os.chdir(path) fileName = f.filename f.save(os.path.join(path, fileName)) f.close() f = open(os.path.join(path, fileName), "rb") result = master.updateScripts([id], fileName, f.read()) f.close() return render_template("script.html", gs=gs, infoMsg=parseScriptUpdateResult(result))
def template_edit(path): path = os.path.join(current_app.root_path, 'templates', "%s.html" % path) html = "" try: f = open(path) html = f.read() f.close() except: flash(_("Template file does not exists"), "error") form = TemplateForm(html=html.decode('utf8')) if form.validate_on_submit(): f = open(path, 'w') f.write(form.html.data.encode('utf8')) f.close() flash(_("Saving success"), "success") return redirect(url_for("frontend.index")) return render_template("blog/template_edit.html", form=form, path=path)
def login(): form = LoginForm(login=request.args.get('login',None), next=request.args.get('next',None)) if form.validate_on_submit(): user, authenticated = User.query.authenticate(form.login.data, form.password.data) if user and authenticated: session.permanent = form.remember.data identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) flash(_("Welcome back, %(name)s", name=user.username), "success") next_url = form.next.data if not next_url or next_url == request.path: next_url = url_for('frontend.people', username=user.username) return redirect(next_url) else: flash(_("Sorry, invalid login"), "error") return render_template("account/login.html", form=form)
class FeedbackForm(wtf.Form): subject = wtf.TextField(_('Subject'), [wtf.validators.required()]) message = wtf.TextAreaField(_('Message'), [wtf.validators.required()]) email = wtf.TextField(_('Email (optional)'), [ wtf.validators.optional(), wtf.validators.email(_('That does not look like an email')), ])
def delete(post_id): post = Post.query.get_or_404(post_id) post.permissions.delete.test(403) Comment.query.filter_by(post=post).delete() db.session.delete(post) db.session.commit() if g.user.id != post.author_id: body = render_template("emails/post_deleted.html", post=post) message = Message(subject="Your post has been deleted", body=body, recipients=[post.author.email]) mail.send(message) flash(_("The post has been deleted"), "success") else: flash(_("Your post has been deleted"), "success") return jsonify(success=True, redirect_url=url_for('frontend.index'))
def contact(): if g.user: form = ContactForm(obj=g.user) else: form = ContactForm() if form and form.validate_on_submit(): admins = User.query.filter(User.role == User.ADMIN) admin_emails = [admin.email for admin in admins] body = render_template("emails/contact.html", name=form.display_name.data, email=form.email.data, text=form.text.data) message = Message(subject=_(u"TZOS: Contact from website"), body=body, recipients=admin_emails) mail.send(message) flash(_(u"Thanks for your message. We will try to reply you " "back as fast as possible."), "success") return redirect(url_for("frontend.index")) return render_template('contact.html', contact_form=form)
def set_home_server(): app_state = current_app.config.geobox_state if app_state.new_home_server is None: flash(_('unable to set homeserver'), 'error') db_session = app_state.user_db_session() gbi_server = db_session.query(GBIServer).filter_by( id=app_state.new_home_server.id).first() if gbi_server is None: flash(_('unable to set homeserver'), 'error') gbi_server.context = app_state.new_home_server.context gbi_server.active_home_server = True db_session.commit() context.update_couchdb_sources(gbi_server, app_state) context_user = gbi_server.context.user() if context_user: app_state.config.set('user', 'type', str(context_user['type'])) else: app_state.config.set('user', 'type', '0') # set default to 0 app_state.config.write() flash( _('assigned %(homeserver)s as homeserver', homeserver=gbi_server.title)) app_state.new_home_server = None if app_state.user.is_customer: return redirect(url_for('admin.upload_gml')) return redirect(url_for('main.index'))
def add(): objective_schema = schema.Objective({}) tmp_collection = mongo.db.objectives.find().sort('id', -1) try: new_index = tmp_collection[0]['id'] + 1 except IndexError: new_index = 1 objective_schema['id'] = new_index if flask.request.method == "POST": data = flask.request.form.to_dict() objective_schema['title']['en'].set(data['title-en']) objective_schema['body']['en'].set(data['body-en']) if objective_schema.validate(): objective = objective_schema.flatten() sugar.get_none_fields_for_schema(objective) flask.flash(_("Objective successfully added."), "success") mongo.db.objectives.save(objective) return flask.redirect(flask.url_for('objectives.list_objectives')) else: flask.flash(_("Error in adding an objective."), "error") return { "schema": objective_schema }
def reset_password(): form = RecoverPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: flash( 'Please see your email for instructions on ' 'how to access your account', 'success') user.activation_key = str(uuid4()) db.session.add(user) db.session.commit() url = url_for('frontend.change_password', email=user.email, activation_key=user.activation_key, _external=True) html = render_template('macros/_reset_password.html', project=current_app.config['PROJECT'], username=user.name, url=url) message = Message(subject=_('Reset your password in ' + current_app.config['PROJECT']), html=html, recipients=[user.email]) mail.send(message) return render_template('frontend/reset_password.html', form=form) else: flash(_('Sorry, no user found for that email address'), 'error') return render_template('frontend/reset_password.html', form=form)
def index(): hosts = Host.query.all() form = AddHostForm(next=request.args.get('next')) if form.validate_on_submit(): host = Host() form.populate_obj(host) status, errMsg = host.check_connect() message = _("Add Host %(address)s", address=host.address) if status: flash(_("Host %(address)s was added", address=host.address), "success") log_task(message) else: flash(_("Failed to add Host %(address)s", address=host.address), "error") current_app.logger.error(errMsg) log_task(message, TASK_FAILED) db.session.add(host) db.session.commit() return redirect(form.next.data or url_for('host.index')) elif form.is_submitted(): flash(_("Failed to add Host"), "error") return render_template('host/index.html', hosts=hosts, active=_('Hosts'), form=form)
def authorize(self, resp): next_url = request.args.get('next') or url_for('urls.index') if resp is None: flash(_(u'You denied the request to sign in.')) return redirect(next_url) user = current_user if not user.is_authenticated(): user = User.query.filter( User.username == resp['screen_name']).first() if user is None: user = User(username=resp['screen_name'], pw_hash=''.join( choice(ASCII_LOWERCASE) for c in xrange(15))) db.session.add(user) user.oauth_token = resp['oauth_token'] user.oauth_secret = resp['oauth_token_secret'] db.session.commit() users.login(user) flash(_('Welcome %(user)s', user=user.username)) return redirect(next_url)
def delete(objective_id, action_id, so1_id=None, so2_id=None, so3_id=None, so4_id=None): from pymongo.errors import OperationFailure myargs = ['objective_id', 'so1_id', 'so2_id', 'so3_id', 'so4_id'] parents = [(i, locals()[i]) for i in myargs if locals()[i] is not None] objective = mongo.db.objectives.find_one_or_404({'id': objective_id}) father = objective for i in range(1, len(parents)): son_id = parents[i][1] try: son = [s for s in father['subobjs'] if s['id'] == son_id][0] except IndexError: flask.abort(404) father = son father['actions'] = [a for a in father['actions'] if a['id'] != action_id] from pymongo.errors import OperationFailure try: mongo.db.objectives.save(objective) flask.flash(_("Action successfully deleted"), "success") except OperationFailure: flask.flash(_("Errors encountered while deleting action"), "errors") return flask.jsonify({'status': 'success'})
class RecoverPasswordForm(Form): email = TextField( "Your email address", validators=[email(message=_("A valid email address is required"))]) submit = SubmitField(_("Find password"))
def start_raster_import(id): proj = g.db.query(model.ImportProject).get(id) if not proj: abort(404) form = forms.SetGBIServerForm(request.form) del form.url source = proj.import_raster_layers[0].source gbi_server = source.gbi_server if source.is_public or gbi_server is None or not gbi_server.auth: create_raster_import_task(proj) return redirect(url_for('tasks.list')) if form.validate_on_submit(): try: context.test_context_document(gbi_server.url, form.username.data, form.password.data) except context.AuthenticationError: flash(_('username or password not correct'), 'error') except ValueError: flash(_('unable to fetch context document'), 'error') else: create_raster_import_task(proj) return redirect(url_for('tasks.list')) return render_template('projects/verify_import_auth.html', form=form, server_title=gbi_server.title)
def reset_password(): form = RecoverPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: flash( _('Please see your email for instructions on ' 'how to access your account'), 'success') user.activation_key = str(uuid4()) db.session.add(user) db.session.commit() body = render_template('emails/reset_password.html', user=user) message = Message(subject=_('Recover your password'), body=body, recipients=[user.email]) mail.send(message) return redirect(url_for('frontend.index')) else: flash(_('Sorry, no user found for that email address'), 'error') return render_template('reset_password.html', form=form)
def reset_password(): form = RecoverPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: flash('Please see your email for instructions on ' 'how to access your account', 'success') user.activation_key = str(uuid4()) db.session.add(user) db.session.commit() url = url_for('frontend.change_password', email=user.email, activation_key=user.activation_key, _external=True) html = render_template('macros/_reset_password.html', project=current_app.config['PROJECT'], username=user.name, url=url ) message = Message(subject=_('Reset your password in '+current_app.config['PROJECT']), html=html, recipients=[user.email] ) mail.send(message) return render_template('frontend/reset_password.html', form=form) else: flash(_('Sorry, no user found for that email address'), 'error') return render_template('frontend/reset_password.html', form=form)
def validate_name(form, field): if field.data == form.name.default: raise ValidationError(_("User name incorrect")) if Person.query.filter(Person.name == field.data)\ .filter(Person.project == form.project)\ .filter(Person.activated == True).all(): raise ValidationError(_("This project already have this member"))
def reset_password(): form = RecoverPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: flash("Please see your email for instructions on " "how to access your account", "success") user.activation_key = str(uuid4()) db.session.add(user) db.session.commit() url = url_for( "frontend.change_password", email=user.email, activation_key=user.activation_key, _external=True ) html = render_template( "emails/reset_password.html", project=current_app.config["PROJECT"], username=user.name, url=url ) message = Message( subject=_("Reset your password in " + current_app.config["PROJECT"]), html=html, recipients=[user.email] ) mail.send(message) return render_template("reset_password.html", form=form) else: flash(_("Sorry, no user found for that email address"), "error") return render_template("reset_password.html", form=form)
def twitter(): if g.user.twitter: flash(_("You twitter's access token is already exists"), "error") return redirect(url_for('frontend.people', username=g.user.username)) consumer_key = current_app.config['TWITTER_KEY'] consumer_secret = current_app.config['TWITTER_SECRET'] signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) oauth_client = oauth.Client(oauth_consumer) try: resp, content = oauth_client.request(REQUEST_TOKEN_URL, 'GET') except AttributeError: flash(_("Can not connect twitter.com")) return redirect(url_for('frontend.people',username=g.user.username)) if resp['status'] != '200': return 'Invalid respond from Twitter requesting temp token: %s' % resp['status'] else: request_token = dict(parse_qsl(content)) session['token'] = request_token return redirect('%s?oauth_token=%s' % (AUTHORIZATION_URL.replace("https:","http:"), request_token['oauth_token']))
class ResponseMessageForm(Form): message_id = HiddenField() offset = HiddenField() comment = TextField(_("Comment"),description=_("What do you have to say about this post")) yes = SubmitField(_('Yes')) no = SubmitField(_('No')) def add_response(self,user,parent_id): self.populate_obj(user) comment = self.comment.data resp = self.yes.data resp = None if resp == "None" else resp if resp: timeline = TimeLine() timeline.add(user.id, parent_id, agreed = True) if(comment == '' and resp == None): return False parent = Message() parent = parent.get_by_id(parent_id) response = Message() response.root_id = parent_id if parent.root_id is None else parent_id.root_id response.user_id = user.id response.parent_id = parent_id response.text = comment response.response = resp response.save() parent.last_activity = response.last_activity parent.save() return True
def signup(): form = SignupForm(next=request.args.get('next',None)) if form.validate_on_submit(): code = UserCode.query.filter_by(code=form.code.data).first() if code: user = User(role=code.role) form.populate_obj(user) db.session.add(user) db.session.delete(code) db.session.commit() identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) flash(_("Welcome, %(name)s", name=user.nickname), "success") next_url = form.next.data if not next_url or next_url == request.path: next_url = url_for('frontend.people', username=user.username) return redirect(next_url) else: form.code.errors.append(_("Code is not allowed")) return render_template("account/signup.html", form=form)
class CommentForm(Form): comment = TextAreaField(validators=[ required(message=_("Comment is required"))]) submit = SubmitField(_("Save")) cancel = SubmitField(_("Cancel"))
def edit(post_id): post = Post.query.get_or_404(post_id) post.permissions.edit.test(403) form = PostForm(obj=post) if form.validate_on_submit(): form.populate_obj(post) db.session.commit() if g.user.id != post.author_id: body = render_template("emails/post_edited.html", post=post) message = Message(subject="Your post has been edited", body=body, recipients=[post.author.email]) mail.send(message) flash(_("The post has been updated"), "success") else: flash(_("Your post has been updated"), "success") return redirect(url_for("post.view", post_id=post_id)) return render_template("post/edit_post.html", post=post, form=form)
class PasswordReminder(Form): id = TextField(_("Project identifier"), validators=[Required()]) submit = SubmitField(_("Send me the code by email")) def validate_id(form, field): if not Project.query.get(field.data): raise ValidationError(_("This project does not exists"))
def add_unknown_confirm(): """ Show confirm on adding untracked files """ if not get_allow_commit(): abort(401) repo = get_repo() form = SelectFileConfirmForm(request.form) form.files.choices = get_choices_unknown(repo) if not form.validate(): flash(_('Invalid request. Please input again.')) return redirect(url_for('index')) if form.data.get('confirm'): # add to repos repo.add(form.data['files']) flash(_('added.')) return redirect(url_for('index')) formdata = MultiDict(request.form) del formdata['csrf'] form = SelectFileConfirmForm(None, confirm=1, **formdata) form.files.choices = get_choices_unknown(repo) form.validate() return render_template('add_unknown_confirm.html', repository=repo, form=form, hostname=gethostname(), )
class MemberForm(Form): name = TextField(_("Name"), validators=[Required()], default=_("Type user name here")) submit = SubmitField(_("Add")) def __init__(self, project, *args, **kwargs): super(MemberForm, self).__init__(*args, **kwargs) self.project = project def validate_name(form, field): if field.data == form.name.default: raise ValidationError(_("User name incorrect")) if Person.query.filter(Person.name == field.data)\ .filter(Person.project == form.project)\ .filter(Person.activated == True).all(): raise ValidationError(_("This project already have this member")) def save(self, project, person): # if the user is already bound to the project, just reactivate him person.name = self.name.data person.project = project return person
class AvatarForm(Form): next = HiddenField() avatar = FileField( label = _("Username"), validators = [Required()] ) submit = SubmitField(_('Save'))
def twitter(): if g.user.twitter: flash(_("You twitter's access token is already exists"), "error") return redirect(url_for('frontend.people', username=g.user.username)) consumer_key = current_app.config['TWITTER_KEY'] consumer_secret = current_app.config['TWITTER_SECRET'] signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) oauth_client = oauth.Client(oauth_consumer) try: resp, content = oauth_client.request(REQUEST_TOKEN_URL, 'GET') except AttributeError: flash(_("Can not connect twitter.com")) return redirect(url_for('frontend.people', username=g.user.username)) if resp['status'] != '200': return 'Invalid respond from Twitter requesting temp token: %s' % resp[ 'status'] else: request_token = dict(parse_qsl(content)) session['token'] = request_token return redirect('%s?oauth_token=%s' % (AUTHORIZATION_URL.replace( "https:", "http:"), request_token['oauth_token']))
def login(): form = LoginForm(login=request.args.get('login', None), next=request.args.get('next', None)) if form.validate_on_submit(): user, authenticated = User.query.authenticate(form.login.data, form.password.data) if user and authenticated: session.permanent = form.remember.data identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) flash(_("Welcome back, %(name)s", name=user.username), "success") next_url = form.next.data if not next_url or next_url == request.path: next_url = url_for('frontend.people', username=user.username) return redirect(next_url) else: flash(_("Sorry, invalid login"), "error") return render_template("account/login.html", form=form)
def index(): templates = Template.query.filter().all() form = AddVMForm(next=request.args.get('next')) form.template_id.choices = Template.get_templates_choices() if current_user.is_admin(): form = AddTemplateForm(next=request.args.get('next')) form.image_id.choices = Image.get_images_choices() if form.validate_on_submit(): template = Template() form.populate_obj(template) db.session.add(template) db.session.commit() log_task(_("Add Template %(name)s", name=template.name)) flash(_("Template %(name)s was added.", name=template.name), "success") return redirect(form.next.data or url_for('template.index')) elif form.is_submitted(): flash(_("Failed to add Template"), "error") return render_template('template/index.html', templates=templates, active=_('Templates'), form=form)
def signup(): form = SignupForm(next=request.args.get('next', None)) if form.validate_on_submit(): code = UserCode.query.filter_by(code=form.code.data).first() if code: user = User(role=code.role) form.populate_obj(user) db.session.add(user) db.session.delete(code) db.session.commit() identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) flash(_("Welcome, %(name)s", name=user.nickname), "success") next_url = form.next.data if not next_url or next_url == request.path: next_url = url_for('frontend.people', username=user.username) return redirect(next_url) else: form.code.errors.append(_("Code is not allowed")) return render_template("account/signup.html", form=form)
def forgot_password(): form = RecoverPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: flash( _("Please see your email for instructions on " "how to access your account"), "success") user.activation_key = str(uuid.uuid4()) db.session.commit() body = render_template("emails/recover_password.html", user=user) message = Message(subject=_("Recover your password"), body=body, recipients=[user.email]) mail.send(message) return redirect(url_for("frontend.index")) else: flash(_("Sorry, no user found for that email address"), "error") return render_template("account/recover_password.html", form=form)
def reset_password(): form = RecoverPasswordForm() if 'value' in request.values: value = request.values['value'] else: value = '' if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: flash(_('Please see your email for instructions on ' 'how to access your account' ), 'success') user.activation_key = str(uuid4()) db.session.add(user) db.session.commit() body = render_template('emails/reset_password.html', user=user) message = Message(subject=_('Recover your password'), html=body, recipients=[user.email]) mail.send(message) return redirect(url_for('frontend.index')) else: flash(_('Sorry, no user found for that email address'), 'error') # Sorry, no user found for that email address return render_template('reset_password.html', newtaskform = TaskForm(), form=form, value=value)
def edit(host_id): host = Host.query.filter_by(id=host_id).first_or_404() form = EditHostForm(obj=host, next=request.args.get('next')) if form.validate_on_submit(): form.populate_obj(host) status, errMsg = host.check_connect() message = _("Update Host %(address)s(%(id)d)", address=host.address, id=host.id) if status: flash(_("Host %(address)s was updated", address=host.address), "success") log_task(message) else: flash( _("Failed to reconnect Host %(address)s", address=host.address), "error") current_app.logger.error(errMsg) log_task(message, TASK_FAILED) db.session.add(host) db.session.commit() return redirect(form.next.data or url_for('host.index')) return render_template('host/edit.html', host=host, form=form)
def login(): # email=request.args.get('email', '*****@*****.**') form = LoginForm(email=request.args.get('email', None), next=request.args.get('next', None)) tries = request.args.get('tries', 0) login_form = form if form.validate_on_submit(): user, authenticated = User.authenticate(form.email.data, form.password.data) if user: if authenticated: remember = request.form.get('remember') == 'y' if login_user(user, remember=remember): name = [user.username,user.name][bool(user.name)] flash("Welcome, " + name + '!', 'success') # Logged in! return redirect(form.next.data or url_for('user.index')) else: flash(_('Sorry, invalid login'), 'error') # Sorry, invalid login tries = tries + 1 else: flash(_('Sorry, there is no such account'), 'error') #Sorry, there is no such account return redirect(url_for('frontend.signup', email=form.email.data)) if form.email.data: return render_template('login.html', form=form, tries=tries, newtaskform = TaskForm(), email=form.email.data, login_form=login_form) return render_template('login.html', form=form, tries=tries, newtaskform = TaskForm(), login_form=login_form)
def editor(): export_form = ExportVectorForm() export_form.srs.choices = list( current_app.config.geobox_state.config.get('web', 'available_srs')) user = current_app.config.geobox_state.user target_box_name = 'file_box' if user.is_consultant else 'upload_box' target_box_label = _('filebox') if user.is_consultant else _('upload_box') target_box = current_app.config.geobox_state.config.get( 'couchdb', target_box_name) export_form.destination.choices = [('file', _('Filesystem')), (target_box, target_box_label)] # load preview layer preview_features = False preview_layername = False box_name = request.args.get('box_name', False) filename = request.args.get('filename', False) if box_name and filename: couchbox = get_couch_box_db(box_name) couch_src = CouchFileBox( 'http://%s:%s' % ('127.0.0.1', current_app.config.geobox_state.config.get('couchdb', 'port')), couchbox) preview_features = couch_src.get_attachment(filename) preview_layername = "%s (%s)" % (filename, _('Temporary')) base_layers = g.db.query(ExternalWMTSSource).filter_by( background_layer=True).all() for base_layer in base_layers: base_layer.bbox = base_layer.bbox_from_view_coverage() wfs_search_sources = g.db.query(ExternalWFSSource).filter_by( active=True).all() if not wfs_search_sources: wfs_search_sources = False parcel_search_sources = g.db.query(ParcelSearchSource).filter_by( active=True).all() if not parcel_search_sources: parcel_search_sources = False server_search_form = ServerSearchForm() return render_template( 'editor.html', base_layers=base_layers, export_form=export_form, preview_layername=preview_layername, preview_features=preview_features, parcel_service=True, wfs_search_sources=wfs_search_sources, parcel_search_sources=parcel_search_sources, server_search_form=server_search_form, with_server=True, wms_search_url=current_app.config.geobox_state.config.get( 'web', 'wms_search_url'), is_local=request_is_local())