def post(): """When ready, this method will post contributions from users that choosen to use our internal message service instead of twitter, identica or whatever.""" audience = request.values.get('aid') newbuzz = Buzz( owner_nick=auth.authenticated_user().display_name, owner_avatar=u'', user=auth.authenticated_user(), content=request.values.get('message')[:300], type_=get_or_create(BuzzType, name=u'site')[0]) newbuzz.audience_id = audience session.commit() return msg.ok(_('Notice posted successfuly. Please wait a few while ' 'your message is approved.'))
def post(): """When ready, this method will post contributions from users that choosen to use our internal message service instead of twitter, identica or whatever.""" audience = request.values.get('aid') newbuzz = Buzz(owner_nick=auth.authenticated_user().display_name, owner_avatar=u'', user=auth.authenticated_user(), content=request.values.get('message')[:300], type_=get_or_create(BuzzType, name=u'site')[0]) newbuzz.audience_id = audience session.commit() return msg.ok( _('Notice posted successfuly. Please wait a few while ' 'your message is approved.'))
def _make_follow(obraid): follow = UserFollow() if authapi.is_authenticated(): follow.user = authapi.authenticated_user() follow.obra_id = int(obraid) return follow
def profile_passwd_json(): """Update the user password""" form = ChangePasswordForm() if form.validate_on_submit(): user = authapi.authenticated_user() user.set_password(form.password.data) dbsession.commit() # return msg.ok({ # 'data': _('Password updated successful'), # 'csrf': form.csrf.data, # }) flash(_(u'Password updated successful'), 'alert-success') return redirect(url_for('.profile')) else: # This field is special, it must be validated before anything. If it # doesn't work, the action must be aborted. # if not form.csrf_is_valid: # flash(_(u'Invalid csrf token'), 'alert-error') # return msg.error(_('Invalid csrf token'), 'InvalidCsrfToken') # Usual validation error # return utils.format_csrf_error(form, form.errors, 'ValidationError') for fd in form: if fd.errors: for er in fd.errors: flash(er, 'alert-error') return redirect(url_for('.profile'))
def contrib_json(): """Receives a user contribution and saves to the database This function will return a JSON format with the result of the operation. That can be successful or an error, if it finds any problem in data received or the lack of the authentication. """ if not auth.is_authenticated(): return msg.error(_(u'User not authenticated')) raise Exception('Not funny') form = ContribForm(csrf_enabled=False) if form.validate_on_submit(): Contrib(title=form.data['title'].encode('utf-8'), content=form.data['content'].encode('utf-8'), theme=form.data['theme'], user=auth.authenticated_user()) session.commit() # Returning the csrf data = {'data': _('Contribution received successful')} data.update({'csrf': form.csrf.data}) return msg.ok(data) else: return format_csrf_error(form, form.errors, 'ValidationError')
def profile(): """Shows the user profile form""" if not authapi.is_authenticated(): return redirect(url_for("index")) data = authapi.authenticated_user().metadata() print "DATA FOR PROFILE", data profile = social(ProfileForm, default=data) passwd = ChangePasswordForm() menus = fromcache("menuprincipal") or tocache( "menuprincipal", wordpress.exapi.getMenuItens(menu_slug="menu-principal") ) try: twitter_hash_cabecalho = utils.twitts() except KeyError: twitter_hash_cabecalho = "" return render_template( "profile.html", profile=profile, passwd=passwd, sidebar=wordpress.getSidebar, menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho, )
def _get_context(custom=None): theme_id = request.values.get('theme') page = request.values.get('page') pg = request.values.get('pg') govr = wordpress.govr ctx = {} # Style customization parameters ctx['hidesidebar'] = False ctx['hidesidebarright'] = False ctx['rclass'] = '' # Parameters from wordpress ctx['wordpress'] = wordpress ctx['theme'] = theme_id and govr.getTheme(theme_id) or '' ctx['page'] = page or '' ctx['pg'] = pg or '' # Info from authenticated users if auth.is_authenticated(): ctx['userstats'] = govr.getUserStats(auth.authenticated_user().id) # Update the default values ctx.update(custom or {}) return ctx
def results(rid, page=0): """Shows results about a single answer """ # Looking for the authenticated user user_id = auth.is_authenticated() and \ auth.authenticated_user().id or '' # Getting the contrib itself and all its related theme_idposts. The page # parameter is used to paginate referral query result. contrib = _format_contrib(wordpress.govr.getContrib(rid, user_id)) if contrib['category']: pagination, posts = wordpress.getPostsByCategory( cat=contrib['category'], page=page) else: pagination, posts = None, [] # Building the context to return the template return render_template( 'govresponde_results.html', **_get_context({ 'contrib': contrib, 'hidesidebar': True, 'rclass': 'result', 'referrals': posts, 'pagination': pagination, 'statusedicao': statusedicao, 'sidebar':wordpress.getSidebar }) )
def contrib_json(): """Receives a user contribution and saves to the database This function will return a JSON format with the result of the operation. That can be successful or an error, if it finds any problem in data received or the lack of the authentication. """ if not auth.is_authenticated(): return msg.error(_(u'User not authenticated')) raise Exception('Not funny') form = ContribForm(csrf_enabled=False) if form.validate_on_submit(): Contrib( title=form.data['title'].encode('utf-8'), content=form.data['content'].encode('utf-8'), theme=form.data['theme'], user=auth.authenticated_user()) session.commit() # Returning the csrf data = { 'data': _('Contribution received successful') } data.update({ 'csrf': form.csrf.data }) return msg.ok(data) else: return format_csrf_error(form, form.errors, 'ValidationError')
def validate_current_password(self, field): """Validates the current password of the logged in user""" hasher = phpass.PasswordHash(8, True) user = authenticated_user() if not hasher.check_password(field.data, user.password): raise ValidationError( _('The current password is wrong'))
def results(rid, page=0): """Shows results about a single answer """ # Looking for the authenticated user user_id = auth.is_authenticated() and \ auth.authenticated_user().id or '' # Getting the contrib itself and all its related theme_idposts. The page # parameter is used to paginate referral query result. contrib = _format_contrib(wordpress.govr.getContrib(rid, user_id)) if contrib['category']: pagination, posts = wordpress.getPostsByCategory( cat=contrib['category'], page=page) else: pagination, posts = None, [] # Building the context to return the template return render_template( 'govresponde_results.html', **_get_context({ 'contrib': contrib, 'hidesidebar': True, 'rclass': 'result', 'referrals': posts, 'pagination': pagination, 'statusedicao': statusedicao }) )
def profile_json(): """Validate the request of the update of a profile. This method will not operate in any user instance but the authenticated one. If there's nobody authenticated, there's no way to execute it successfuly. """ form = social(ProfileForm, False) if not form.validate_on_submit(): # This field is special, it must be validated before anything. If it # doesn't work, the action must be aborted. if not form.csrf_is_valid: return msg.error(_('Invalid csrf token'), 'InvalidCsrfToken') # Usual validation error return utils.format_csrf_error(form, form.errors, 'ValidationError') # Let's save the authenticated user's meta data mget = form.meta.get try: user = authapi.authenticated_user() except authapi.NobodyHome: return redirect(url_for('index')) # First, the specific ones email = mget('email') redologin = False if user.username == user.email and user.username != email \ and not (user.get_meta('twitteruser') or user.get_meta('facebookuser')): flash(_(u'You changed your email, please relogin.')) redologin = True user.username = email user.name = mget('name') user.email = email # Saving the thumbnail form.meta.pop('avatar') if bool(form.avatar.file): flike = form.avatar.file thumb = utils.thumbnail(flike, (48, 48)) form.meta['avatar'] = Upload.imageset.save( FileStorage(thumb, flike.filename, flike.name), 'thumbs/%s' % user.name[0].lower()) # And then, the meta ones, stored in `UserMeta' for key, val in form.meta.items(): user.set_meta(key, val) # return msg.ok({ # 'data': _('User profile updated successfuly'), # 'csrf': form.csrf.data, # }) flash(_(u'Profile update successful'), 'alert-success') if redologin: authapi.logout() return redirect(url_for('auth.login')) else: return redirect(url_for('.profile'))
def ismod(): ismoderador = False if authapi.is_authenticated(): user = authapi.authenticated_user() if user.email in conf.SEMINARIO_MODERADORES.split(","): ismoderador = True else: ismoderador = False return ismoderador
def ismod(): ismoderador = False if authapi.is_authenticated(): user = authapi.authenticated_user() if user.email in conf.SEMINARIO_MODERADORES.split(','): ismoderador = True else: ismoderador = False return ismoderador
def questions(): ctx = _get_context() theme = ctx['theme'] questions = [] sortby = request.values.get('sortby') or '?rand' #sortby = '?rand' # Looking for the authenticated user user_id = auth.is_authenticated() and \ auth.authenticated_user().id or '' # Discovering the theme id theme_id = theme and \ theme['id'] or '' # Finally, listing the questions that are able to receive votes. pagination = {} pagination['page'] = int(request.values.get('page', 0)) print "=================> wordpress.govr.getVotingContribs INI" questions_raw, count = wordpress.govr.getVotingContribs( theme_id, # theme id user_id, # user id pagination['page'], # page number sortby, # sortby '', # to '', # from CONTRIBS_PER_PAGE, # perpage ) print "=================> wordpress.govr.getVotingContribs FIM" # Pagination stuff count = int(count) pagination['pages'] = int(ceil(float(count) / CONTRIBS_PER_PAGE)) pagination['count'] = count # Small fix for the date value in the question content for i in questions_raw: question = _format_contrib(i) questions.append(question) try: twitter_hash_cabecalho = twitts() except KeyError: twitter_hash_cabecalho = "" ctx.update({ 'menu':wordpress.exapi.getMenuItens(menu_slug='menu-principal'), 'twitter_hash_cabecalho':twitter_hash_cabecalho, 'questions': questions, 'pagination': pagination, 'sortby': sortby, 'statusedicao': statusedicao }) return render_template('govresponde_questions.html', **ctx)
def contribs_user(): """Lists all contributions in the JSON format""" try: user = auth.authenticated_user() except auth.NobodyHome: return dumps([]) return dumps([ _format_contrib(i) for i in Contrib.query.filter_by().filter(Contrib.user == user) ])
def contribs_user(): """Lists all contributions in the JSON format""" try: user = auth.authenticated_user() except auth.NobodyHome: return dumps([]) return dumps([ _format_contrib(i) for i in Contrib.query .filter_by() .filter(Contrib.user==user)])
def seguir(obraid): emailto = "" obra = fromcache("obra-" + obraid) or tocache("obra-" + obraid, _get_obras(obraid=obraid)[0]) if not obra: print "Não achou a obra!" return abort(404) slug = obra['slug'] if request.form: follow = UserFollow() if authapi.is_authenticated(): follow.user = authapi.authenticated_user() emailto = follow.user.email follow.obra_id = int(obraid) if request.form.has_key('faceid'): follow.facebook_id = request.form['faceid'] if request.form.has_key('twitterid'): follow.twitter_id = request.form['twitterid'] if request.form.has_key('email'): follow.email = request.form['email'] emailto = follow.email dbsession.commit() if emailto: base_url = current_app.config['BASE_URL'] base_url = base_url if base_url[-1:] != '/' else base_url[:-1] #corta a barra final _dados_email = { 'titulo': obra['title'], 'link' : base_url + url_for('.obra',slug=slug), 'descricao' : Markup(obra['content']).striptags(), 'monitore_url': base_url + url_for('.index'), 'siteurl': base_url, } sendmail( current_app.config['SEGUIROBRA_SUBJECT'] % _dados_email, emailto, current_app.config['SEGUIROBRA_MSG'] % _dados_email ) return dumps({'status':'ok'}) else: return dumps({'status':'error'})
def seguir(obraid): emailto = "" obra = fromcache("obra-" + obraid) or tocache("obra-" + obraid, _get_obras(obraid=obraid)[0]) if not obra: print "Não achou a obra!" return abort(404) slug = obra['slug'] if request.form: follow = UserFollow() if authapi.is_authenticated(): follow.user = authapi.authenticated_user() emailto = follow.user.email follow.obra_id = int(obraid) if request.form.has_key('faceid'): follow.facebook_id = request.form['faceid'] if request.form.has_key('twitterid'): follow.twitter_id = request.form['twitterid'] if request.form.has_key('email'): follow.email = request.form['email'] emailto = follow.email dbsession.commit() if emailto: base_url = current_app.config['BASE_URL'] base_url = base_url if base_url[ -1:] != '/' else base_url[:-1] #corta a barra final _dados_email = { 'titulo': obra['title'], 'link': base_url + url_for('.obra', slug=slug), 'descricao': Markup(obra['content']).striptags(), 'monitore_url': base_url + url_for('.index'), 'siteurl': base_url, } sendmail(current_app.config['SEGUIROBRA_SUBJECT'] % _dados_email, emailto, current_app.config['SEGUIROBRA_MSG'] % _dados_email) return dumps({'status': 'ok'}) else: return dumps({'status': 'error'})
def send_json(): form = forms.QuestionForm(csrf_enabled=False) form.theme.choices = [(None, '----')] + \ [(i['id'], i['name']) for i in wordpress.govr.getThemes()] if form.validate_on_submit(): wordpress.govr.createContrib( form.data['title'], form.data['theme'], form.data['question'], auth.authenticated_user().id, '', 0, 0 ) return msg.ok(u'Contribution received successful') else: return format_csrf_error(form, form.errors, 'ValidationError')
def salvar_noticia_comite(): if request.method == 'POST': titulo = request.form['titulo'] noticia = request.form['noticia'] cn = ComiteNews() cn.title = unicode(titulo) cn.content = unicode(noticia) cn.user = authenticated_user() dbsession.commit() #Envia o email avisando que chegou uma nova contribuição sendmail(conf.COMITE_SUBJECT, conf.COMITE_TO_EMAIL, conf.COMITE_MSG % { 'titulo': titulo, 'noticia': noticia, }) return msg.ok(_(u'Thank you. Your contribution was successfuly sent.')) else: return msg.error(_(u'Method not allowed'))
def profile(): """Shows the user profile form""" if not authapi.is_authenticated(): return redirect(url_for('index')) data = authapi.authenticated_user().metadata() print "DATA FOR PROFILE", data profile = social(ProfileForm, default=data) passwd = ChangePasswordForm() menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') ) try: twitter_hash_cabecalho = utils.twitts() except KeyError: twitter_hash_cabecalho = "" return render_template( 'profile.html', profile=profile, passwd=passwd, sidebar=wordpress.getSidebar, menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho)
def question(qid): if wordpress.govr.contribIsAggregated(qid): abort(404) # Looking for the authenticated user user_id = auth.is_authenticated() and \ auth.authenticated_user().id or '' # Getting the contrib contrib = _format_contrib(wordpress.govr.getContrib(qid, user_id)) # Just making sure that the user is authorized to see the requested # contrib if contrib['status'] != 'approved': abort(404) return render_template( 'govresponde_question.html', **_get_context({ 'question': contrib, 'statusedicao': statusedicao }) )
def salvar_noticia_comite(): if request.method == 'POST': titulo = request.form['titulo'] noticia = request.form['noticia'] cn = ComiteNews() cn.title = unicode(titulo) cn.content = unicode(noticia) cn.user = authenticated_user() dbsession.commit() #Envia o email avisando que chegou uma nova contribuição sendmail( conf.COMITE_SUBJECT, conf.COMITE_TO_EMAIL, conf.COMITE_MSG % { 'titulo': titulo, 'noticia': noticia, } ) return msg.ok(_(u'Thank you. Your contribution was successfuly sent.')) else: return msg.error(_(u'Method not allowed'))
def extend_context(): """This function is a context processor. It injects variables such as `user' and `host' variable in all templates that will be rendered for this application""" context = {} # This will be used to bind socket.io client API to our # server. Without the port information. context['host'] = request.host.split(':')[0] # It's also useful to be able to access the configuration module # from some templates context['conf'] = conf # Time to add the `user' var try: context['user'] = authenticated_user() except NobodyHome: context['user'] = None # Job done! return context
def signup_continuation(): '''Show the second part of registration''' print "/signup/continuation/ ===========================" user = None username = None if authapi.is_authenticated() and not 'byconfirm' in session: print "esta logado, indo pro profile ===========================" return redirect(url_for('.profile')) elif 'byconfirm' in session: print "byconfirm in session =========================== ", session['byconfirm'] user = User.query.filter_by(username=session['byconfirm']).one() # if user.get_meta('twitteruser'): # username = user.get_meta('twitter') # else: # username = user.username username = user.username del session['byconfirm'] elif request.method == 'POST': print "vindo do post ===========================", request.form['email'], request.form['username'] if request.form['username']: user = User.query.filter_by(username=request.form['username']).one() else: user = User.query.filter_by(username=request.form['email']).one() username = user.username if user: print "tem user ============================", user data = user.metadata() data['social'] = ('facebookuser' in data and data['facebookuser']) or \ ('twitteruser' in data and data['twitteruser']) print "DATA DEFAULT", data form = social(SignupForm, default=data) else: print "NAO tem user ============================" return redirect(url_for('auth.login')) form = social(SignupForm) if 'password_confirmation' in form: #Remove not needed field del form.password_confirmation if request.method == 'POST' and form.validate_on_submit(): # user = authapi.authenticated_user() print "form validado ============================" meta = form.meta dget = meta.pop password = dget('password') fromsocial = form.social or \ ('facebookuser' in data and data['facebookuser']) or \ ('twitteruser' in data and data['twitteruser']) try: print "FROMSOCIAL", fromsocial authapi.login(user.username, password, fromsocial) except authapi.UserNotFound: flash(_(u'Wrong user or password'), 'alert-error') except authapi.UserAndPasswordMissmatch: flash(_(u'Wrong password'), 'alert-error') else: user = authapi.authenticated_user() # First, the specific ones # user.name = mget('name') # user.email = mget('email') # And then, the meta ones, stored in `UserMeta' for key, val in form.meta.items(): user.set_meta(key, val) flash(_(u'Your registration is complete'), 'alert-success') return redirect(url_for('auth.profile')) else: print "ERRO NO FORM VALIDATION", form.errors menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') ) try: twitter_hash_cabecalho = utils.twitts() except KeyError: twitter_hash_cabecalho = "" return render_template( 'signup_second.html', form=form, menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho, sidebar=wordpress.getSidebar, username=username )
def vote(obraid, slug, plus): """ O controle do voto é como segue: - obraid = É o id do item da timeline (post-filho) que está sendo votado - slug = É um md5 criado através do slug do post-filho - plus = É um md5 criado através do obraid juntamente com: -> 1 se for para somar voto -> -1 se for para dominuir voto """ ret = {} post = wordpress.getCustomPost(obraid, 'gdobra') # print "Post", post['id'], post['post_type'] post_slug = md5(post['slug']).hexdigest() slugok = True if post_slug == slug else False # print "SLUG===", slug, type(post_slug), post['slug'], type(post['slug']) md5_plus = md5(obraid + '1').hexdigest() md5_down = md5(obraid + '-1').hexdigest() vote_plus = True if md5_plus == plus else False vote_down = True if md5_down == plus else False # print "PLUS===", plus, md5_plus # print "DOWN===", plus, md5_down # print "Votando", slugok, vote_plus, vote_down item = "gdobra_" itemup = item + "voto_up" itemdown = item + "voto_down" itemscore = item + "voto_score" itemvoted = item + "users_voted" if 'custom_fields' in post: cfs = post['custom_fields'] # print "Custom Fields", [ f['value'] for f in cfs if f['key'] == itemvoted] score = [int(f['value']) for f in cfs if f['key'] == itemscore] votosup = [int(f['value']) for f in cfs if f['key'] == itemup] votosdown = [int(f['value']) for f in cfs if f['key'] == itemdown] users_voted = [f['value'] for f in cfs if f['key'] == itemvoted] score = score[0] if score else 0 votosup = votosup[0] if votosup else 0 votosdown = votosdown[0] if votosdown else 0 users_voted = users_voted[0] if users_voted else "" if vote_plus: score += 1 votosup += 1 else: score -= 1 votosdown += 1 ret['score'] = score feito = "" newcfs = [] for cf in cfs: if cf['key'] == itemscore: cf['value'] = score feito += ",%s" % itemscore newcfs.append(cf) if cf['key'] == itemup: cf['value'] = votosup feito += ",%s" % itemup newcfs.append(cf) if cf['key'] == itemdown: cf['value'] = votosdown feito += ",%s" % itemdown newcfs.append(cf) if itemscore not in feito: newcfs.append({'key': itemscore, 'value': score}) if itemup not in feito: newcfs.append({'key': itemup, 'value': votosup}) if itemdown not in feito: newcfs.append({'key': itemdown, 'value': votosdown}) # print "Custom Fields OK", newcfs #Grava o usuário que votou users_voted = users_voted + authapi.authenticated_user().username + "," newcfs.append({'key': itemvoted, 'value': users_voted}) # edit_post_id = wordpress.wp.editPost( # post_id=post['id'], # custom_fields = cfs # ) edit_post_id = wordpress.exapi.setPostCustomFields(post['id'], newcfs) return dumps(ret)
def vote(obraid, slug, plus): """ O controle do voto é como segue: - obraid = É o id do item da timeline (post-filho) que está sendo votado - slug = É um md5 criado através do slug do post-filho - plus = É um md5 criado através do obraid juntamente com: -> 1 se for para somar voto -> -1 se for para dominuir voto """ ret = {} post = wordpress.getCustomPost(obraid, 'gdobra') # print "Post", post['id'], post['post_type'] post_slug = md5(post['slug']).hexdigest() slugok = True if post_slug == slug else False # print "SLUG===", slug, type(post_slug), post['slug'], type(post['slug']) md5_plus = md5(obraid + '1').hexdigest() md5_down = md5(obraid + '-1').hexdigest() vote_plus = True if md5_plus == plus else False vote_down = True if md5_down == plus else False # print "PLUS===", plus, md5_plus # print "DOWN===", plus, md5_down # print "Votando", slugok, vote_plus, vote_down item = "gdobra_" itemup = item+"voto_up" itemdown = item+"voto_down" itemscore = item+"voto_score" itemvoted = item+"users_voted" if 'custom_fields' in post: cfs = post['custom_fields'] # print "Custom Fields", [ f['value'] for f in cfs if f['key'] == itemvoted] score = [ int(f['value']) for f in cfs if f['key'] == itemscore] votosup = [ int(f['value']) for f in cfs if f['key'] == itemup] votosdown = [ int(f['value']) for f in cfs if f['key'] == itemdown] users_voted = [ f['value'] for f in cfs if f['key'] == itemvoted] score = score[0] if score else 0 votosup = votosup[0] if votosup else 0 votosdown = votosdown[0] if votosdown else 0 users_voted = users_voted[0] if users_voted else "" if vote_plus: score += 1 votosup += 1 else: score -= 1 votosdown += 1 ret['score'] = score feito = "" newcfs = [] for cf in cfs : if cf['key'] == itemscore: cf['value'] = score feito+=",%s" % itemscore newcfs.append(cf) if cf['key'] == itemup: cf['value'] = votosup feito+=",%s" % itemup newcfs.append(cf) if cf['key'] == itemdown: cf['value'] = votosdown feito+=",%s" % itemdown newcfs.append(cf) if itemscore not in feito: newcfs.append({'key':itemscore, 'value':score}) if itemup not in feito: newcfs.append({'key':itemup, 'value':votosup}) if itemdown not in feito: newcfs.append({'key':itemdown, 'value':votosdown}) # print "Custom Fields OK", newcfs #Grava o usuário que votou users_voted = users_voted + authapi.authenticated_user().username + "," newcfs.append({'key':itemvoted, 'value':users_voted}) # edit_post_id = wordpress.wp.editPost( # post_id=post['id'], # custom_fields = cfs # ) edit_post_id = wordpress.exapi.setPostCustomFields(post['id'], newcfs) return dumps(ret)
r = {'status':'ok', 'message':'Sua contibuição foi aceita com sucesso. Verifique seu email para confirmar o cadastro.'} user_recent = True send_welcome_email(user) send_password(user.email, novasenha) except authapi.UserExistsUnconfirmed, e: r = {'status':'nok', 'message':u'Seu usuário precisa ser confirmado, veja seu email!'} return dumps(r) if telefone: user.set_meta('phone', telefone) dbsession.commit() else: r = {'status':'nok', 'message':u'É necessário informar uma senha ou dados para cadastro.'} else: print "JAH ESTAVA LOGADO!" user = authapi.authenticated_user() if authapi.is_authenticated() or user_recent: print ">>>>>>>>>>>> SALVANDO CONTRIBUIÇÃO ..." print user author_id = user.id if hasattr(user,'id') else user['id'] status = "pending" ultimo_status = wordpress.monitoramento.getUltimaRespostaGovObra(obra['id']) print "Achou o ultimo status publico da obra:" print ultimo_status if request.form['link'] :
} return dumps(r) if telefone: user.set_meta('phone', telefone) dbsession.commit() else: r = { 'status': 'nok', 'message': u'É necessário informar uma senha ou dados para cadastro.' } else: print "JAH ESTAVA LOGADO!" user = authapi.authenticated_user() if authapi.is_authenticated() or user_recent: print ">>>>>>>>>>>> SALVANDO CONTRIBUIÇÃO ..." print user author_id = user.id if hasattr(user, 'id') else user['id'] status = "pending" ultimo_status = wordpress.monitoramento.getUltimaRespostaGovObra( obra['id']) print "Achou o ultimo status publico da obra:" print ultimo_status if request.form['link']:
def index(): ctx = _get_context() theme = ctx['theme'] page = ctx['page'] pg = ctx['pg'] # pg = ctx['pg'] or 'resp' # Discovering the theme id theme_id = theme and \ theme['id'] or '' if pg <> '': if theme_id <> '': statusedicao = '' else: statusedicao = 'ultima' pagerender = 'govresponde_edicoesanteriores.html' else: return redirect( url_for('.questions')+"?theme=21" ) statusedicao = 'ultima' pagerender = 'govresponde_home.html' if pg == 'todos': statusedicao = '' # Getting the user id if the user is authenticated user_id = auth.is_authenticated() and \ auth.authenticated_user().id or '' # Finally, listing the questions that are able to receive votes. pagination = {} pagination['page'] = int(request.values.get('page', 0)) print 'xxxx === ', pagination['page'] # Querying the contribs ordenated by the answer date contribs = [] contribs_raw, count = wordpress.govr.getContribs( theme_id, user_id, pagination['page'], '-answerdate', '', '', 'responded', '', CONTRIBS_PER_PAGE, statusedicao) for i in contribs_raw: contribs.append(_format_contrib(i)) # Pagination stuff count = count pagination['pages'] = int(ceil(float(count) / CONTRIBS_PER_PAGE)) pagination['count'] = count #print "4 = ",datetime.datetime.now() # Yes, this is a hammer! This date value will be use to know which # question should be highlighted. # # The rule is actually quite simple. We have to aggregate all the # contribs that were published in the same day of the last published # one. #base_date = contribs[0]['answered_at'].strftime('%d/%m/%Y') base_date = contribs[0]['answered_at'].strftime('%d/%m/%Y') try: twitter_hash_cabecalho = twitts() except KeyError: twitter_hash_cabecalho = "" #govresponde_edicoesanteriores return render_template( pagerender, **_get_context({ 'contribs': contribs, 'count': count, 'menu':wordpress.exapi.getMenuItens(menu_slug='menu-principal'), 'twitter_hash_cabecalho':twitter_hash_cabecalho, 'base_date': base_date, 'statusedicao': statusedicao, 'pagination': pagination, 'pg' : pg, 'sidebar':wordpress.getSidebar }))
def index(): ctx = _get_context() theme = ctx['theme'] page = ctx['page'] pg = ctx['pg'] or 'resp' # Discovering the theme id theme_id = theme and \ theme['id'] or '' if pg <> '': if theme_id <> '': statusedicao = '' else: statusedicao = 'ultima' pagerender = 'govresponde_edicoesanteriores.html' else: statusedicao = 'ultima' pagerender = 'govresponde_home.html' if pg == 'todos': statusedicao = '' # Getting the user id if the user is authenticated user_id = auth.is_authenticated() and \ auth.authenticated_user().id or '' # Finally, listing the questions that are able to receive votes. pagination = {} pagination['page'] = int(request.values.get('page', 0)) print 'xxxx === ', pagination['page'] # Querying the contribs ordenated by the answer date contribs = [] contribs_raw, count = wordpress.govr.getContribs( theme_id, user_id, pagination['page'], '-answerdate', '', '', 'responded', '', CONTRIBS_PER_PAGE, statusedicao) for i in contribs_raw: contribs.append(_format_contrib(i)) # Pagination stuff count = count pagination['pages'] = int(ceil(float(count) / CONTRIBS_PER_PAGE)) pagination['count'] = count #print "4 = ",datetime.datetime.now() # Yes, this is a hammer! This date value will be use to know which # question should be highlighted. # # The rule is actually quite simple. We have to aggregate all the # contribs that were published in the same day of the last published # one. #base_date = contribs[0]['answered_at'].strftime('%d/%m/%Y') base_date = contribs[0]['answered_at'].strftime('%d/%m/%Y') try: twitter_hash_cabecalho = twitts() except KeyError: twitter_hash_cabecalho = "" #govresponde_edicoesanteriores return render_template( pagerender, **_get_context({ 'contribs': contribs, 'count': count, 'menu':wordpress.exapi.getMenuItens(menu_slug='menu-principal'), 'twitter_hash_cabecalho':twitter_hash_cabecalho, 'base_date': base_date, 'statusedicao': statusedicao, 'pagination': pagination, 'pg' : pg }))
def vote(qid): return str(wordpress.govr.contribVote( qid, auth.authenticated_user().id))
def signup_continuation(): """Show the second part of registration""" print "/signup/continuation/ ===========================" user = None username = None if authapi.is_authenticated() and not "byconfirm" in session: print "esta logado, indo pro profile ===========================" return redirect(url_for(".profile")) elif "byconfirm" in session: print "byconfirm in session =========================== ", session["byconfirm"] user = User.query.filter_by(username=session["byconfirm"]).one() # if user.get_meta('twitteruser'): # username = user.get_meta('twitter') # else: # username = user.username username = user.username del session["byconfirm"] elif request.method == "POST": print "vindo do post ===========================", request.form["email"], request.form["username"] if request.form["username"]: user = User.query.filter_by(username=request.form["username"]).one() else: user = User.query.filter_by(username=request.form["email"]).one() username = user.username if user: print "tem user ============================", user data = user.metadata() data["social"] = ("facebookuser" in data and data["facebookuser"]) or ( "twitteruser" in data and data["twitteruser"] ) print "DATA DEFAULT", data form = social(SignupForm, default=data) else: print "NAO tem user ============================" return redirect(url_for("auth.login")) form = social(SignupForm) if "password_confirmation" in form: # Remove not needed field del form.password_confirmation if request.method == "POST" and form.validate_on_submit(): # user = authapi.authenticated_user() print "form validado ============================" meta = form.meta dget = meta.pop password = dget("password") fromsocial = ( form.social or ("facebookuser" in data and data["facebookuser"]) or ("twitteruser" in data and data["twitteruser"]) ) try: print "FROMSOCIAL", fromsocial authapi.login(user.username, password, fromsocial) except authapi.UserNotFound: flash(_(u"Wrong user or password"), "alert-error") except authapi.UserAndPasswordMissmatch: flash(_(u"Wrong password"), "alert-error") else: user = authapi.authenticated_user() # First, the specific ones # user.name = mget('name') # user.email = mget('email') # And then, the meta ones, stored in `UserMeta' for key, val in form.meta.items(): user.set_meta(key, val) flash(_(u"Your registration is complete"), "alert-success") return redirect(url_for("auth.profile")) else: print "ERRO NO FORM VALIDATION", form.errors menus = fromcache("menuprincipal") or tocache( "menuprincipal", wordpress.exapi.getMenuItens(menu_slug="menu-principal") ) try: twitter_hash_cabecalho = utils.twitts() except KeyError: twitter_hash_cabecalho = "" return render_template( "signup_second.html", form=form, menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho, sidebar=wordpress.getSidebar, username=username, )
def signup_continuation(): '''Show the second part of registration''' print "/signup/continuation/ ===========================" user = None username = None if authapi.is_authenticated() and not 'byconfirm' in session: print "esta logado, indo pro profile ===========================" return redirect(url_for('.profile')) elif 'byconfirm' in session: print "byconfirm in session =========================== ", session['byconfirm'] user = User.query.filter_by(username=session['byconfirm']).one() # if user.get_meta('twitteruser'): # username = user.get_meta('twitter') # else: # username = user.username username = user.username del session['byconfirm'] elif request.method == 'POST': print "vindo do post ===========================", request.form['email'], request.form['username'] if request.form['username']: user = User.query.filter_by(username=request.form['username']).one() else: user = User.query.filter_by(username=request.form['email']).one() username = user.username if user: print "tem user ============================", user data = user.metadata() data['social'] = ('facebookuser' in data and data['facebookuser']) or \ ('twitteruser' in data and data['twitteruser']) print "DATA DEFAULT", data form = social(SignupForm, default=data) else: print "NAO tem user ============================" return redirect(url_for('auth.login')) form = social(SignupForm) if 'password_confirmation' in form: #Remove not needed field del form.password_confirmation if request.method == 'POST' and form.validate_on_submit(): # user = authapi.authenticated_user() print "form validado ============================" meta = form.meta dget = meta.pop password = dget('password') fromsocial = form.social or \ ('facebookuser' in data and data['facebookuser']) or \ ('twitteruser' in data and data['twitteruser']) try: print "FROMSOCIAL", fromsocial authapi.login(user.username, password, fromsocial) except authapi.UserNotFound: flash(_(u'Wrong user or password'), 'alert-error') except authapi.UserAndPasswordMissmatch: flash(_(u'Wrong password'), 'alert-error') else: user = authapi.authenticated_user() # First, the specific ones # user.name = mget('name') # user.email = mget('email') # And then, the meta ones, stored in `UserMeta' for key, val in form.meta.items(): user.set_meta(key, val) flash(_(u'Your registration is complete'), 'alert-success') return redirect(url_for('auth.profile')) else: print "ERRO NO FORM VALIDATION", form.errors menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') ) try: twitter_hash_cabecalho = utils.twitts() except KeyError: twitter_hash_cabecalho = "" return render_template( 'signup_second.html', form=form, menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho, username=username )