def test_fileurl_parsing_windows(implicit_format, localhost, monkeypatch): if implicit_format: pathformat = None monkeypatch.setattr("os.name", "nt") else: pathformat = "windows" monkeypatch.delattr("os.name") # just to make sure it won't get used url = urls.url_parse("file:///C:/Documents and Settings/Foobar/stuff.txt") assert url.netloc == "" assert url.scheme == "file" assert url.get_file_location(pathformat) == ( None, r"C:\Documents and Settings\Foobar\stuff.txt", ) url = urls.url_parse("file://///server.tld/file.txt") assert url.get_file_location(pathformat) == ("server.tld", r"file.txt") url = urls.url_parse("file://///server.tld") assert url.get_file_location(pathformat) == ("server.tld", "") url = urls.url_parse("file://///%s" % localhost) assert url.get_file_location(pathformat) == (None, "") url = urls.url_parse("file://///%s/file.txt" % localhost) assert url.get_file_location(pathformat) == (None, r"file.txt")
def test_fileurl_parsing_windows(implicit_format, localhost, monkeypatch): if implicit_format: pathformat = None monkeypatch.setattr('os.name', 'nt') else: pathformat = 'windows' monkeypatch.delattr('os.name') # just to make sure it won't get used url = urls.url_parse('file:///C:/Documents and Settings/Foobar/stuff.txt') assert url.netloc == '' assert url.scheme == 'file' assert url.get_file_location(pathformat) == \ (None, r'C:\Documents and Settings\Foobar\stuff.txt') url = urls.url_parse('file://///server.tld/file.txt') assert url.get_file_location(pathformat) == ('server.tld', r'file.txt') url = urls.url_parse('file://///server.tld') assert url.get_file_location(pathformat) == ('server.tld', '') url = urls.url_parse('file://///%s' % localhost) assert url.get_file_location(pathformat) == (None, '') url = urls.url_parse('file://///%s/file.txt' % localhost) assert url.get_file_location(pathformat) == (None, r'file.txt')
def test_redirect_to_records(self): self.company_A = self.env['res.company'].create({ 'name': 'Company A', 'user_ids': [(4, self.ref('base.user_admin'))], }) self.company_B = self.env['res.company'].create({ 'name': 'Company B', }) self.multi_company_record = self.env['mail.test.multi.company'].create({ 'name': 'Multi Company Record', 'company_id': self.company_A.id, }) # Test Case 0 # Not logged, redirect to web/login response = self.url_open('/mail/view?model=%s&res_id=%s' % ( self.multi_company_record._name, self.multi_company_record.id), timeout=15) path = url_parse(response.url).path self.assertEqual(path, '/web/login') self.authenticate('admin', 'admin') # Test Case 1 # Logged into company 1, try accessing record in company A # _redirect_to_record should add company A in allowed_company_ids response = self.url_open('/mail/view?model=%s&res_id=%s' % ( self.multi_company_record._name, self.multi_company_record.id), timeout=15) self.assertEqual(response.status_code, 200) fragment = url_parse(response.url).fragment cids = url_decode(fragment)['cids'] self.assertEqual(cids, '1,%s' % (self.company_A.id)) # Test Case 2 # Logged into company 1, try accessing record in company B # _redirect_to_record should redirect to messaging as the user # doesn't have any access for this company self.multi_company_record.company_id = self.company_B response = self.url_open('/mail/view?model=%s&res_id=%s' % ( self.multi_company_record._name, self.multi_company_record.id), timeout=15) self.assertEqual(response.status_code, 200) fragment = url_parse(response.url).fragment action = url_decode(fragment)['action'] self.assertEqual(action, 'mail.action_discuss')
def test_replace(): url = urls.url_parse("http://de.wikipedia.org/wiki/Troll") strict_eq( url.replace(query="foo=bar"), urls.url_parse("http://de.wikipedia.org/wiki/Troll?foo=bar"), ) strict_eq( url.replace(scheme="https"), urls.url_parse("https://de.wikipedia.org/wiki/Troll"), )
def rewrite_static_url(path): """Remove __vxxx prefix from static URLs.""" plugin_pattern = _plugin_url_pattern.format(url_parse(config.BASE_URL).path) static_pattern = _static_url_pattern.format(url_parse(config.BASE_URL).path) custom_pattern = _custom_url_pattern.format(url_parse(config.BASE_URL).path) if re.match(plugin_pattern, path): return re.sub(plugin_pattern, r'static/plugins/\1/\2.\3', path) elif re.match(static_pattern, path): return re.sub(static_pattern, r'static/\1\2/\3.\4', path) else: return re.sub(custom_pattern, r'static/custom/\1', path)
def _redirect_to_record(cls, model, res_id, access_token=None, **kwargs): """ If the current user doesn't have access to the document, but provided a valid access token, redirect him to the front-end view. If the partner_id and hash parameters are given, add those parameters to the redirect url to authentify the recipient in the chatter, if any. :param model: the model name of the record that will be visualized :param res_id: the id of the record :param access_token: token that gives access to the record bypassing the rights and rules restriction of the user. :param kwargs: Typically, it can receive a partner_id and a hash (sign_token). If so, those two parameters are used to authentify the recipient in the chatter, if any. :return: """ if issubclass(type(request.env[model]), request.env.registry['portal.mixin']): uid = request.session.uid or request.env.ref('base.public_user').id record_sudo = request.env[model].sudo().browse(res_id).exists() try: record_sudo.sudo(uid).check_access_rights('read') record_sudo.sudo(uid).check_access_rule('read') except AccessError: if record_sudo.access_token and access_token and consteq(record_sudo.access_token, access_token): record_action = record_sudo.with_context(force_website=True).get_access_action() if record_action['type'] == 'ir.actions.act_url': pid = kwargs.get('pid') hash = kwargs.get('hash') url = record_action['url'] if pid and hash: url = urls.url_parse(url) url_params = url.decode_query() url_params.update([("pid", pid), ("hash", hash)]) url = url.replace(query=urls.url_encode(url_params)).to_url() return werkzeug.utils.redirect(url) return super(MailController, cls)._redirect_to_record(model, res_id, access_token=access_token)
def _clean_website(self, website): url = urls.url_parse(website) if not url.scheme: if not url.netloc: url = url.replace(netloc=url.path, path='') website = url.replace(scheme='http').to_url() return website
def get_redis_args(url): """Parses Redis connection arguments out of a URL string redis://[db-number[:password]@]host:port[?option=value][#prefix] Returns (args, poolsize, prefix), where args can be passed directly to a redis Connection """ url = url_parse(url) if url.path and url.path != '/': raise ValueError("Bad redis URL: can't contain path") db_number = int(url.username or 0) password = url.password or None host = url.host or 'localhost' port = url.port or 6379 prefix = url.fragment if not prefix.endswith(':'): prefix = prefix + ':' options = url.decode_query() poolsize = options.pop('poolsize', 20) if options: raise ValueError('Extra Redis options: %s' % ', '.join(options)) return dict( host=host, port=port, password=password, db=db_number, auto_reconnect=True, ), poolsize, prefix
def connection_info_for(db_or_uri): """ parse the given `db_or_uri` and return a 2-tuple (dbname, connection_params) Connection params are either a dictionary with a single key ``dsn`` containing a connection URI, or a dictionary containing connection parameter keywords which psycopg2 can build a key/value connection string (dsn) from :param str db_or_uri: database name or postgres dsn :rtype: (str, dict) """ if db_or_uri.startswith(('postgresql://', 'postgres://')): # extract db from uri us = urls.url_parse(db_or_uri) if len(us.path) > 1: db_name = us.path[1:] elif us.username: db_name = us.username else: db_name = us.hostname return db_name, {'dsn': db_or_uri} connection_info = {'database': db_or_uri} for p in ('host', 'port', 'user', 'password', 'sslmode'): cfg = tools.config['db_' + p] if cfg: connection_info[p] = cfg return db_or_uri, connection_info
def subscribe(self, request, writer): content_type = request.get('content-type') if content_type != 'text/html': raise WebsocketBadRequest('unknown content type', **{'content-type': content_type}) channel_url = request.get('channel') index = request.get('index') if not channel_url: raise WebsocketBadRequest('no channel specified', index=index) url = url_parse(channel_url) channel = url.path try: view = yield from self.root[channel] except LookupError: raise WebsocketBadRequest('no such channel', index=index, channel=channel) try: sub = view.ws_subscribe except AttributeError: raise WebsocketBadRequest('not a channel', index=index, channel=channel) last_stamp = request.get('last_stamp') def send(**data): data.setdefault('action', 'push') data['index'] = index data['channel'] = channel writer.send(json.dumps(data)) task = asyncio.Task(view.ws_subscribe(send, last_stamp, options=url.decode_query())) return index, task.cancel
def _sendReport(self): cfg = Config.getInstance() data = json.loads(self._msg) template = get_template_module('emails/error_report.txt', comment=self._comments, traceback=data['traceback'], request_info=pformat(data['request_info']), server_name=url_parse(cfg.getBaseURL()).netloc) send_email(make_email(cfg.getSupportEmail(), reply_address=self._userMail, template=template), skip_queue=True)
def _replace_local_links(self, html): """ Post-processing of html content to replace local links to absolute links, using web.base.url as base url. """ if not html: return html # form a tree root = lxml.html.fromstring(html) if not len(root) and root.text is None and root.tail is None: html = '<div>%s</div>' % html root = lxml.html.fromstring(html) base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') base = urls.url_parse(base_url) def _process_link(url): new_url = urls.url_parse(url) if new_url.scheme and new_url.netloc: return url return new_url.replace(scheme=base.scheme, netloc=base.netloc).to_url() # check all nodes, replace : # - img src -> check URL # - a href -> check URL for node in root.iter(): if node.tag == 'a' and node.get('href'): node.set('href', _process_link(node.get('href'))) elif node.tag == 'img' and not node.get('src', 'data').startswith('data'): node.set('src', _process_link(node.get('src'))) html = lxml.html.tostring(root, pretty_print=False, method='html') # this is ugly, but lxml/etree tostring want to put everything in a 'div' that breaks the editor -> remove that if html.startswith('<div>') and html.endswith('</div>'): html = html[5:-6] return html
def image(self, src, title, text): if self.record is not None: url = url_parse(src) if not url.scheme: src = self.record.url_to('!' + src, base_url=get_ctx().base_url) return mistune.Renderer.image(self, src, title, text)
def route_from(url, method=None): appctx = _app_ctx_stack.top reqctx = _request_ctx_stack.top if appctx is None: raise RuntimeError( "Attempted to match a URL without the " "application context being pushed. This has to be " "executed when application context is available." ) if reqctx is not None: url_adapter = reqctx.url_adapter else: url_adapter = appctx.url_adapter if url_adapter is None: raise RuntimeError( "Application was not able to create a URL " "adapter for request independent URL matching. " "You might be able to fix this by setting " "the SERVER_NAME config variable." ) parsed_url = url_parse(url) if parsed_url.netloc is not "" and parsed_url.netloc != url_adapter.server_name: raise NotFound() return url_adapter.match(parsed_url.path, method)
def serialize_event(cal, fossil, now, id_prefix="indico-event"): event = ical.Event() event.add('uid', '{}-{}@{}'.format(id_prefix, fossil['id'], url_parse(config.BASE_URL).host)) event.add('dtstamp', now) event.add('dtstart', _deserialize_date(fossil['startDate'])) event.add('dtend', _deserialize_date(fossil['endDate'])) event.add('url', fossil['url']) event.add('summary', to_unicode(fossil['title'])) loc = fossil['location'] or '' if loc: loc = to_unicode(loc) if fossil['roomFullname']: loc += ' ' + to_unicode(fossil['roomFullname']) event.add('location', loc) description = '' if fossil.get('speakers'): speakers = ('{} ({})'.format(speaker['fullName'].encode('utf-8'), speaker['affiliation'].encode('utf-8')) for speaker in fossil['speakers']) description += 'Speakers: {}\n'.format(', '.join(speakers)) if fossil['description']: desc_text = fossil['description'].strip() if not desc_text: desc_text = '<p/>' try: description += '{}\n\n{}'.format(to_unicode(html.fromstring(to_unicode(desc_text)) .text_content()).encode('utf-8'), fossil['url'].encode('utf-8')) except ParserError: # this happens e.g. if desc_text contains only a html comment description += fossil['url'].encode('utf-8') else: description += fossil['url'] event.add('description', description) cal.add_component(event)
def link(self, link, title, text): if self.record is not None: url = url_parse(link) if not url.scheme: link = self.record.url_to('!' + link, base_url=get_ctx().base_url) return mistune.Renderer.link(self, link, title, text)
def endpoint_for_url(url): urldata = url_parse(url) adapter = app.url_map.bind(urldata.netloc) try: return adapter.match(urldata.path) except RequestRedirect, e: return endpoint_for_url(e.new_url)
def _sendReport( self ): cfg = Config.getInstance() # if no e-mail address was specified, # add a default one if self._userMail: fromAddr = self._userMail else: fromAddr = '*****@*****.**' toAddr = Config.getInstance().getSupportEmail() Logger.get('errorReport').debug('mailing %s' % toAddr) subject = "[Indico@{}] Error report".format(url_parse(cfg.getBaseURL()).netloc) request_info = self._requestInfo or '' if isinstance(request_info, (dict, list)): request_info = pformat(request_info) # build the message body body = [ "-" * 20, "Error details\n", self._code, self._message, "Inner error: " + str(self._inner), request_info, "-" * 20 ] maildata = {"fromAddr": fromAddr, "toList": [toAddr], "subject": subject, "body": "\n".join(body)} GenericMailer.send(GenericNotification(maildata))
def configure_app(app, set_path=False): cfg = Config.getInstance() app.config['DEBUG'] = cfg.getDebug() app.config['SECRET_KEY'] = cfg.getSecretKey() if not app.config['SECRET_KEY'] or len(app.config['SECRET_KEY']) < 16: raise ValueError('SecretKey must be set to a random secret of at least 16 characters. ' 'You can generate one using os.urandom(32) in Python shell.') app.config['PROPAGATE_EXCEPTIONS'] = True app.config['SESSION_COOKIE_NAME'] = 'indico_session' app.config['PERMANENT_SESSION_LIFETIME'] = cfg.getSessionLifetime() app.config['INDICO_SESSION_PERMANENT'] = cfg.getSessionLifetime() > 0 app.config['INDICO_HTDOCS'] = cfg.getHtdocsDir() app.config['INDICO_COMPAT_ROUTES'] = cfg.getRouteOldUrls() configure_multipass(app) app.config['PLUGINENGINE_NAMESPACE'] = 'indico.plugins' app.config['PLUGINENGINE_PLUGINS'] = cfg.getPlugins() if set_path: base = url_parse(cfg.getBaseURL()) app.config['SERVER_NAME'] = base.netloc if base.path: app.config['APPLICATION_ROOT'] = base.path app.config['WTF_CSRF_ENABLED'] = False # for forms of room booking static_file_method = cfg.getStaticFileMethod() if static_file_method: app.config['USE_X_SENDFILE'] = True method, args = static_file_method if method in ('xsendfile', 'lighttpd'): # apache mod_xsendfile, lighttpd pass elif method in ('xaccelredirect', 'nginx'): # nginx if not args or not hasattr(args, 'items'): raise ValueError('StaticFileMethod args must be a dict containing at least one mapping') app.wsgi_app = XAccelMiddleware(app.wsgi_app, args) else: raise ValueError('Invalid static file method: %s' % method)
def url_for(path_or_uri, lang=None): if isinstance(path_or_uri, unicode): path_or_uri = path_or_uri.encode('utf-8') current_path = request.httprequest.path if isinstance(current_path, unicode): current_path = current_path.encode('utf-8') location = path_or_uri.strip() force_lang = lang is not None url = urls.url_parse(location) if request and not url.netloc and not url.scheme and (url.path or force_lang): location = urls.url_join(current_path, location) lang = lang or request.context.get('lang') langs = [lg[0] for lg in request.website.get_languages()] if (len(langs) > 1 or force_lang) and is_multilang_url(location, langs): ps = location.split('/') if ps[1] in langs: # Replace the language only if we explicitly provide a language to url_for if force_lang: ps[1] = lang.encode('utf-8') # Remove the default language unless it's explicitly provided elif ps[1] == request.website.default_lang_code: ps.pop(1) # Insert the context language or the provided language elif lang != request.website.default_lang_code or force_lang: ps.insert(1, lang.encode('utf-8')) location = '/'.join(ps) return location.decode('utf-8')
def configure_app(app, set_path=False): config = IndicoConfig(app.config['INDICO']) # needed since we don't have an app ctx yet app.config['DEBUG'] = config.DEBUG app.config['SECRET_KEY'] = config.SECRET_KEY app.config['LOGGER_NAME'] = 'flask.app' app.config['LOGGER_HANDLER_POLICY'] = 'never' if config.SENTRY_DSN: app.config['SENTRY_CONFIG'] = { 'dsn': config.SENTRY_DSN, 'release': indico.__version__ } if not app.config['SECRET_KEY'] or len(app.config['SECRET_KEY']) < 16: raise ValueError('SECRET_KEY must be set to a random secret of at least 16 characters. ' 'You can generate one using os.urandom(32) in Python shell.') if config.MAX_UPLOAD_FILES_TOTAL_SIZE > 0: app.config['MAX_CONTENT_LENGTH'] = config.MAX_UPLOAD_FILES_TOTAL_SIZE * 1024 * 1024 app.config['PROPAGATE_EXCEPTIONS'] = True app.config['TRAP_HTTP_EXCEPTIONS'] = False app.config['TRAP_BAD_REQUEST_ERRORS'] = config.DEBUG app.config['SESSION_COOKIE_NAME'] = 'indico_session' app.config['PERMANENT_SESSION_LIFETIME'] = config.SESSION_LIFETIME configure_multipass(app, config) app.config['PLUGINENGINE_NAMESPACE'] = 'indico.plugins' app.config['PLUGINENGINE_PLUGINS'] = config.PLUGINS if set_path: base = url_parse(config.BASE_URL) app.config['PREFERRED_URL_SCHEME'] = base.scheme app.config['SERVER_NAME'] = base.netloc if base.path: app.config['APPLICATION_ROOT'] = base.path configure_xsendfile(app, config.STATIC_FILE_METHOD) if config.USE_PROXY: app.wsgi_app = ProxyFix(app.wsgi_app)
def create_response_and_send_mail(wizard, token, partner_id, email): """ Create one mail by recipients and replace __URL__ by link with identification token """ #set url url = wizard.survey_id.public_url url = urls.url_parse(url).path[1:] # dirty hack to avoid incorrect urls if token: url = url + '/' + token # post the message values = { 'model': None, 'res_id': None, 'subject': wizard.subject, 'body': wizard.body.replace("__URL__", url), 'body_html': wizard.body.replace("__URL__", url), 'parent_id': None, 'attachment_ids': wizard.attachment_ids and [(6, 0, wizard.attachment_ids.ids)] or None, 'email_from': wizard.email_from or None, 'auto_delete': True, } if partner_id: values['recipient_ids'] = [(4, partner_id)] else: values['email_to'] = email Mail.create(values).send()
def split_url(url, method='GET'): """Returns the endpoint name and arguments that match a given URL. In other words, this is the reverse for Flask's url_for().""" appctx = _app_ctx_stack.top reqctx = _request_ctx_stack.top if appctx is None: raise RuntimeError('Attempted to match an URL without the ' 'application context being pushed. this has to be ' 'executed when application context is available.') if reqctx is not None: url_adapter = reqctx.url_adapter else: url_adapter = appctx.url_adapter if url_adapter is None: raise RuntimeError('Application was not able to create an URL ' 'adapter for request independent URL matching. ' 'You might be able to fix this by setting ' 'the SERVER_NAME config variable.') parsed_url = url_parse(url) if parsed_url.netloc is not '' \ and parsed_url.netloc != url_adapter.server_name: raise ValidationError('Invalid URL: ' + url) try: result = url_adapter.match(parsed_url.path, method) except NotFound: raise ValidationError('Invalid URL: ' + url) return result
def __init__(self, uuid, link, user_id=None): self.uuid = uuid self.link = link url = url_parse(link) self.domain = url.host if user_id: self.user_id = user_id
def resolve_redirect(self, response, new_location, environ, buffered=False): """Resolves a single redirect and triggers the request again directly on this redirect client. """ scheme, netloc, script_root, qs, anchor = url_parse(new_location) base_url = url_unparse((scheme, netloc, "", "", "")).rstrip("/") + "/" cur_server_name = netloc.split(":", 1)[0].split(".") real_server_name = get_host(environ).rsplit(":", 1)[0].split(".") if self.allow_subdomain_redirects: allowed = cur_server_name[-len(real_server_name) :] == real_server_name else: allowed = cur_server_name == real_server_name if not allowed: raise RuntimeError("%r does not support redirect to " "external targets" % self.__class__) # For redirect handling we temporarily disable the response # wrapper. This is not threadsafe but not a real concern # since the test client must not be shared anyways. old_response_wrapper = self.response_wrapper self.response_wrapper = None try: return self.open(path=script_root, base_url=base_url, query_string=qs, as_tuple=True, buffered=buffered) finally: self.response_wrapper = old_response_wrapper
def test_link_tracker(self): _url = 'https://www.example.com/foo/bar?baz=qux' mailing = self.env['mail.mass_mailing'].create({ 'name': 'TestMailing', 'medium_id': self.test_medium.id, 'body_html': '<p>Hello <a role="button" href="%s">${object.name}</a><a role="button" href="/unsubscribe_from_list">Unsubscribe</a></p>' % _url, 'reply_to_mode': 'email', 'mailing_model_id': self.ref('test_mass_mailing.model_mass_mail_test_bl'), 'mailing_domain': [('id', 'in', self.mm_recs.ids)], }) mailing.send_mail() # basic test emails are sent self.assertEqual(mailing.sent, 5) self.assertEqual(mailing.delivered, 5) # link trackers links = self.env['link.tracker'].sudo().search([('mass_mailing_id', '=', mailing.id)]) self.assertEqual(len(links), 1) self.assertEqual(links.mapped('url'), [_url]) # check UTMS are correctly set on redirect URL redirect_url = urls.url_parse(links.redirected_url) redirect_params = redirect_url.decode_query().to_dict(flat=True) self.assertEqual(redirect_url.scheme, 'https') self.assertEqual(redirect_url.decode_netloc(), 'www.example.com') self.assertEqual(redirect_url.path, '/foo/bar') self.assertEqual(redirect_params, { 'utm_source': mailing.name, 'utm_medium': self.test_medium.name, 'baz': 'qux', })
def configure_app(app, set_path=False): cfg = Config.getInstance() app.config['PROPAGATE_EXCEPTIONS'] = True app.config['SESSION_COOKIE_NAME'] = 'indico_session' app.config['PERMANENT_SESSION_LIFETIME'] = cfg.getSessionLifetime() app.config['INDICO_SESSION_PERMANENT'] = cfg.getSessionLifetime() > 0 app.config['INDICO_HTDOCS'] = cfg.getHtdocsDir() app.config['INDICO_COMPAT_ROUTES'] = cfg.getRouteOldUrls() if set_path: base = url_parse(cfg.getBaseURL()) app.config['SERVER_NAME'] = base.netloc if base.path: app.config['APPLICATION_ROOT'] = base.path static_file_method = cfg.getStaticFileMethod() if static_file_method: app.config['USE_X_SENDFILE'] = True method, args = static_file_method if method in ('xsendfile', 'lighttpd'): # apache mod_xsendfile, lighttpd pass elif method in ('xaccelredirect', 'nginx'): # nginx if not args or not hasattr(args, 'items'): raise ValueError('StaticFileMethod args must be a dict containing at least one mapping') app.wsgi_app = XAccelMiddleware(app.wsgi_app, args) else: raise ValueError('Invalid static file method: %s' % method)
def match_url(url, method=None): """Get endpoint and arguments from a url. SEE http://stackoverflow.com/questions/19631335/reverting-a-url-in-flask Returns: endpoint name (str?) arguments (dict). """ appctx = _app_ctx_stack.top reqctx = _request_ctx_stack.top if appctx is None: raise RuntimeError('Attempted to match a URL without the ' 'application context being pushed. This has to be ' 'executed when application context is available.') if reqctx is not None: url_adapter = reqctx.url_adapter else: url_adapter = appctx.url_adapter if url_adapter is None: raise RuntimeError('Application was not able to create a URL ' 'adapter for request independent URL matching. ' 'You might be able to fix this by setting ' 'the SERVER_NAME config variable.') parsed_url = url_parse(url) if parsed_url.netloc is not '' and \ parsed_url.netloc != url_adapter.server_name: raise NotFound() return url_adapter.match(parsed_url.path, method)
def version_url(value): """Moves the version tag from the query string to the URL""" url = url_parse(value) if not url.query: return value path = url.path.replace('/static', '/static_v/' + url.query, 1) return str(url.replace(path=path, query=''))
def parse_redirect(self, location, parse_fragment=False): from werkzeug.urls import url_parse, url_decode, url_unparse scheme, netloc, script_root, qs, anchor = url_parse(location) return ( url_unparse((scheme, netloc, script_root, '', '')), url_decode(anchor if parse_fragment else qs) )
def login(): if current_user.is_authenticated: return redirect(url_for("index")) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() # Check user if user is None or not user.check_password(form.password.data): flash("Invalid username or password") return redirect(url_for("login")) login_user(user, remember=form.remember_me.data) # return redirect(url_for("index")) next_page = request.args.get("next") if not next_page or url_parse(next_page).netloc != "": next_page = url_for("index") return redirect(next_page) return render_template("login.html", title="Sign In", form=form)
def login(): if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): conn = sqlite3.connect(db_path) cur = conn.execute('SELECT * FROM users WHERE username = ?', (form.username.data,)) cur = cur.fetchone() user = User(cur[1], cur[2]) # at this point cur contains either [] or the row of data for the user # which includes userid (int), username(string), and password(string) if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=True) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': flash('Hello \"' + user.username + '\"') next_page = url_for('index') return redirect(next_page) return render_template('login_v2.html', form=form)
def login(): if current_user.is_authenticated: return redirect(url_for('main.index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash(_('Invalid username or password')) login_user(user, remember=form.remember_me.data) next_page = request.args.get('next') # The second part of the conditional is for security reasons. Doesn't allow redirects to external page # More info in https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins if not next_page or url_parse(next_page).netloc != '': return redirect(url_for('main.index')) return redirect(next_page) return render_template('login.html', title=_('Sign In'), form=form)
def login(): # already login user if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): # 일치하는 user을 db에서 쿼리 user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) #어규멘트로 들어온 nexturl 파싱 next_page = request.args.get('next') #어규멘트가 없거나 netloc가 있는 (즉 풀도메인)인경우 경우 index 페이지로 if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') return redirect(next_page) return render_template('login.html', title='Sign In', form=form)
def try_to_guess_url(url): url_adapter = g.get_url_adapter() if url is None: url_adapter = g.get_url_adapter() rules = url_adapter.map._rules_by_endpoint.get( request.endpoint, ()) url = '' if len(rules) < 1 else rules[0].rule else: try: from werkzeug.urls import url_parse parsed_url = url_parse(url) rules = url_adapter.match(parsed_url.path, method='GET', return_rule=True) url = rules[0].rule except Exception: url = '' return url
def login(): if (current_user.is_authenticated): return redirect(url_for('index')) form = LoginForm() if (form.validate_on_submit()): user = User.query.filter_by(username=form.username.data).first() if (user is None or not user.check_password(form.password.data)): flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) next_page = request.args.get('next') if (not next_page or url_parse(next_page).netloc != ''): return redirect(url_for('index')) return redirect(next_page) return render_template('forms.html', form=form)
def login(): """ Logs user in :return: main page if user is already logged, login page if not """ if current_user.is_authenticated: return redirect(url_for("main.index")) title = "HR - logowanie" form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash("Nieprawidłowa nazwa użytkownika lub hasło") return redirect(url_for("auth.login")) login_user(user, remember=form.remember_me.data) next_page = request.args.get("next") if not next_page or url_parse(next_page).netloc != "": next_page = url_for("main.index") return redirect(next_page) return render_template("auth/login.html", title=title, form=form)
def login(): if current_user.is_authenticated: return redirect(url_for('index')) errors = [] form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(name=form.username.data).first() if user is None or not user.check_password(form.password.data): errors.append('用户名或密码无效') return render_template("login.html", form=form, errors=errors) login_user(user) # 重定向到登录之前的页面 next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') return redirect(next_page) return render_template("login.html", form=form)
def login(): form = LoginForm() # Instance of auth.forms.loginform if request.method == "GET": if current_user.is_authenticated: return redirect(url_for(admin_urls['admin'])) return render_template(auth_templates['login'], title=context['app_name'], form=form) elif request.method == "POST": if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password', 'success') return redirect(url_for(auth_urls['login'])) else: login_user(user, remember=form.remember_me.data) load_permissions(user.id) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for(admin_urls['admin']) return redirect(url_for(admin_urls['admin']))
def __init__( self, app, path="/", base_url=None, subdomain=None, url_scheme=None, *args, **kwargs, ): assert not (base_url or subdomain or url_scheme) or ( base_url is not None) != bool( subdomain or url_scheme ), 'Cannot pass "subdomain" or "url_scheme" with "base_url".' if base_url is None: http_host = app.config.get("SERVER_NAME") or "localhost" app_root = app.config["APPLICATION_ROOT"] if subdomain: http_host = "{0}.{1}".format(subdomain, http_host) if url_scheme is None: url_scheme = app.config["PREFERRED_URL_SCHEME"] url = url_parse(path) base_url = "{scheme}://{netloc}/{path}".format( scheme=url.scheme or url_scheme, netloc=url.netloc or http_host, path=app_root.lstrip("/"), ) path = url.path if url.query: sep = b"?" if isinstance(url.query, bytes) else "?" path += sep + url.query self.app = app super(EnvironBuilder, self).__init__(path, base_url, *args, **kwargs)
def login(): # User already logged in if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() # POST Request if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.data.password): flash("Invalid username or password") return redirect(url_for('login')) # Add data to session so we know they're logged in login_user(user, remember=form.data.remember) # Handle redirecting to page they requested when logged out next_page = request.args.get('next') if not next_page or url_parse( next_page ).netloc != '': # netloc not being empty means this is not a relative url return redirect(url_for('index')) return redirect(url_for(next_page)) # GET Request return render_template('login.html', title='Sign In', form=form)
def url_to_static_filename(endpoint, url): """Handle special endpoint/URLs so that they link to offline content.""" if re.match(r'(events)?\.display(_overview)?$', endpoint): return 'index.html' elif endpoint == 'event_layout.css_display': return 'custom.css' elif endpoint == 'event_images.logo_display': return 'logo.png' indico_path = url_parse(config.BASE_URL).path if re.match(_static_url_pattern.format(indico_path), url): url = rewrite_static_url(url) else: # get rid of [/whatever]/event/1234 url = re.sub(fr'{indico_path}(?:/event/\d+)?/(.*)', r'\1', url) if not url.startswith('assets/'): # replace all remaining slashes url = url.rstrip('/').replace('/', '--') # it's not executed in a webserver, so we do need a .html extension if not _url_has_extension_re.match(url): url += '.html' return url
def login(): """ Login page for employees. If user is already logged in, they are redirected to the manager dashboard page. """ if current_user.is_authenticated: return redirect(url_for('manager')) form = LoginForm() if form.validate_on_submit(): user = Marketer.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('manager') return redirect(next_page) return render_template('login.html', form=form)
def login(): if current_user.is_authenticated: return redirect(url_for('index')) admin = db.session.query(Administrator).count() form = LoginForm() if form.validate_on_submit(): user = db.session.query(User).filter_by( username=form.username.data).first() if user is None or not user.check_password(form.password.data): message = Markup( '<div class="alert alert-danger alert-dismissible"><button type="button" class="close" data-dismiss="alert">×</button>Invalid username or password</div>' ) flash(message) return redirect(url_for('login')) login_user(user) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('admin_dashboard') return redirect(next_page) return render_template('login.html', form=form, admin_setting=admin)
def login(): """Endpoint to log the user in""" if current_user.is_authenticated: # used to check the user is already logged in return redirect(url_for("index")) form = LoginForm() # Creating a form instance if (form.validate_on_submit() or request.method == "POST" ): # Checking if a post request or if the button is submitted user = User.query.filter_by(username=form.username.data).first( ) # Getting the user with specific filters if user is None or not user.check_password( form.password.data): # Authenticating the user flash("Invalid username or password") return redirect(url_for("login")) login_user(user, remember=form.remember_me.data) next_page = request.args.get("next") if ( not next_page or url_parse(next_page).netloc != "" ): # Passing on the the page wherethe user is supposed to be redirected after logging in next_page = url_for("index") return redirect(next_page) return render_template("login.html", title="Sign In", form=form) # passing the form to jinja template
def match_url(url, method=None): appctx = _app_ctx_stack.top reqctx = _request_ctx_stack.top if appctx is None: raise RuntimeError('Attempted to match a URL without the ' 'application context being pushed. This has to be ' 'executed when application context is available.') if reqctx is not None: url_adapter = reqctx.url_adapter else: url_adapter = appctx.url_adapter if url_adapter is None: raise RuntimeError('Application was not able to create a URL ' 'adapter for request independent URL matching. ' 'You might be able to fix this by setting ' 'the SERVER_NAME config variable.') parsed_url = url_parse(url) if parsed_url.netloc is not '' and \ parsed_url.netloc != url_adapter.server_name: raise NotFound() return url_adapter.match(parsed_url.path, method)
def login(): if current_user.is_authenticated: return redirect(url_for('main.index')) login_form = LoginForm() registration_form = RegistrationForm() if login_form.validate_on_submit(): user = User.query.filter_by(username=login_form.username.data).first() if user is None or not user.check_password(login_form.password.data): flash('invalid username or password') return redirect(url_for('auth.login')) login_user(user, remember=login_form.remember_me.data) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('main.index') return redirect(next_page) return render_template('auth/register.html', title='Sign In', registration_form=registration_form, login_form=login_form) '''
def login(): if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() # form.validate_on_submit()はsubmitされた瞬間にバリデーションチェックを行い、問題なければTrueを返す if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) # 別ページを開こうとして強制的にログインページに飛ばされた場合はログイン完了したら元のページに戻してやる next_page = request.args.get('next') # next_pageは基本的に相対パスのはずだが、攻撃者が別サイトなど絶対URLを指定して来たらnetlocにexample.com等が入っているのでその場合はindexページに飛ばす if not next_page or url_parse(next_page).netloc != '': next_page = 'index' if next_page[0] == "/": next_page = next_page[1:] return redirect(url_for(next_page)) return render_template('login.html', title='Sign In', form=form)
def login(): """Login page :return: Page for logging in users """ if current_user.is_authenticated: return redirect(url_for('input_page')) form = LoginForm() if form.validate_on_submit(): # look at first result first() user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=form.rememberMe.data) # return to page before user got asked to login next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('input_page') return redirect(next_page) return render_template('login.html', title='Sign in', form=form)
def login(): if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): requested_user = User.query.filter_by( username=form.username.data).first() if requested_user: if requested_user.check_password(form.password.data): login_user(requested_user, remember=form.remember_me.data) current_user.last_sign_in = datetime.utcnow() db.session.commit() request_redirect_page = request.args.get('next') if request_redirect_page is None or url_parse( request_redirect_page).netloc != '': return redirect(url_for('index')) return redirect(request_redirect_page) flash(_('Invalid username or password. Please try again.')) return redirect(url_for('login')) return render_template('login.html', form=form, page_title=_('Reddit - Log In'))
def login(): if current_user.is_authenticated: return redirect(url_for('get_started')) form = LoginForm() if form.validate_on_submit(): #User must either be a student or an advisor student = Student.query.filter_by(vip_id=form.username.data).first() advisor = Advisor.query.filter_by(vip_id=form.username.data).first() if (student is None or not student.check_password(form.password.data) ) and (advisor is None or not advisor.check_password(form.password.data)): flash('The password or username you entered was invalid.') return redirect(url_for('login')) if student is None: login_user(advisor) else: login_user(student) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('get_started') return redirect(next_page) return render_template('index.html', title='Login', form=form)
def login(): if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is None: flash("Invalid user",'danger') return redirect(url_for('login')) if user.confrim=='NO': flash('unconfrimed account, Please check your mail to confrim',category='danger') return redirect(url_for('login')) if not user.check_password(form.password.data): flash("Invalid password",'danger') return redirect(url_for('login')) login_user(user, remember = form.remember_me.data) next_page = request.args.get('next') session['login_user']=True if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') return redirect(url_for('profile')) return render_template("login.html",title="Sign In", form=form)
def login(): myform = request.form if current_user.is_authenticated: flash("El usuario ya se encuentra autenticado") return redirect(url_for('test')) if request.method == 'POST': user = Usuario.query.filter( func.lower(Usuario.email) == func.lower( request.form['inputEmail'])).first() if user is None or not user.check_password( request.form['inputPassword']): flash('Usuario o contraseña incorrectos') return redirect(url_for('login')) if request.form.get('remember_me', None) is None: login_user(user) else: login_user(user, remember=True) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') return redirect(next_page) return render_template('login.html', form=myform)
def test_html_render(self): html_node = html.fromstring(self.mail0.body_html) link_node = html_node.xpath("//a[hasclass('view_in_browser_url')]") self.assertEqual( url_parse(link_node[0].get('href')).path, self.mail0.view_in_browser_url) self.mail0.auto_delete = True self.mail0._replace_view_url() self.mail0.refresh() html_node = html.fromstring(self.mail0.body_html) link_node = html_node.xpath("//a[hasclass('view_in_browser_url')]") self.assertEqual(link_node, []) link_node = html_node.xpath( "//a[not(hasclass('view_in_browser_url'))]") self.assertEqual(len(link_node), 1) self.assertEqual(link_node[0].get('href'), 'https://www.google.com') p_node = html_node.xpath("//p") self.assertEqual(len(p_node), 2)
def login(): if current_user.is_authenticated: return redirect(url_for("main.index")) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).one_or_none() if user is None or not user.check_password(form.password.data): flash(_("Invalid email address or password")) return redirect(url_for("main.login")) elif not user.is_activated: flash(_("User not activated yet")) return redirect(url_for("main.login")) login_user(user, remember=form.remember_me.data) next_page = request.args.get("next") if not next_page or url_parse(next_page).netloc != "": next_page = url_for("main.index") return redirect(next_page) return render_template("form_generator.html", title=_("Login"), form=form)
def login(): # Redirect user to index if they are already logged in if current_user.is_authenticated: return redirect(url_for('main.index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() # Return to login if username is not found or password is wrong if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('auth.login')) login_user(user, remember=form.remember_me.data) # Redirect the user where they came from next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('main.index') return redirect(next_page) return render_template('auth/login.html', title='Sign In', form=form)
def _find_document_data_from_url(self, url): url_obj = urls.url_parse(url) if url_obj.ascii_host == 'youtu.be': return ('youtube', url_obj.path[1:] if url_obj.path else False) elif url_obj.ascii_host in ('youtube.com', 'www.youtube.com', 'm.youtube.com'): v_query_value = url_obj.decode_query().get('v') if v_query_value: return ('youtube', v_query_value) split_path = url_obj.path.split('/') if len(split_path) >= 3 and split_path[1] in ('v', 'embed'): return ('youtube', split_path[2]) expr = re.compile( r'(^https:\/\/docs.google.com|^https:\/\/drive.google.com).*\/d\/([^\/]*)' ) arg = expr.match(url) document_id = arg and arg.group(2) or False if document_id: return ('google', document_id) return (None, False)
def login() -> 'html': if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Неверный логин или пароль'.format(form.username.data, form.remember_me.data)) return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') return redirect(next_page) return render_template('login.html', form=form)
def login(): if current_user.is_authenticated: return redirect(url_for('home')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): app.logger.warning('Invalid username or password') flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) app.logger.warning('Successful User Login') next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('home') return redirect(next_page) session["state"] = str(uuid.uuid4()) auth_url = _build_auth_url(scopes=Config.SCOPE, state=session["state"]) return render_template('login.html', title='Sign In', form=form, auth_url=auth_url)
def register(): '''Registers new user. ''' if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User( first_name=form.first_name.data, last_name=form.last_name.data, username=form.username.data, email=form.email.data ) user.set_password(form.password.data) db.session.add(user) db.session.commit() login_user(user) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') return redirect(next_page) return render_template('register.html', title='Register', form=form)