def get_student(self, email, name, phone): if self.current_user and self.current_user.email == email: try: return Subscriber.objects.get(user=self.current_user) except: self.cart.addlog("Creating a new student", save=False) return Subscriber.objects.create( name=name, email=email, phone=phone, user=self.current_user ) try: user = User.objects.get(email=email) except: self.cart.addlog("Creating new user %s" % email) user = User.objects.create( name=name, email=email, password="" ) # autenticar e mandar email password login_user(user) return Subscriber.objects.create( name=name, email=email, phone=phone, user=user )
def post(self): form = LoginForm() if form.validate_on_submit(): login_user(form.user, remember=False) after_this_request(_commit) return _make_response(form, include_auth_token=True)
def login_handler(response, provider, query): """Shared method to handle the signin process""" connection = _datastore.find_connection(**query) if connection: after_this_request(_commit) user = connection.user login_user(user) key = _social.post_oauth_login_session_key redirect_url = session.pop(key, get_post_login_redirect()) login_completed.send(current_app._get_current_object(), provider=provider, user=user) return redirect(redirect_url) login_failed.send(current_app._get_current_object(), provider=provider, oauth_response=response) #_security.login_manager.login_view = "user.register" #next = get_url(_security.login_manager.login_view) next = url_for('user.register', provider_id=provider.id, login_failed=1) msg = '%s account not associated with an existing user' % provider.name #if session['login_attempt']: # session['failed_login_connection'] = dict(dummy="dummy") do_flash(msg, 'danger' if session['login_attempt'] else 'info') return redirect(next)
def login_handler(response, provider, query): """Shared method to handle the signin process""" connection = _datastore.find_connection(**query) if connection: after_this_request(_commit) user = connection.user login_user(user) key = _social.post_oauth_login_session_key redirect_url = session.pop(key, get_post_login_redirect()) login_completed.send(current_app._get_current_object(), provider=provider, user=user) return redirect(redirect_url) login_failed.send(current_app._get_current_object(), provider=provider, oauth_response=response) next = get_url(_security.login_manager.login_view) msg = '%s account not associated with an existing user' % provider.name do_flash(msg, 'error') return redirect(next)
def google_authorized(): check_oauth_provider(google) resp = google.authorized_response() if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) session['google_token'] = (resp['access_token'], '') resp = google.get('userinfo') user = user_get_or_create( resp.data['email'], resp.data['given_name'], resp.data['family_name'], 'google', resp.data['email']) if user.is_active: login_user(user, remember=True) elif user.deleted: flash('This username has been deleted') else: flash('This account is disabled') return redirect(url_for('index'))
def get_student(self, email, name, phone): if self.current_user and self.current_user.email == email: try: return Subscriber.objects.get(user=self.current_user) except: self.cart.addlog("Creating a new student", save=False) return Subscriber.objects.create(name=name, email=email, phone=phone, user=self.current_user) try: user = User.objects.get(email=email) except: self.cart.addlog("Creating new user %s" % email) user = User.objects.create(name=name, email=email, password="") # autenticar e mandar email password login_user(user) return Subscriber.objects.create(name=name, email=email, phone=phone, user=user)
def facebook_authorized(): check_oauth_provider(facebook) resp = facebook.authorized_response() if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) if isinstance(resp, OAuthException): return 'Access denied: %s' % resp.message session['facebook_oauth_token'] = (resp['access_token'], '') resp = facebook.get('/me') user = user_get_or_create( resp.data['email'], resp.data['first_name'], resp.data['last_name'], 'facebook', resp.data['id']) if user.is_active: login_user(user, remember=True) elif user.deleted: flash('This username has been deleted') else: flash('This account is disabled') return redirect(url_for('index'))
def oauth_handler(resp): app = current_app oauth_app = get_oauth_app(provider) if not oauth_app: return "Access denied: oauth app not found" oauth_app.tokengetter( lambda: session.get("oauth_" + provider + "_token")) if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description']) session["oauth_" + provider + "_token"] = (resp['access_token'], '') data = app.config.get("OAUTH", {}).get(provider) me = oauth_app.get(data.get('_info_endpoint')) if not any([me.data.get('verified'), me.data.get('verified_email')]): return "Access denied: email not verified" email = me.data.get('email') name = me.data.get('name') provider_user_id = me.data.get('id') profile_url = me.data.get('link') access_token = resp['access_token'] try: user = User.objects.get(email=email) except User.DoesNotExist: user = User(name=name, email=email, username=User.generate_username(email)) user.save() try: connection = Connection.objects.get( user_id=str(user.id), provider_id=provider, ) connection.access_token = access_token connection.save() except Connection.DoesNotExist: connection = Connection(user_id=str(user.id), provider_id=provider, provider_user_id=provider_user_id, profile_url=profile_url, access_token=access_token) connection.save() login_user(user) _next = request.args.get( 'next', request.referrer) or session.get('next') or app.config.get( 'OAUTH_POST_LOGIN', "/") return redirect(_next)
def _check_json_auth(): security = current_app.extensions['security'] auth = request.get_json() user = security.datastore.find_user(email=auth['email']) if user and utils.verify_and_update_password(auth['password'], user): utils.login_user(user) return True return False
def on_login_failed(sender, provider, oauth_response): connection_values = get_connection_values_from_oauth_response( provider, oauth_response) ds = app.security.datastore email = connection_values.pop('email', None) user = ds.create_user(email=email) ds.commit() connection_values['user_id'] = user.id connect_handler(connection_values, provider) login_user(user) db.session.commit()
def oauth_handler(resp): app = current_app oauth_app = get_oauth_app(provider) if not oauth_app: return "Access denied: oauth app not found" oauth_app.tokengetter(lambda: session.get("oauth_" + provider + "_token")) if resp is None: return "Access denied: reason=%s error=%s" % ( request.args["error_reason"], request.args["error_description"], ) session["oauth_" + provider + "_token"] = (resp["access_token"], "") data = app.config.get("OAUTH", {}).get(provider) me = oauth_app.get(data.get("_info_endpoint")) if not any([me.data.get("verified"), me.data.get("verified_email")]): return "Access denied: email not verified" email = me.data.get("email") name = me.data.get("name") provider_user_id = me.data.get("id") profile_url = me.data.get("link") access_token = resp["access_token"] try: user = User.objects.get(email=email) except User.DoesNotExist: user = User(name=name, email=email, username=User.generate_username(email)) user.save() try: connection = Connection.objects.get(user_id=str(user.id), provider_id=provider) connection.access_token = access_token connection.save() except Connection.DoesNotExist: connection = Connection( user_id=str(user.id), provider_id=provider, provider_user_id=provider_user_id, profile_url=profile_url, access_token=access_token, ) connection.save() login_user(user) next = ( request.args.get("next", request.referrer) or session.get("next") or app.config.get("OAUTH_POST_LOGIN", "/") ) return redirect(next)
def login(**kwargs): # Make sure username and password are there if((kwargs['email'] is not None) and (kwargs['password'] is not None)): user = models.User.query.filter_by(email=kwargs['email']).first() if(user.password == kwargs['password']): # Sweet, this is some right shit!! utils.login_user(user, remember=None) return {"success": True, "user": {"email": kwargs['email']}} else: return {"success": False} return {}
def index(self): login_user_form = LoginForm() if login_user_form.validate_on_submit(): user = user_datastore.get_user(login_user_form.email.data) if verify_and_update_password(login_user_form.password.data, user): login_user(user, login_user_form.remember.data) return self.render( 'admin/master.html') #redirect(url_for('indexview.index')) #self._template_args['login_user_form'] = login_user_form return render_template('members.html', login_user_form=login_user_form) #class NewsPostView(sqla.ModelView): # column_list = ['title', 'content', 'date', 'live'] # column_editable_list = ('live',) # form_columns = ['title', 'content'] # form_widget_args = { # 'content': { # 'rows': 15 # } # } # def is_accessible(self): # return current_user.is_authenticated #def get_save_return_url(self, model, is_created): # return url_for('newspost.index_view') #def _handle_view(self, name, **kwargs): # if not self.is_accessible(): # return redirect(url_for('loginview.index', next=request.url)) # def __init__(self, session, **kwargs): # super(NewsPostView, self).__init__(NewsPost, session, **kwargs) #class CategoryView(sqla.ModelView): # form_columns = ['name'] # column_labels = dict(name='Category') # def is_accessible(self): # return current_user.is_authenticated #def _handle_view(self, name, **kwargs): # if not self.is_accessible(): # return redirect(url_for('loginview.index', next=request.url)) # def __init__(self, session, **kwargs): # super(CategoryView, self).__init__(Category, session, **kwargs)
def index(self): login_user_form = LoginForm() if login_user_form.validate_on_submit(): user = user_datastore.get_user(login_user_form.email.data) if verify_and_update_password(login_user_form.password.data, user): login_user(user, login_user_form.remember.data) return self.render('admin/master.html')#redirect(url_for('indexview.index')) #self._template_args['login_user_form'] = login_user_form return render_template('members.html', login_user_form=login_user_form) #class NewsPostView(sqla.ModelView): # column_list = ['title', 'content', 'date', 'live'] # column_editable_list = ('live',) # form_columns = ['title', 'content'] # form_widget_args = { # 'content': { # 'rows': 15 # } # } # def is_accessible(self): # return current_user.is_authenticated #def get_save_return_url(self, model, is_created): # return url_for('newspost.index_view') #def _handle_view(self, name, **kwargs): # if not self.is_accessible(): # return redirect(url_for('loginview.index', next=request.url)) # def __init__(self, session, **kwargs): # super(NewsPostView, self).__init__(NewsPost, session, **kwargs) #class CategoryView(sqla.ModelView): # form_columns = ['name'] # column_labels = dict(name='Category') # def is_accessible(self): # return current_user.is_authenticated #def _handle_view(self, name, **kwargs): # if not self.is_accessible(): # return redirect(url_for('loginview.index', next=request.url)) # def __init__(self, session, **kwargs): # super(CategoryView, self).__init__(Category, session, **kwargs)
def setup(): form = forms.ExtendedRegisterForm() if form.validate_on_submit(): flash(_("User %(username)s created", username=form.email.data), "success") admin_role = user_datastore.find_or_create_role('admin') user_role = user_datastore.find_or_create_role('user') user = user_datastore.create_user(email=form.email.data, password=encrypt_password(form.password.data), locale=form.locale.data, active=1, roles=[admin_role, user_role]) user_datastore.commit() login_user(user) return redirect(url_for('settings')) if not db.session.query(models.User).first(): return render_template('setup.html', form=form, title=_('Setup'), data_dir=config.DATA_DIR) else: return redirect(url_for("importer"))
def login(): form = LoginForm() form.next.data = request.values.get('next') or request.referrer if form.validate_on_submit(): current_app.logger.info(form.data) email = form.email.data.strip() user = user_datastore.get_user(email) if not user: flash("You don't have a user account yet") return redirect(url_for('mylearning.index')) login_user(user) # TODO check next is valid return redirect(form.next.data) return render_template('login.html', form=form)
def handle_login(): form = LoginForm(request.form) possible_match = User.query.filter(User.email == form.email.data).first() if not possible_match: flash('Login invalid') return redirect('/login') #store verify_password in variable so I can step into function with pdb elif hashlib.sha512(form.password.data).hexdigest() \ == possible_match.password: login_user(possible_match) return redirect('/home') else: flash('Login invalid') return redirect('/login')
def dispatch_request(self): form = forms.LoginForm() if form.validate_on_submit(): utils.login_user(form.user, remember=form.remember.data) flask.after_this_request(security_views._commit) return flask.redirect(utils.get_post_login_redirect()) form.next.data = ( utils.get_url(flask.request.args.get('next')) or utils.get_url(flask.request.form.get('next')) or '' ) return flask.render_template('login.html', form=form)
def authenticate(username, password): user = _datastore.get_user(username) if user and verify_and_update_password(password, user) and user.roles: _log.info("%s authenticated successfully, logging in", username) login_user(user) user.save() #Saving just in case to make sure the login stats are tracked. _request_ctx_stack.top.current_user = user return user if not user: _log.warn("Authentication failed; unknown username %s", username) else: _log.warn("Authentication failed; invalid password for %s", username) if not user.roles: _log.warn("Authentication failed; No user roles found.")
def blender_id_authorized(): check_oauth_provider(blender_id) resp = blender_id.authorized_response() if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) if isinstance(resp, OAuthException): return 'Access denied: %s' % resp.message session['blender_id_oauth_token'] = (resp['access_token'], '') resp = blender_id.get('user') user = user_get_or_create( resp.data['email'], resp.data['first_name'], resp.data['last_name'], 'blender-id', resp.data['id']) if user.is_active: login_user(user, remember=True) elif user.deleted: flash('This username has been deleted') return redirect(url_for('index')) else: flash('This account is disabled') return redirect(url_for('index')) # Update or create roles for role, is_assigned in resp.data['roles'].items(): r = user_datastore.find_or_create_role(role) if is_assigned: user_datastore.add_role_to_user(user, r) else: user_datastore.remove_role_from_user(user, r) db.session.commit() if not user.first_name or not user.last_name: if not user.username: flash('Please set your first and last name or pick a username') return redirect(url_for('settings.profile')) return redirect(url_for('index'))
def authorized(): resp = youckan.authorized_response() if resp is None or isinstance(resp, OAuthException): # TODO: better error handling abort(403) session['youckan.token'] = (resp['access_token'], '') response = youckan.get('me') data = response.data user = datastore.find_user(slug=data['slug']) # TODO: use user id instead if not user: user = datastore.create_user( slug=data['slug'], first_name=data['first_name'], last_name=data['last_name'], email=data['email'], avatar_url=data['profile'].get('avatar') or None, website=data['profile'].get('website') or None, about=data['profile'].get('about') or None ) else: user.first_name = data['first_name'] user.last_name = data['last_name'] user.email = data['email'] user.avatar_url = data['profile'].get('avatar') or None user.website = data['profile'].get('website') or None user.about = data['profile'].get('about') or None admin_role = datastore.find_or_create_role('admin') if data['is_superuser'] and not user.has_role(admin_role): datastore.add_role_to_user(user, admin_role) if not user.is_active() and data['is_active']: user.active = True user.save() login_user(user) redirect_to = url_for('site.home') if 'state' in request.args: state = request.args.get('state') decoded_state = json.loads(b64decode(state)) redirect_to = decoded_state.get('next_url', redirect_to) return redirect(redirect_to)
def from_profile(cls, user, profile): provider = profile.data["provider"] if not user or user.is_anonymous(): # Twiiter does not provide email if not provider == 'Twitter': email = profile.data.get("email") if not email: msg = "Cannot create new user, authentication provider did not provide email" logging.warning(msg) raise Exception(_(msg)) conflict = User.query.filter(User.email == email).first() # User already registered with email if conflict: login_user(conflict) connection = cls(user_id=conflict.id, **profile.data) db.session.add(connection) db.session.commit() return connection else: username = profile.data.get("username") email = username + "@fox.net" now = datetime.datetime.now() password = password_generator(16) user = User( email=email, password=encrypt_password(password), first_name=profile.data.get("first_name"), last_name=profile.data.get("last_name"), confirmed_at=now, active=True, ) db.session.add(user) db.session.flush() assert user.id, "User does not have an id" connection = cls(user_id=user.id, **profile.data) db.session.add(connection) db.session.commit() return connection
def oidc_callback(): auth_code = request.args.get('code') provider = session['provider'] try: user_info = current_app.oidc_client.authenticate( provider, auth_code, url_for('.oidc_callback', _external=True)) except Exception as e: flash('Login failed: {}: {}'.format(e.__class__.__name__, e), 'error') return redirect(url_for('frontend.index')) user = user_datastore.get_user(user_info['email']) if not user: # query identity mapping service for linked identities that may already # have an account for uid in mapped_ids(user_info['email'])['ids']: user = user_datastore.get_user(uid) if user: break if not user: # user has successfully logged in or registered on IdP # so create an account user = user_datastore.create_user( email=user_info['email'], inbox_email=make_inbox_email(user_info['email']), full_name=user_info.get('nickname', user_info.get('name'))) user_role = user_datastore.find_or_create_role('USER') user_datastore.add_role_to_user(user, user_role) login_user(user) publish_login(user) if 'next' in request.args: return redirect(request.args['next']) return redirect(url_for('frontend.index'))
def confirm_email(token): """View function which handles a email confirmation request.""" expired, invalid, user = confirm_email_token_status(token) if not user or invalid: invalid = True do_flash(*get_message('INVALID_CONFIRMATION_TOKEN')) if expired: send_confirmation_instructions(user) do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email, within=_security.confirm_email_within)) if invalid or expired: return redirect(get_url(_security.confirm_error_view) or url_for_security('send_confirmation')) if user.confirmed_at is not None: do_flash(*get_message('ALREADY_CONFIRMED')) return redirect(get_url(_security.post_confirm_view) or get_url(_security.post_login_view)) if request.json: form_data = MultiDict(request.json) else: form_data = request.form form = forms.ConfirmEmailForm(form_data) if form.validate_on_submit(): user.password = form.password.data confirm_user(user) # this saves 'user' if user != current_user: logout_user() login_user(user) do_flash(*get_message('EMAIL_CONFIRMED')) return redirect(get_url(_security.post_confirm_view) or get_url(_security.post_login_view)) return render_template('security/confirm.html', token=token, confirm_form=form, **_ctx('change_password') )
def flask_login(): """Login view with custom form validation. Login into site like Admin user (is_staff) and like Control user (only is_authenticated). """ if request.json: form = LoginForm(MultiDict(request.json)) else: form = LoginForm() if form.validate_on_submit(): login_user(form.user, remember=form.remember.data) after_this_request(_commit) if not request.json: return redirect(get_post_login_redirect(form.next.data)) if request.json: return _render_json(form, include_auth_token=True) return _security.render_template(config_value('LOGIN_USER_TEMPLATE'), login_user_form=form, **_ctx('login'))
def setup(): form = forms.ExtendedRegisterForm() if form.validate_on_submit(): flash(_("User %(username)s created", username=form.email.data), "success") admin_role = user_datastore.find_or_create_role('admin') user_role = user_datastore.find_or_create_role('user') user = user_datastore.create_user(email=form.email.data, password=encrypt_password( form.password.data), locale=form.locale.data, active=1, roles=[admin_role, user_role]) user_datastore.commit() login_user(user) return redirect(url_for('settings')) if not db.session.query(models.User).first(): return render_template('setup.html', form=form, title=_('Setup'), data_dir=config.DATA_DIR) else: return redirect(url_for("importer"))
def su(email_or_name): users = set(User.objects.filter(email=email_or_name)) users = users | set(User.objects.filter(full_name=email_or_name)) if len(users) == 1: login_user(list(users)[0]) return redirect(url_for('frontend.index'))
def create_db(): from aprovapp.exams.models import FederalRegion, FederalUnit, \ ExaminingBoard, ExamLevel, Promoter, CalendarEventTrigger, \ ExamJobRole, KnowledgeArea, Discipline, Subject db.create_all() user = user_datastore.create_user(email='*****@*****.**', password='******') db.session.commit() ctx = app.test_request_context('/') ctx.push() login_user(user) db.session.add_all([ FederalRegion(id = 1, name = u'Sul', short_name = u'S'), FederalRegion(id = 2, name = u'Sudeste', short_name = u'SE'), FederalRegion(id = 3, name = u'Centroeste', short_name = u'CO'), FederalRegion(id = 4, name = u'Nordeste', short_name = u'NE'), FederalRegion(id = 5, name = u'Norte', short_name = u'N'), FederalRegion(id = 6, name = u'Brasil', short_name = u'B'), ]) db.session.add_all([ FederalUnit(name = u'NACIONAL', short_name = u'BR', region_id=6), FederalUnit(name = u'Acre', short_name = u'AC', region_id=5), FederalUnit(name = u'Alagoas', short_name = u'AL', region_id=4), FederalUnit(name = u'Amapá', short_name = u'AP', region_id=5), FederalUnit(name = u'Amazonas', short_name = u'AM', region_id=5), FederalUnit(name = u'Bahia', short_name = u'BA', region_id=4), FederalUnit(name = u'Ceará', short_name = u'CE', region_id=4), FederalUnit(name = u'Distrito Federal', short_name = u'DF', region_id=3), FederalUnit(name = u'Espírito Santo', short_name = u'ES', region_id=2), FederalUnit(name = u'Goiás', short_name = u'GO', region_id=3), FederalUnit(name = u'Maranhão', short_name = u'MA', region_id=4), FederalUnit(name = u'Mato Grosso', short_name = u'MT', region_id=3), FederalUnit(name = u'Mato Grosso do Sul', short_name = u'MS', region_id=3), FederalUnit(name = u'Minas Gerais', short_name = u'MG', region_id=2), FederalUnit(name = u'Pará', short_name = u'PA', region_id=5), FederalUnit(name = u'Paraíba', short_name = u'PB', region_id=4), FederalUnit(name = u'Paraná', short_name = u'PR', region_id=1), FederalUnit(name = u'Pernambuco', short_name = u'PE', region_id=4), FederalUnit(name = u'Piauí', short_name = u'PI', region_id=4), FederalUnit(name = u'Rio de Janeiro', short_name = u'RJ', region_id=2), FederalUnit(name = u'Rio Grande do Norte', short_name = u'RN', region_id=4), FederalUnit(name = u'Rio Grande do Sul', short_name = u'RS', region_id=1), FederalUnit(name = u'Rondônia', short_name = u'RO', region_id=5), FederalUnit(name = u'Roraima', short_name = u'RR', region_id=5), FederalUnit(name = u'Santa Catarina', short_name = u'SC', region_id=1), FederalUnit(name = u'São Paulo', short_name = u'SP', region_id=2), FederalUnit(name = u'Sergipe', short_name = u'SE', region_id=4), FederalUnit(name = u'Tocantins', short_name = u'TO', region_id=5), ]) db.session.add_all([ ExaminingBoard( name = u'CESPE/UnB', short_name = u'CESPE', url = u'http://www.cespe.unb.br/concursos/' ), ExaminingBoard( name = u'Fundação Getúlio Vargas', short_name = u'FGV', url = u'http://oab.fgv.br/'), ]) db.session.add_all([ Promoter( name = u'Ordem dos Advogados do Brasil', short_name = u'OAB', url = u'http://www.oab.org.br/servicos/examedeordem' ), ]) db.session.add_all([ ExamLevel(level = u'Ensino Fundamental'), ExamLevel(level = u'Ensino Médio'), ExamLevel(level = u'Técnico'), ExamLevel(level = u'Superior'), ExamLevel(level = u'Mestrado'), ExamLevel(level = u'Doutorado'), ]) db.session.add_all([ CalendarEventTrigger(id=1, name=u'Publicação'), CalendarEventTrigger(id=2, name=u'Início das Inscrições'), CalendarEventTrigger(id=3, name=u'Encerramento das Inscrições'), CalendarEventTrigger(id=4, name=u'Isenção de Inscrição'), CalendarEventTrigger(id=5, name=u'Recursos de Inscrição'), CalendarEventTrigger(id=6, name=u'Data e Local das Provas'), CalendarEventTrigger(id=7, name=u'Exame'), CalendarEventTrigger(id=8, name=u'Gabaritos'), CalendarEventTrigger(id=9, name=u'Resultado 1ª fase'), CalendarEventTrigger(id=10, name=u'Resultado 2ª fase'), CalendarEventTrigger(id=11, name=u'Resultado 3ª fase'), CalendarEventTrigger(id=12, name=u'Encerramento'), ]) db.session.add_all([ ExamJobRole(role=u'Analista Judiciário'), ExamJobRole(role=u'Técnico Judiciário'), ExamJobRole(role=u'Oficial de Justiça)'), ]) db.session.add_all([ KnowledgeArea(id=1, name=u'Direito'), Discipline(id=1, name=u'Direito Tributário', knowledge_area_id=1), Discipline(id=2, name=u'Direito Penal', knowledge_area_id=1), Subject(id=1, name=u'Substituição', discipline_id=1), Subject(id=2, name=u'Solidariedade', discipline_id=1), Subject(id=3, name=u'Penas', discipline_id=2), Subject(id=4, name=u'Dolo', discipline_id=2), ]) db.session.commit() ctx.pop()
def register(): form_data = MultiDict(request.json) form = RegisterForm(form_data) user = register_user(**form.to_dict()) login_user(user) return current_user.get_auth_token()
def su(email_or_name): users = set(User.objects.filter(email=email_or_name)) users = users | set(User.objects.filter(full_name=email_or_name)) if len(users) == 1: login_user(list(users)[0]) return redirect(url_for("frontend.index"))
def oauth_handler(resp): app = current_app oauth_app = get_oauth_app(provider) if not oauth_app: return "Access denied: oauth app not found" oauth_app.tokengetter( lambda: session.get("oauth_" + provider + "_token") ) if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) session["oauth_" + provider + "_token"] = (resp['access_token'], '') data = app.config.get("OAUTH", {}).get(provider) me = oauth_app.get(data.get('_info_endpoint')) if not any([me.data.get('verified'), me.data.get('verified_email')]): return "Access denied: email not verified" email = me.data.get('email') name = me.data.get('name') provider_user_id = me.data.get('id') profile_url = me.data.get('link') access_token = resp['access_token'] try: user = User.objects.get(email=email) except User.DoesNotExist: user = User( name=name, email=email, username=User.generate_username(email) ) user.save() try: connection = Connection.objects.get( user_id=str(user.id), provider_id=provider, ) connection.access_token = access_token connection.save() except Connection.DoesNotExist: connection = Connection( user_id=str(user.id), provider_id=provider, provider_user_id=provider_user_id, profile_url=profile_url, access_token=access_token ) connection.save() login_user(user) _next = request.args.get( 'next', request.referrer ) or session.get( 'next' ) or app.config.get('OAUTH_POST_LOGIN', "/") return redirect(_next)
def login(user): return security_utils.login_user(user)
def create_db(): from aprovapp.exams.models import FederalRegion, FederalUnit, \ ExaminingBoard, ExamLevel, Promoter, CalendarEventTrigger, \ ExamJobRole, KnowledgeArea, Discipline, Subject db.create_all() user = user_datastore.create_user(email='*****@*****.**', password='******') db.session.commit() ctx = app.test_request_context('/') ctx.push() login_user(user) db.session.add_all([ FederalRegion(id=1, name=u'Sul', short_name=u'S'), FederalRegion(id=2, name=u'Sudeste', short_name=u'SE'), FederalRegion(id=3, name=u'Centroeste', short_name=u'CO'), FederalRegion(id=4, name=u'Nordeste', short_name=u'NE'), FederalRegion(id=5, name=u'Norte', short_name=u'N'), FederalRegion(id=6, name=u'Brasil', short_name=u'B'), ]) db.session.add_all([ FederalUnit(name=u'NACIONAL', short_name=u'BR', region_id=6), FederalUnit(name=u'Acre', short_name=u'AC', region_id=5), FederalUnit(name=u'Alagoas', short_name=u'AL', region_id=4), FederalUnit(name=u'Amapá', short_name=u'AP', region_id=5), FederalUnit(name=u'Amazonas', short_name=u'AM', region_id=5), FederalUnit(name=u'Bahia', short_name=u'BA', region_id=4), FederalUnit(name=u'Ceará', short_name=u'CE', region_id=4), FederalUnit(name=u'Distrito Federal', short_name=u'DF', region_id=3), FederalUnit(name=u'Espírito Santo', short_name=u'ES', region_id=2), FederalUnit(name=u'Goiás', short_name=u'GO', region_id=3), FederalUnit(name=u'Maranhão', short_name=u'MA', region_id=4), FederalUnit(name=u'Mato Grosso', short_name=u'MT', region_id=3), FederalUnit(name=u'Mato Grosso do Sul', short_name=u'MS', region_id=3), FederalUnit(name=u'Minas Gerais', short_name=u'MG', region_id=2), FederalUnit(name=u'Pará', short_name=u'PA', region_id=5), FederalUnit(name=u'Paraíba', short_name=u'PB', region_id=4), FederalUnit(name=u'Paraná', short_name=u'PR', region_id=1), FederalUnit(name=u'Pernambuco', short_name=u'PE', region_id=4), FederalUnit(name=u'Piauí', short_name=u'PI', region_id=4), FederalUnit(name=u'Rio de Janeiro', short_name=u'RJ', region_id=2), FederalUnit(name=u'Rio Grande do Norte', short_name=u'RN', region_id=4), FederalUnit(name=u'Rio Grande do Sul', short_name=u'RS', region_id=1), FederalUnit(name=u'Rondônia', short_name=u'RO', region_id=5), FederalUnit(name=u'Roraima', short_name=u'RR', region_id=5), FederalUnit(name=u'Santa Catarina', short_name=u'SC', region_id=1), FederalUnit(name=u'São Paulo', short_name=u'SP', region_id=2), FederalUnit(name=u'Sergipe', short_name=u'SE', region_id=4), FederalUnit(name=u'Tocantins', short_name=u'TO', region_id=5), ]) db.session.add_all([ ExaminingBoard(name=u'CESPE/UnB', short_name=u'CESPE', url=u'http://www.cespe.unb.br/concursos/'), ExaminingBoard(name=u'Fundação Getúlio Vargas', short_name=u'FGV', url=u'http://oab.fgv.br/'), ]) db.session.add_all([ Promoter(name=u'Ordem dos Advogados do Brasil', short_name=u'OAB', url=u'http://www.oab.org.br/servicos/examedeordem'), ]) db.session.add_all([ ExamLevel(level=u'Ensino Fundamental'), ExamLevel(level=u'Ensino Médio'), ExamLevel(level=u'Técnico'), ExamLevel(level=u'Superior'), ExamLevel(level=u'Mestrado'), ExamLevel(level=u'Doutorado'), ]) db.session.add_all([ CalendarEventTrigger(id=1, name=u'Publicação'), CalendarEventTrigger(id=2, name=u'Início das Inscrições'), CalendarEventTrigger(id=3, name=u'Encerramento das Inscrições'), CalendarEventTrigger(id=4, name=u'Isenção de Inscrição'), CalendarEventTrigger(id=5, name=u'Recursos de Inscrição'), CalendarEventTrigger(id=6, name=u'Data e Local das Provas'), CalendarEventTrigger(id=7, name=u'Exame'), CalendarEventTrigger(id=8, name=u'Gabaritos'), CalendarEventTrigger(id=9, name=u'Resultado 1ª fase'), CalendarEventTrigger(id=10, name=u'Resultado 2ª fase'), CalendarEventTrigger(id=11, name=u'Resultado 3ª fase'), CalendarEventTrigger(id=12, name=u'Encerramento'), ]) db.session.add_all([ ExamJobRole(role=u'Analista Judiciário'), ExamJobRole(role=u'Técnico Judiciário'), ExamJobRole(role=u'Oficial de Justiça)'), ]) db.session.add_all([ KnowledgeArea(id=1, name=u'Direito'), Discipline(id=1, name=u'Direito Tributário', knowledge_area_id=1), Discipline(id=2, name=u'Direito Penal', knowledge_area_id=1), Subject(id=1, name=u'Substituição', discipline_id=1), Subject(id=2, name=u'Solidariedade', discipline_id=1), Subject(id=3, name=u'Penas', discipline_id=2), Subject(id=4, name=u'Dolo', discipline_id=2), ]) db.session.commit() ctx.pop()
def log(): json = request.get_json() app.logger.debug(json) #mail = request.args.get("mail") mail = json["mail"] app.logger.debug(mail) #password = request.args.get("password") password = json["password"] #url = json["url"] u = user_datastore.get_user(mail) if u: v = utils.verify_password(password, u.password) if v: if u.confirmed_at: utils.login_user(u, remember=True) i=[] for v in u.roles: i.append(v.name) response = { "status": True, "message": "Authenticated", #"url":url, "route":"home", "mail":mail, "roles":i, "confirmed_at":u.confirmed_at, "active":u.active } else: response = { "status": False, "message": "Not logged", "route":"confirm", "mail":"", "roles":[], "active":False, #"url":url } else: response = { "status": False, "message": "Not logged", "route":"login", "mail":"", "roles":[], "active":False, #"url":url } else: response = { "status": False, "message": "Not a user", "route":"register", "mail":"", "roles":[], "active":False, #"url":url } return jsonify(response )