def new_comment(): """Posts new comments to the blog""" print "/new_comment/" if not is_authenticated(): resp = make_response(dumps({ 'status': 'error', 'msg': _(u'User not authenticated'), 'redirectTo': url_for('auth.login') })) # if request.form['content']: # resp.set_cookie('live_comment_save', request.form['content'].replace('\n','<br/>') ) return resp try: nao_exibir_nome = request.form['nao_exibir_nome'] except: nao_exibir_nome = "" try: post_id = request.form['comentar_em'] except: post_id = request.form['post_id'] try: wordpress.newComment( username=session['username'], password=session['password'], post_id=post_id, content=request.form['content'], nao_exibir_nome=nao_exibir_nome ) removecache("comentarios%s" % str(post_id)) return msg.ok(_(u'Thank you. Your comment was successfuly sent')) except xmlrpclib.Fault, err: return msg.error(_(err.faultString), code='CommentError')
def login(): """Renders the login form""" if authapi.is_authenticated(): return redirect(url_for('.profile')) # signup_process = g.signup_process if 'twitter_token' in session: del session['twitter_token'] next = request.args.get('next') or request.referrer if next and '/auth/' in next : next = "" print 'NEXT=', request.args.get('next') print 'NEXT=', next menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') ) try: twitter_hash_cabecalho = utils.twitts() except KeyError: twitter_hash_cabecalho = "" resp = make_response( render_template('login.html', next=next, # signup_process=signup_process, menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho ) ) resp.set_cookie('connect_type', '') return resp
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 login(): """Renders the login form""" if authapi.is_authenticated(): return redirect(url_for('.profile')) # signup_process = g.signup_process if 'twitter_token' in session: del session['twitter_token'] next = request.args.get('next') or request.referrer if next and '/auth/' in next : next = "" print 'NEXT=', request.args.get('next') print 'NEXT=', next menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') ) try: twitter_hash_cabecalho = utils.twitts() except KeyError: twitter_hash_cabecalho = "" resp = make_response( render_template('login.html', next=next, # signup_process=signup_process, menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho, sidebar=wordpress.getSidebar, ) ) resp.set_cookie('connect_type', '') return resp
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 post(pid): try: p = fromcache("post-%s" % str(pid)) or tocache("post-%s" % str(pid),wordpress.getPost(pid)) except: return abort(404) """View that renders a post template""" recent_posts = fromcache("recent_posts") or tocache("recent_posts", wordpress.getRecentPosts( post_status='publish', numberposts=4)) #Retorna a ultima foto inserida neste album. # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID) menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') ) cmts = fromcache("comentarios%s" % str(pid)) or tocache("comentarios%s" % str(pid), wordpress.getComments(status='approve',post_id=pid)) tags = fromcache("tags") or tocache("tags", wordpress.getTagCloud()) try: twitter_hash_cabecalho = twitts() except KeyError: twitter_hash_cabecalho = "" # live_comment_ = request.cookies.get('live_comment_save') return render_template( 'post.html', post=p, tags=tags, sidebar=wordpress.getSidebar, # live_comment_save=live_comment_, # picday=picday, twitter_hash_cabecalho=twitter_hash_cabecalho, menu=menus, comments=cmts, show_comment_form=is_authenticated(), recent_posts=recent_posts)
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 _make_follow(obraid): follow = UserFollow() if authapi.is_authenticated(): follow.user = authapi.authenticated_user() follow.obra_id = int(obraid) return follow
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 login(): """Renders the login form""" if authapi.is_authenticated(): return redirect(url_for(".profile")) # signup_process = g.signup_process if "twitter_token" in session: del session["twitter_token"] next = request.args.get("next") or request.referrer if next and "/auth/" in next: next = "" print "NEXT=", request.args.get("next") print "NEXT=", next menus = fromcache("menuprincipal") or tocache( "menuprincipal", wordpress.exapi.getMenuItens(menu_slug="menu-principal") ) try: twitter_hash_cabecalho = utils.twitts() except KeyError: twitter_hash_cabecalho = "" resp = make_response( render_template( "login.html", next=next, # signup_process=signup_process, menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho, sidebar=wordpress.getSidebar, ) ) resp.set_cookie("connect_type", "") return resp
def conselho(): """Renders a wordpress page special""" path = 'conselho-comunicacao' # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID) page = fromcache("page-%s" % path) or tocache( "page-%s" % path, wordpress.getPageByPath(path)) cmts = fromcache("cmts-page-%s" % path) or tocache( "cmts-page-%s" % path, wordpress.getComments( status='approve', post_id=page.data['id'], number=1000)) try: twitter_hash_cabecalho = twitts() except KeyError: twitter_hash_cabecalho = "" menus = fromcache('menuprincipal') or tocache( 'menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal')) return render_template( 'post.html', post=page, sidebar=wordpress.getSidebar, # picday=picday, twitter_hash_cabecalho=twitter_hash_cabecalho, comments=cmts, show_comment_form=is_authenticated(), categoria_contribuicao_text=categoria_contribuicao_text, menu=menus)
def new_comment(): """Posts new comments to the blog""" print "/new_comment/" if not is_authenticated(): resp = make_response( dumps({ 'status': 'error', 'msg': _(u'User not authenticated'), 'redirectTo': url_for('auth.login') })) # if request.form['content']: # resp.set_cookie('live_comment_save', request.form['content'].replace('\n','<br/>') ) return resp try: nao_exibir_nome = request.form['nao_exibir_nome'] except: nao_exibir_nome = "" try: post_id = request.form['comentar_em'] except: post_id = request.form['post_id'] try: wordpress.newComment(username=session['username'], password=session['password'], post_id=post_id, content=request.form['content'], nao_exibir_nome=nao_exibir_nome) removecache("comentarios%s" % str(post_id)) return msg.ok(_(u'Thank you. Your comment was successfuly sent')) except xmlrpclib.Fault, err: return msg.error(_(err.faultString), code='CommentError')
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 logout(): """Logs the user out and returns """ if not authapi.is_authenticated(): return redirect(url_for("index")) authapi.logout() next = request.values.get("next") app = request.values.get("app") menus = fromcache("menuprincipal") or tocache( "menuprincipal", wordpress.exapi.getMenuItens(menu_slug="menu-principal") ) try: twitter_hash_cabecalho = utils.twitts() except KeyError: twitter_hash_cabecalho = "" if next: print "NEXTT=", next return redirect(next) else: return render_template( "logout.html", menu=menus, app=app, twitter_hash_cabecalho=twitter_hash_cabecalho, voltar=request.referrer or "/", sidebar=wordpress.getSidebar, )
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 artigo_hierarquico(slug): """Renders a wordpress page special""" path = slug post_type = 'artigo-herarquico' # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID) post = fromcache("artigo-%s" % slug) or tocache("artigo-%s" % slug, wordpress.getCustomPostByPath(post_type,path)) # print '====================================================' # print post # print '====================================================' if not post['id']: return abort(404) total_artigos = [] total_comentarios = [] comentarios_separados = [] add_filhos_and_comments_to_post(post_type, post, total_artigos, total_comentarios, comentarios_separados) HABILITAR_SANFONA="false" HABILITAR_ABAS="false" HABILITAR_COMENTARIO_MESTRE="false" HABILITAR_COMENTARIO_FILHOS="false" TEMPLATE = "artigo_hierarquico.html" for cf in post['custom_fields']: if cf['key'] == 'artigo_hierarquico_comentario_master' and cf['value'] == '1': HABILITAR_COMENTARIO_MESTRE = 'true' if cf['key'] == 'artigo_hierarquico_comentarios_filhos' and cf['value'] == '1': HABILITAR_COMENTARIO_FILHOS = 'true' if cf['key'] == 'artigo_hierarquico_sanfona' and cf['value'] == '1': HABILITAR_SANFONA = 'true' if cf['key'] == 'artigo_hierarquico_abas' and cf['value'] == '1': HABILITAR_ABAS = 'true' TEMPLATE = "artigo_hierarquico_aba.html" try: twitter_hash_cabecalho = twitts() except KeyError: twitter_hash_cabecalho = "" menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') ) return render_template( TEMPLATE, post=post, wp=wordpress, total_artigos=sum(total_artigos), total_comentarios=sum(total_comentarios), todos_comentarios=comentarios_separados, sidebar=wordpress.getSidebar, HABILITAR_SANFONA=HABILITAR_SANFONA, HABILITAR_ABAS=HABILITAR_ABAS, HABILITAR_COMENTARIO_MESTRE=HABILITAR_COMENTARIO_MESTRE, HABILITAR_COMENTARIO_FILHOS=HABILITAR_COMENTARIO_FILHOS, twitter_hash_cabecalho=twitter_hash_cabecalho, show_comment_form=is_authenticated(), categoria_contribuicao_text=categoria_contribuicao_text ,menu=menus )
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 post_slug(slug): try: post = fromcache("post-%s" % slug) or tocache( "post-%s" % slug, wordpress.getPostByPath(slug)) if not post['id']: abort(404) except: abort(404) print '==============================================================================' print post print '==============================================================================' pid = post['id'] if 'the_date' not in post.keys(): # post['the_date'] = post['date']['date'].value post['the_date'] = datetime.datetime.strptime( post['date']['date'].value, '%Y%m%dT%H:%M:%S') """View that renders a post template""" recent_posts = fromcache("recent_posts") or tocache( "recent_posts", wordpress.getRecentPosts(post_status='publish', numberposts=4)) #Retorna a ultima foto inserida neste album. # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID) menus = fromcache('menuprincipal') or tocache( 'menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal')) # cmts = fromcache("comentarios_post_slug-%s"%slug) or tocache("comentarios_post_slug-%s"%slug, wordpress.getComments(status='approve',post_id=pid)) tags = fromcache("tags") or tocache("tags", wordpress.getTagCloud()) try: twitter_hash_cabecalho = twitts() except KeyError: twitter_hash_cabecalho = "" # live_comment_ = request.cookies.get('live_comment_save') # if live_comment_: # live_comment_ = live_comment_.replace('<br/>','\n') resp = make_response( render_template( 'post.html', post=post, tags=tags, # live_comment_save=live_comment_, sidebar=wordpress.getSidebar, # picday=picday, twitter_hash_cabecalho=twitter_hash_cabecalho, menu=menus, base_url=app.config['BASE_URL'], # comments=cmts, show_comment_form=is_authenticated(), recent_posts=recent_posts)) # resp.set_cookie('live_comment_save', "" ) return resp
def resendconfirmation(): if authapi.is_authenticated(): return redirect(url_for('.profile')) email = request.form['email'] user = User.query.filter_by(email=email).one() if user: utils.send_welcome_email(user) flash(_(u"The confirmation email was sent")) else: flash(_(u"User not found")) return redirect(url_for('auth.login'))
def post_slug(slug): try: post = fromcache("post-%s" % slug) or tocache("post-%s" % slug, wordpress.getPostByPath(slug)) if not post['id']: abort(404) except: abort(404) print '==============================================================================' print post print '==============================================================================' pid = post['id'] if 'the_date' not in post.keys(): # post['the_date'] = post['date']['date'].value post['the_date'] = datetime.datetime.strptime(post['date']['date'].value,'%Y%m%dT%H:%M:%S') """View that renders a post template""" recent_posts = fromcache("recent_posts") or tocache("recent_posts", wordpress.getRecentPosts( post_status='publish', numberposts=4)) #Retorna a ultima foto inserida neste album. # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID) menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') ) # cmts = fromcache("comentarios_post_slug-%s"%slug) or tocache("comentarios_post_slug-%s"%slug, wordpress.getComments(status='approve',post_id=pid)) tags = fromcache("tags") or tocache("tags", wordpress.getTagCloud()) try: twitter_hash_cabecalho = twitts() except KeyError: twitter_hash_cabecalho = "" # live_comment_ = request.cookies.get('live_comment_save') # if live_comment_: # live_comment_ = live_comment_.replace('<br/>','\n') resp = make_response( render_template( 'post.html', post=post, tags=tags, # live_comment_save=live_comment_, sidebar=wordpress.getSidebar, # picday=picday, twitter_hash_cabecalho=twitter_hash_cabecalho, menu=menus, base_url=app.config['BASE_URL'], # comments=cmts, show_comment_form=is_authenticated(), recent_posts=recent_posts) ) # resp.set_cookie('live_comment_save', "" ) return resp
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 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 logout(): """Logs the user out and returns """ if not authapi.is_authenticated(): return redirect(url_for('index')) authapi.logout() next = request.values.get('next') menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') ) try: twitter_hash_cabecalho = utils.twitts() except KeyError: twitter_hash_cabecalho = "" if next: print "NEXTT=", next return redirect(next) else: return render_template('logout.html', menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho, voltar=request.referrer or "/" )
def new_contribution(): """Posts new contributions on the page 'conselho-comunicacao' """ try: mostrar_nome = request.form['mostrar_nome'] except KeyError: mostrar_nome = 'N' if not is_authenticated(): return msg.error(_(u'User not authenticated')) try: print "\n\nMOSTRAR NOME!", mostrar_nome cid = wordpress.newComment( username=session['username'], password=session['password'], post_id=request.form['post_id'], content=request.form['content1'] or request.form['content2'], categoria_sugestao=request.form['categoria_sugestao'], mostrar_nome=mostrar_nome) return msg.ok(_(u'Thank you. Your contribution was successfuly sent.')) except xmlrpclib.Fault, err: return msg.error(_(err.faultString), code='CommentError')
def conselho(): """Renders a wordpress page special""" path = 'conselho-comunicacao' # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID) page = fromcache("page-%s" %path) or tocache("page-%s" %path, wordpress.getPageByPath(path) ) cmts = fromcache("cmts-page-%s" %path) or tocache("cmts-page-%s" %path, wordpress.getComments(status='approve',post_id=page.data['id'], number=1000)) try: twitter_hash_cabecalho = twitts() except KeyError: twitter_hash_cabecalho = "" menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') ) return render_template( 'post.html', post=page, sidebar=wordpress.getSidebar, # picday=picday, twitter_hash_cabecalho=twitter_hash_cabecalho, comments=cmts, show_comment_form=is_authenticated(), categoria_contribuicao_text=categoria_contribuicao_text ,menu=menus )
def new_contribution(): """Posts new contributions on the page 'conselho-comunicacao' """ try: mostrar_nome = request.form['mostrar_nome'] except KeyError : mostrar_nome = 'N' if not is_authenticated(): return msg.error(_(u'User not authenticated')) try: print "\n\nMOSTRAR NOME!", mostrar_nome cid = wordpress.newComment( username=session['username'], password=session['password'], post_id=request.form['post_id'], content=request.form['content1'] or request.form['content2'], categoria_sugestao=request.form['categoria_sugestao'], mostrar_nome=mostrar_nome ) return msg.ok(_(u'Thank you. Your contribution was successfuly sent.')) except xmlrpclib.Fault, err: return msg.error(_(err.faultString), code='CommentError')
def post(pid): try: p = fromcache("post-%s" % str(pid)) or tocache("post-%s" % str(pid), wordpress.getPost(pid)) except: return abort(404) """View that renders a post template""" recent_posts = fromcache("recent_posts") or tocache( "recent_posts", wordpress.getRecentPosts(post_status='publish', numberposts=4)) #Retorna a ultima foto inserida neste album. # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID) menus = fromcache('menuprincipal') or tocache( 'menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal')) cmts = fromcache("comentarios%s" % str(pid)) or tocache( "comentarios%s" % str(pid), wordpress.getComments(status='approve', post_id=pid)) tags = fromcache("tags") or tocache("tags", wordpress.getTagCloud()) try: twitter_hash_cabecalho = twitts() except KeyError: twitter_hash_cabecalho = "" # live_comment_ = request.cookies.get('live_comment_save') return render_template( 'post.html', post=p, tags=tags, sidebar=wordpress.getSidebar, # live_comment_save=live_comment_, # picday=picday, twitter_hash_cabecalho=twitter_hash_cabecalho, menu=menus, comments=cmts, show_comment_form=is_authenticated(), recent_posts=recent_posts)
def logout(): """Logs the user out and returns """ if not authapi.is_authenticated(): return redirect(url_for('index')) authapi.logout() next = request.values.get('next') app = request.values.get('app') menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') ) try: twitter_hash_cabecalho = utils.twitts() except KeyError: twitter_hash_cabecalho = "" if next: print "NEXTT=", next return redirect(next) else: return render_template('logout.html', menu=menus, app=app, twitter_hash_cabecalho=twitter_hash_cabecalho, voltar=request.referrer or "/", sidebar=wordpress.getSidebar, )
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 contribui(slug): obra = fromcache("obra-" + slug) or tocache("obra-" + slug, _get_obras(slug)[0]) if not obra: return abort(404) r = {'status':'ok', 'message':'Sua contibuição foi aceita com sucesso'} user_recent = False if not authapi.is_authenticated(): # r = {'status':'not_logged'} """ Se não está autenticado, tenta achar o usuário pelo email, e acessar com a senha inserida no formulario. Se não, cadastra o camarada, com o nome e email informados, gerando uma senha para ele e enviando o email de boas vindas. """ email = request.form['email'] if request.form['senha']: #Informou a senha do cadastro já existente # username = email # senha = request.form['senha'] #Efetua o login print "Usuario e senha informado... logando!" username = request.values.get('email') senha = request.values.get('senha') print "tentando logar com", username, senha try: user = authapi.login(username, senha) r = {'status':'ok', 'message':'Sua contibuição foi aceita com sucesso', 'refresh': True} except authapi.UserNotFound: r = {'status':'nok', 'message':_(u'Wrong user or password')} return dumps(r) except authapi.UserAndPasswordMissmatch: r = {'status':'nok', 'message':_(u'Wrong user or password')} return dumps(r) elif request.form['nome']: print "Nome informado... cadastrando..." #Informou a senha para cadastro nome = request.form['nome'] telefone = request.form['telefone'] if 'telefone' in request.form else "" novasenha = request.form['newPassword'] if 'newPassword' in request.form else "" if not novasenha: # novasenha = "gabinetedigital" novasenha = ''.join(random.choice(string.printable) for x in range(8)) # print nome, '-', email, '-', novasenha try: user = authapi.create_user(nome, email, unicode(novasenha), email) 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.'}
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']: #Contribuição em texto print "COM VIDEO -------------"
def signup(): """Renders the signup form""" if authapi.is_authenticated(): return redirect(url_for('.profile')) # default_data=None ret_code = -1 form = social(SignupForm) print "CADASTRANDO" #form = SignupForm() fromsocial = request.cookies.get('connect_type') in ('social_f','social_t') form.social = fromsocial print "VALIDANDO" if request.method == 'POST' and form.validate_on_submit(): print "VALIDADO!" try: meta = form.meta dget = meta.pop if fromsocial: print "\nsenha fromsocial" password = "" else: password = dget('password') print "\nsenha", password # Finally, it's time to create the user email = dget('email') username = email if request.cookies.get('connect_type') == 'social_t': username = session['tmp_twitter_id'] # if request.cookies.get('connect_type') == 'social_f': # username = dget('fbid') # print "FACEBOOK ID =", username user = authapi.create_user( dget('name'), username, password, email, form.meta, dget('receive_sms'), dget('receive_email') ) if fromsocial: if request.cookies.get('connect_type') == 'social_t': user.set_meta('twitter', session['tmp_twitter_id']) user.set_meta('twitteruser', True) dbsession.commit() if request.cookies.get('connect_type') == 'social_f': user.set_meta('facebookuser', True) dbsession.commit() utils.send_welcome_email(user) flash(_(u'Your user was registered with successful!'), 'alert-success') ret_code = 0 except authapi.UserExists: flash( _(u'User already exists'), 'alert-error') ret_code = 1 except authapi.UserExistsUnconfirmed: flash( _(u'User already exists, but need confirmation'), 'alert-error') ret_code = 4 except authapi.EmailAddressExists: flash(_(u'The email address informed is being used by another person'), 'alert-error') ret_code = 2 else: if request.method == 'POST' : print form.errors # for errorMessages, fieldName in enumerate(form.errors): # print errorMessages, fieldName # for err in errorMessages: # # do something with your errorMessages for fieldName # flash( "%s - %s" % (fieldName,err),'alert-error') flash(_(u'Correct the validation errors and resend'),'alert-error') ret_code = 3 tos = fromcache('tossigin') or tocache('tossigin',wordpress.getPageByPath('tos')) rm = fromcache('moresigin') or tocache('moresigin',wordpress.getPageByPath('signup-read-more')) 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.html', form=form, readmore=rm,tos=tos, menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho, ret_code=ret_code )
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 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 )
def artigo_hierarquico(slug): """Renders a wordpress page special""" path = slug post_type = 'artigo-herarquico' # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID) post = fromcache("artigo-%s" % slug) or tocache( "artigo-%s" % slug, wordpress.getCustomPostByPath(post_type, path)) # print '====================================================' # print post # print '====================================================' if not post['id']: return abort(404) total_artigos = [] total_comentarios = [] comentarios_separados = [] add_filhos_and_comments_to_post(post_type, post, total_artigos, total_comentarios, comentarios_separados) HABILITAR_SANFONA = "false" HABILITAR_ABAS = "false" HABILITAR_COMENTARIO_MESTRE = "false" HABILITAR_COMENTARIO_FILHOS = "false" TEMPLATE = "artigo_hierarquico.html" for cf in post['custom_fields']: if cf['key'] == 'artigo_hierarquico_comentario_master' and cf[ 'value'] == '1': HABILITAR_COMENTARIO_MESTRE = 'true' if cf['key'] == 'artigo_hierarquico_comentarios_filhos' and cf[ 'value'] == '1': HABILITAR_COMENTARIO_FILHOS = 'true' if cf['key'] == 'artigo_hierarquico_sanfona' and cf['value'] == '1': HABILITAR_SANFONA = 'true' if cf['key'] == 'artigo_hierarquico_abas' and cf['value'] == '1': HABILITAR_ABAS = 'true' TEMPLATE = "artigo_hierarquico_aba.html" try: twitter_hash_cabecalho = twitts() except KeyError: twitter_hash_cabecalho = "" menus = fromcache('menuprincipal') or tocache( 'menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal')) return render_template( TEMPLATE, post=post, wp=wordpress, total_artigos=sum(total_artigos), total_comentarios=sum(total_comentarios), todos_comentarios=comentarios_separados, sidebar=wordpress.getSidebar, HABILITAR_SANFONA=HABILITAR_SANFONA, HABILITAR_ABAS=HABILITAR_ABAS, HABILITAR_COMENTARIO_MESTRE=HABILITAR_COMENTARIO_MESTRE, HABILITAR_COMENTARIO_FILHOS=HABILITAR_COMENTARIO_FILHOS, twitter_hash_cabecalho=twitter_hash_cabecalho, show_comment_form=is_authenticated(), categoria_contribuicao_text=categoria_contribuicao_text, menu=menus)
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 signup(): """Renders the signup form""" if authapi.is_authenticated(): return redirect(url_for('.profile')) # default_data=None ret_code = -1 form = social(SignupForm) print "CADASTRANDO" #form = SignupForm() fromsocial = request.cookies.get('connect_type') in ('social_f','social_t') form.social = fromsocial print "VALIDANDO" if request.method == 'POST' and form.validate_on_submit(): print "VALIDADO!" try: meta = form.meta dget = meta.pop if fromsocial: print "\nsenha fromsocial" password = "" else: password = dget('password') print "\nsenha", password # Finally, it's time to create the user email = dget('email') username = email if request.cookies.get('connect_type') == 'social_t': username = session['tmp_twitter_id'] # if request.cookies.get('connect_type') == 'social_f': # username = dget('fbid') # print "FACEBOOK ID =", username user = authapi.create_user( dget('name'), username, password, email, form.meta, dget('receive_sms'), dget('receive_email') ) if fromsocial: if request.cookies.get('connect_type') == 'social_t': user.set_meta('twitter', session['tmp_twitter_id']) user.set_meta('twitteruser', True) dbsession.commit() if request.cookies.get('connect_type') == 'social_f': user.set_meta('facebookuser', True) dbsession.commit() utils.send_welcome_email(user) flash(_(u'Your user was registered with successful!'), 'alert-success') ret_code = 0 except authapi.UserExists: flash( _(u'User already exists'), 'alert-error') ret_code = 1 except authapi.UserExistsUnconfirmed: flash( _(u'User already exists, but need confirmation'), 'alert-error') ret_code = 4 except authapi.EmailAddressExists: flash(_(u'The email address informed is being used by another person'), 'alert-error') ret_code = 2 else: if request.method == 'POST' : print form.errors # for errorMessages, fieldName in enumerate(form.errors): # print errorMessages, fieldName # for err in errorMessages: # # do something with your errorMessages for fieldName # flash( "%s - %s" % (fieldName,err),'alert-error') flash(_(u'Correct the validation errors and resend'),'alert-error') ret_code = 3 tos = fromcache('tossigin') or tocache('tossigin',wordpress.getPageByPath('tos')) rm = fromcache('moresigin') or tocache('moresigin',wordpress.getPageByPath('signup-read-more')) 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.html', form=form, readmore=rm,tos=tos, menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho, sidebar=wordpress.getSidebar, ret_code=ret_code )
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'] : #Contribuição em texto print "COM VIDEO -------------" new_post_id = wordpress.wp.newPost(
def contribui(slug): obra = fromcache("obra-" + slug) or tocache("obra-" + slug, _get_obras(slug)[0]) if not obra: return abort(404) r = {'status': 'ok', 'message': 'Sua contibuição foi aceita com sucesso'} user_recent = False if not authapi.is_authenticated(): # r = {'status':'not_logged'} """ Se não está autenticado, tenta achar o usuário pelo email, e acessar com a senha inserida no formulario. Se não, cadastra o camarada, com o nome e email informados, gerando uma senha para ele e enviando o email de boas vindas. """ email = request.form['email'] if request.form['senha']: #Informou a senha do cadastro já existente # username = email # senha = request.form['senha'] #Efetua o login print "Usuario e senha informado... logando!" username = request.values.get('email') senha = request.values.get('senha') print "tentando logar com", username, senha try: user = authapi.login(username, senha) r = { 'status': 'ok', 'message': 'Sua contibuição foi aceita com sucesso', 'refresh': True } except authapi.UserNotFound: r = {'status': 'nok', 'message': _(u'Wrong user or password')} return dumps(r) except authapi.UserAndPasswordMissmatch: r = {'status': 'nok', 'message': _(u'Wrong user or password')} return dumps(r) elif request.form['nome']: print "Nome informado... cadastrando..." #Informou a senha para cadastro nome = request.form['nome'] telefone = request.form[ 'telefone'] if 'telefone' in request.form else "" novasenha = request.form[ 'newPassword'] if 'newPassword' in request.form else "" if not novasenha: # novasenha = "gabinetedigital" novasenha = ''.join( random.choice(string.printable) for x in range(8)) # print nome, '-', email, '-', novasenha try: user = authapi.create_user(nome, email, unicode(novasenha), email) 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.' }
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, )