def action(self, resource, context, form): email = form['username'].strip() password = form['password'] # Check the user exists root = context.root user = root.get_user_from_login(email) if user is None: message = ERROR(u'The user "{username}" does not exist.', username=email) goto = context.get_referrer() return context.come_back(message, goto) # Check the password is right if not user.authenticate(password, clear=True): message = ERROR(u'The password is wrong.') goto = context.get_referrer() return context.come_back(message, goto) # Check user is enabled ac = resource.get_access_control() if not user.get_property('is_enabled') and \ not ac.is_admin(user, resource): message = ERROR(u"""Your account isn't validated, please contact the webmaster""") goto = context.get_referrer() return context.come_back(message, goto) # Check user has confirm is registration if user.get_property('user_must_confirm'): message = ERROR(u"""Your account has not been confirmed.""") goto = '/users/%s/;confirm_registration' % user.name return context.come_back(message, goto) # We log authentification if resource != context.root: shop = get_shop(resource) if shop.get_property('log_authentification'): logs = shop.get_resource('customers/authentification_logs') logs.log_authentification(user.name) user.set_property('last_time', datetime.now()) # Set cookie user.set_auth_cookie(context, password) # Set context context.user = user # Come back referrer = context.get_referrer() if referrer is None: goto = get_reference('./') else: path = get_uri_path(referrer) if path.endswith(';login'): goto = get_reference('./') else: goto = referrer return context.come_back(INFO(u"Welcome!"), goto)
def start_test(odf_handler): # Create the 'results' folder if vfs.exists('results'): vfs.remove('results') vfs.make_folder('results') # Find test files print 'Searching for ODF files...' unitests = get_tests() unitests = list(unitests) nb_tests = len(unitests) print 'Number of files found: %d' % nb_tests test_number = 0 msgs_error = [] for odf_path, po_handler in unitests: # Progress bar test_number += 1 progress(test_number, nb_tests) # Call ODF handler try: odf_sources = odf_handler(odf_path) except: print 'ERROR with test %d / "%s"' % (test_number, odf_path) continue # Post-process the results odf_sources = clean_sources(odf_sources) odf_sources = list(set(odf_sources)) # Remove duplicates odf_sources.sort() # Expected results po_sources = [ u''.join(x.source) for x in po_handler.get_units() ] po_sources = clean_sources(po_sources) po_sources.sort() # Check if odf_sources == po_sources: continue # Error. Create a diff report for the current test. test_name = odf_path.split('/')[-2] filename = 'test_%d_%s.txt' % (test_number, test_name) po_path = get_uri_path(po_handler.uri) write_diff_file(test_number, filename, odf_path, po_path, odf_sources, po_sources) # Inform the user that there where failures msgs_error.append('results/%s\n' % filename) # Summurarizes the results print print 'Results:' print '--------' print ' %s Tests' % nb_tests print ' %s Errors' % len(msgs_error) print if msgs_error: stderr.write('Generated error files\n') stderr.write('---------------------\n') for msg in msgs_error: stderr.write(msg)
def action(self, resource, context, form): # Get the user email = form['username'].strip() user = context.root.get_user_from_login(email) if form['no_password']: if not Email.is_valid(email): message = u'The given username is not an email address.' context.message = ERROR(message) return # Case 1: Register # check captcha first captcha = form['captcha'].strip() crypted = crypt_captcha(captcha) crypt_imgtext = form['crypt_imgtext'].strip() decrypt = Password.decode('%s' % crypt_imgtext) if crypted != decrypt: error = u"You typed an incorrect captcha string." context.message = ERROR(error) return # does the user exists? if user is None: if context.site_root.is_allowed_to_register(): return self._register(resource, context, email) # FIXME This message does not protect privacy error = u"You don't have an account, contact the site admin." context.message = ERROR(error) return # Case 2: Forgotten password email = user.get_property('email') user.send_forgotten_password(context, email) path = '/ui/website/forgotten_password.xml' handler = resource.get_resource(path) return stl(handler) # Case 3: Login password = form['password'] if user is None or not user.authenticate(password, clear=True): context.message = ERROR(u'The email or the password is incorrect.') return # Set cookie & context user.set_auth_cookie(context, password) context.user = user # Come back referrer = context.get_referrer() if referrer is None: goto = get_reference('./') else: path = get_uri_path(referrer) if path.endswith(';login'): goto = get_reference('./') else: goto = referrer return context.come_back(INFO(u"Welcome to the Phoenix Project!"), goto)
def get_tests(): """Returns list of tuples: [(odf_path, po_handler), ...] """ # We traverse all ODF documents for odf_uri in vfs.traverse('./documents/'): odf_handler = get_handler(odf_uri) if not isinstance(odf_handler, ODFFile): continue # We found a ODF Document, We search the corresponding PO file po_uri = resolve_uri(odf_uri, 'testDoc.po') yield get_uri_path(odf_uri), get_handler(po_uri)
def get_goto(self, user): context = self.context # Check if user account is completed for name, field in user.get_fields(): if field.required and user.get_value(name) is None: msg = MSG(u'You must complete your account informations') goto = '/users/%s/;edit_account' % user.name return context.come_back(msg, goto) # Come back referrer = context.get_referrer() if referrer is None: goto = get_reference('./') else: path = get_uri_path(referrer) if path.endswith(';login') or path.endswith(';register'): goto = get_reference('./') else: goto = referrer return context.come_back(INFO(u"Welcome!"), goto)
def get_path(reference): return get_uri_path(reference)
def update_20090705(self): """ Encode the unencoded MOV or AVI file, and add the thumb, erase the original file. """ from pprint import pprint from datetime import datetime from tempfile import mkdtemp from issue import Tchack_Issue from ikaaro.file import Video from ikaaro.exceptions import ConsistencyError from itools import vfs from itools.vfs import FileName from itools.core import guess_extension from itools.uri import get_uri_path from videoencoding import VideoEncodingToFLV from ikaaro.registry import get_resource_class for issue in self.search_resources(cls=Tchack_Issue): history = issue.get_history() for record in history.get_records(): filename = record.file comment = record.comment is_video = False if not comment and not filename: continue if filename: file = issue.get_resource(filename) is_video = isinstance(file, Video) if not is_video: continue if is_video: name = file.name filename, ext, lang = FileName.decode(name) if ext is None: mimetype = file.get_content_type() ext = guess_extension(mimetype)[1:] if(mimetype == 'video/x-msvideo' or mimetype == 'video/quicktime'): pprint("The file %s.%s will be encoded in FLV, \ replaced by, then erased." % (filename, ext)) handler_path = get_uri_path(issue.handler.uri) dirname = mkdtemp('videoencoding', 'ikaaro') tempdir = vfs.open(dirname) # Paste the file in the tempdir tmp_uri= "file:///%s/%s" % (dirname, filename) vfs.copy(file.handler.uri, tmp_uri) # Encode to 512 of width encoded = VideoEncodingToFLV(file).encode_avi_to_flv( dirname, filename, name, 512) if encoded is not None: flvfilename, flvmimetype, flvbody, flvextension = encoded['flvfile'] thumbfilename, thumbmimetype, thumbbody, thumbextension = encoded['flvthumb'] # Create the video FLV and thumbnail PNG resources video = get_resource_class(flvmimetype) thumbnail = get_resource_class(thumbmimetype) # Remove the original files if vfs.exists(file.handler.uri): vfs.remove(file.handler.uri) if vfs.exists(file.metadata.uri): vfs.remove(file.metadata.uri) video.make_resource(video, issue, name, body=flvbody, filename=flvfilename, extension=flvextension, format=flvmimetype) thumbnail.make_resource(thumbnail, issue, thumbfilename, body=thumbbody, filename=thumbfilename, extension=thumbextension, format=thumbmimetype) # Clean the temporary folder vfs.remove(dirname) pprint("====================") pprint("xxxxxxxxxxxxxxxx")
def do_request(self, method='GET', path='/', headers=None, body='', context=None, as_json=False, as_multipart=False, files=None, user=None, cookies=None): """Experimental method to do a request on the server""" from itools.web.router import RequestMethod headers = [] path_info = get_uri_path(path) q_string = path.split('?')[-1] # Build base environ environ = {'PATH_INFO': path_info, 'REQUEST_METHOD': method, 'HTTP_X-Forwarded-Host': 'localhost/', 'HTTP_X_FORWARDED_PROTO': 'http', 'QUERY_STRING': q_string} setup_testing_defaults(environ) if files: as_multipart = True # Get request header / body if as_json: req = Request( method, 'http://localhost:8080{0}'.format(path), json=body, ) prepped = req.prepare() elif as_multipart: req = Request( method, 'http://localhost:8080{0}'.format(path), data=body, files=files ) prepped = req.prepare() else: req = Request( method, 'http://localhost:8080{0}'.format(path), data=body, ) prepped = req.prepare() # Build headers headers = [(key.lower(), value) for key, value in prepped.headers.items()] headers.append(('User-Agent', 'Firefox')) for key, value in headers: environ['HTTP_%s' % key.upper().replace('-', '_')] = value # Set wsgi input body environ['wsgi.input'] = BytesIO(prepped.body) # Set content length if prepped.body: environ['CONTENT_LENGTH'] = len(prepped.body) # Set accept if as_json: environ['CONTENT_TYPE'] = 'application/json' environ['HTTP_ACCEPT'] = 'application/json' elif as_multipart: environ['CONTENT_TYPE'] = prepped.headers['Content-Type'] else: environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded' # Get context context = get_context() # Log user user = context.user or user if user: context.login(user) context.user = user context.server = self # Init context from environ context.init_from_environ(environ, user) # Cookies if cookies: for key, value in cookies.items(): context.set_cookie(key, value) # Do request RequestMethod.handle_request(context) # Transform result if context.entity is None: response = None elif as_json and not str(context.status).startswith('3'): # Do not load json if 302 (url redirection) try: response = loads(context.entity) except ValueError: msg = 'Cannot load json {0}'.format(context.entity) raise ValueError(msg) else: response = context.entity # Commit if method == 'POST': context.database.save_changes() # Return result return {'status': context.status, 'method': context.method, 'entity': response, 'context': context}