def change_password(self, request): """Changes the user's password Takes a classical authentication or a reset code """ # the body is in plain text utf8 string new_password = request.body.decode('utf8') if not valid_password(request.user.get('username'), new_password): raise HTTPBadRequest('Password should be at least 8 ' 'characters and not the same as your ' 'username') key = request.headers.get('X-Weave-Password-Reset') if key is not None: user_id = self.auth.get_user_id(request.user) if user_id is None: raise HTTPNotFound() if not self.reset.verify_reset_code(request.user, key): log_cef('Invalid Reset Code submitted', 5, request.environ, self.app.config, request.user['username'], 'InvalidResetCode', submitedtoken=key) raise HTTPJsonBadRequest(ERROR_INVALID_RESET_CODE) if not self.auth.admin_update_password(request.user, new_password, key): raise HTTPInternalServerError('Password change failed ' 'unexpectedly.') else: # classical auth self.app.auth.authenticate_user(request, self.app.config, request.user['username']) if request.user['userid'] is None: log_cef('User Authentication Failed', 5, request.environ, self.app.config, request.user['username'], AUTH_FAILURE) raise HTTPUnauthorized() if not self.auth.update_password( request.user, request.user_password, new_password): raise HTTPInternalServerError('Password change failed ' 'unexpectedly.') return text_response('success')
def __call__(self, environ, start_response): request = None response = None # Signal to callbacks that request failed hard try: request = self.make_request(environ) try: response = self.handle_request(request) finally: request.response = response response = self._request_finished_handler(self, request) return response(request.environ, start_response) except Exception as exc: error_message = self.exc_log_message_factory(self, request, exc) if self.debug: if self.settings.get('debug.pdb', False): pdb.post_mortem(exc.__traceback__) response = DebugHTTPInternalServerError(error_message) else: # Attempt to ensure this exception is logged (i.e., if # the exc logger is broken for some reason). exc_info = exc.__class__, exc, exc.__traceback__ log.critical(error_message, exc_info=exc_info) response = HTTPInternalServerError() try: self.log_exc(request, exc) finally: return response(environ, start_response)
def __call__(self, env, start_response): start_time = time.time() req = Request(env) self.logger.txn_id = req.headers.get('x-trans-id', None) if not check_utf8(req.path_info): res = HTTPPreconditionFailed(body='Invalid UTF8') else: try: # disallow methods which have not been marked 'public' try: method = getattr(self, req.method) getattr(method, 'publicly_accessible') except AttributeError: res = HTTPMethodNotAllowed() else: res = method(req) except (Exception, Timeout): self.logger.exception(_('ERROR __call__ error with %(method)s' ' %(path)s '), {'method': req.method, 'path': req.path}) res = HTTPInternalServerError(body=traceback.format_exc()) trans_time = '%.4f' % (time.time() - start_time) log_message = '%s - - [%s] "%s %s" %s %s "%s" "%s" "%s" %s' % ( req.remote_addr, time.strftime('%d/%b/%Y:%H:%M:%S +0000', time.gmtime()), req.method, req.path, res.status.split()[0], res.content_length or '-', req.headers.get('x-trans-id', '-'), req.referer or '-', req.user_agent or '-', trans_time) if req.method.upper() == 'REPLICATE': self.logger.debug(log_message) else: self.logger.info(log_message) return res(env, start_response)
def delete_perms(self, group_name): try: obj_type = request.POST.get('obj_type') obj_id = None if obj_type == 'user': obj_id = safe_int(request.POST.get('user_id')) elif obj_type == 'user_group': obj_id = safe_int(request.POST.get('user_group_id')) if not request.authuser.is_admin: if obj_type == 'user' and request.authuser.user_id == obj_id: msg = _('Cannot revoke permission for yourself as admin') h.flash(msg, category='warning') raise Exception('revoke admin permission on self') recursive = request.POST.get('recursive', 'none') if obj_type == 'user': RepoGroupModel().delete_permission(repo_group=group_name, obj=obj_id, obj_type='user', recursive=recursive) elif obj_type == 'user_group': RepoGroupModel().delete_permission(repo_group=group_name, obj=obj_id, obj_type='user_group', recursive=recursive) Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during revoking of permission'), category='error') raise HTTPInternalServerError()
def delete_repo_perm_member(self, repo_name): """ DELETE an existing repository permission user :param repo_name: """ try: obj_type = request.POST.get('obj_type') obj_id = None if obj_type == 'user': obj_id = safe_int(request.POST.get('user_id')) elif obj_type == 'user_group': obj_id = safe_int(request.POST.get('user_group_id')) if obj_type == 'user': RepoModel().revoke_user_permission(repo=repo_name, user=obj_id) elif obj_type == 'user_group': RepoModel().revoke_users_group_permission(repo=repo_name, group_name=obj_id) #TODO: implement this #action_logger(self.rhodecode_user, 'admin_revoked_repo_permissions', # repo_name, self.ip_addr, self.sa) Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during revoking of permission'), category='error') raise HTTPInternalServerError()
def repo_check(self, repo_name): c.repo = repo_name task_id = request.GET.get('task_id') if task_id and task_id not in ['None']: from kallithea import CELERY_ON from celery.result import AsyncResult if CELERY_ON: task = AsyncResult(task_id) if task.failed(): raise HTTPInternalServerError(task.traceback) repo = Repository.get_by_repo_name(repo_name) if repo and repo.repo_state == Repository.STATE_CREATED: if repo.clone_uri: clone_uri = repo.clone_uri_hidden h.flash(_('Created repository %s from %s') % (repo.repo_name, clone_uri), category='success') else: repo_url = h.link_to( repo.repo_name, h.url('summary_home', repo_name=repo.repo_name)) fork = repo.fork if fork: fork_name = fork.repo_name h.flash(h.literal( _('Forked repository %s as %s') % (fork_name, repo_url)), category='success') else: h.flash(h.literal(_('Created repository %s') % repo_url), category='success') return {'result': True} return {'result': False}
def register(ctx, request): try: payload = request.json() nickname = payload['nickname'] mail = payload['mail'] password = payload['password'] except KeyError as e: raise HTTPBadRequest('{} is required'.format(e)) except Exception as e: raise HTTPBadRequest(e) user = User.query.filter(or_(User.nickname == nickname, User.mail == mail)).first() if user is not None: return jsonify(code=400, message='user exist') catalog = Catalog(name='notes') user = User(nickname=nickname, mail=mail, catalogs=[catalog], password=bcrypt.hashpw(password.encode(), bcrypt.gensalt())) db.session.add(user) try: db.session.commit() return jsonify(code=200) except Exception as e: logging.error(e) db.session.rollback() raise HTTPInternalServerError(e)
def delete_perms(self, id): """ DELETE an existing repository group permission user :param group_name: """ try: obj_type = request.POST.get('obj_type') obj_id = None if obj_type == 'user': obj_id = safe_int(request.POST.get('user_id')) elif obj_type == 'user_group': obj_id = safe_int(request.POST.get('user_group_id')) if not c.authuser.is_admin: if obj_type == 'user' and c.authuser.user_id == obj_id: msg = _('Cannot revoke permission for yourself as admin') h.flash(msg, category='warning') raise Exception('revoke admin permission on self') if obj_type == 'user': UserGroupModel().revoke_user_permission(user_group=id, user=obj_id) elif obj_type == 'user_group': UserGroupModel().revoke_user_group_permission( target_user_group=id, user_group=obj_id) Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during revoking of permission'), category='error') raise HTTPInternalServerError()
class LunrWsgiApp(object): def __init__(self, conf, urlmap, helper=None): self.conf = conf self.urlmap = urlmap if helper: self.helper = helper else: self.helper = self._get_helper(conf) def _get_helper(conf): pass def match(self, request): route = self.urlmap.match(environ=request.environ) if route is None: raise HTTPNotFound("No route matched for path '%s'" % request.path) logger.debug("Request path: %s matched: %s" % (request.path, repr(route))) try: # Try to call the controller and action controller = route['controller'](route, self) return controller.__getattribute__(route['action']) except AttributeError, e: # Couldn't find the action on the controller logger.debug( 'No action (%s) for controller (%s) Error: %s' % (route.get('action', ''), route.get('controller', ''), e)) raise HTTPNotImplemented("No action for path '%s'" % request.path) except Exception, e: logger.exception('controller/action FAIL: %s %s' % (e, route)) raise HTTPInternalServerError('Internal route error')
def __call__(self, env, start_response): start_time = time.time() req = Request(env) self.logger.txn_id = req.headers.get('x-trans-id', None) if not check_utf8(req.path_info): res = HTTPPreconditionFailed(body='Invalid UTF8') else: try: if hasattr(self, req.method): res = getattr(self, req.method)(req) else: res = HTTPMethodNotAllowed() except (Exception, Timeout): self.logger.exception(_('ERROR __call__ error with %(method)s' ' %(path)s '), {'method': req.method, 'path': req.path}) res = HTTPInternalServerError(body=traceback.format_exc()) trans_time = '%.4f' % (time.time() - start_time) additional_info = '' if res.headers.get('x-container-timestamp') is not None: additional_info += 'x-container-timestamp: %s' % \ res.headers['x-container-timestamp'] log_message = '%s - - [%s] "%s %s" %s %s "%s" "%s" "%s" %s "%s"' % ( req.remote_addr, time.strftime('%d/%b/%Y:%H:%M:%S +0000', time.gmtime()), req.method, req.path, res.status.split()[0], res.content_length or '-', req.headers.get('x-trans-id', '-'), req.referer or '-', req.user_agent or '-', trans_time, additional_info) if req.method.upper() == 'REPLICATE': self.logger.debug(log_message) else: self.logger.info(log_message) return res(env, start_response)
def __call__(self, environ, start_response): """ Find appropriate controller for requested address. Return Response object that support the WSGI interface. """ request = Request(environ) try: controller_name = request.get_controller_name() action_name = request.get_action_name() action_handler = self.get_action_handler(controller_name, action_name) if not callable(action_handler): # action handler should be a callable function raise PageNotFound( "Controller '{name}' doesn't have action '{action}'", name=controller_name, action=action_name) resp = action_handler(request) if not isinstance(resp, Response): raise Exception( "Controller should return Response object, but given '{}'". format(type(resp))) except PageNotFound as err: message = self._format_error_message(str(err), with_traceback=True) return HTTPNotFound(message)(environ, start_response) except Exception as err: message = self._format_error_message(str(err), with_traceback=True) return HTTPInternalServerError(message)(environ, start_response) return resp(environ, start_response)
def _dispatch(request): iter = (api for api in apis if api.matches_start(request.path)) for api in iter: try: request.url_for = _url_for(api).__get__(request) handler = api.match(request.method, request.path) return handler(request, api.config) except HTTPNotFound: continue except HTTPError as e: logger.error(str(e)) logger.debug("\n".join(current_traceback())) return e except Exception as e: errstr = str(e) tbstr = "\n".join(current_traceback()) logger.error(errstr) logger.debug(tbstr) return HTTPInternalServerError(detail=errstr, comment=tbstr) return HTTPNotFound()
def __call__(self, environ, start_response): app = self.wrapped request = Request(environ, charset='utf-8') self.exception = None self.traceback = None try: to_return = b'' for i in app(environ, start_response): try: to_return += i except: import pdb pdb.set_trace() except: to_return = b'' (_, self.exception, self.traceback) = sys.exc_info() traceback_html = str(traceback.format_exc()) for i in HTTPInternalServerError(content_type='text/plain', charset='utf-8', unicode_body=traceback_html)( environ, start_response): to_return += i yield to_return
def edit_permissions_revoke(self, repo_name): try: obj_type = request.POST.get('obj_type') obj_id = None if obj_type == 'user': obj_id = safe_int(request.POST.get('user_id')) elif obj_type == 'user_group': obj_id = safe_int(request.POST.get('user_group_id')) else: assert False if obj_type == 'user': RepoModel().revoke_user_permission(repo=repo_name, user=obj_id) elif obj_type == 'user_group': RepoModel().revoke_user_group_permission(repo=repo_name, group_name=obj_id) else: assert False # TODO: implement this #action_logger(request.authuser, 'admin_revoked_repo_permissions', # repo_name, request.ip_addr) Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during revoking of permission'), category='error') raise HTTPInternalServerError() return []
def repo_check(self, repo_name): c.repo = repo_name task_id = request.GET.get('task_id') if task_id and task_id not in ['None']: if kallithea.CELERY_APP: task_result = celery.result.AsyncResult( task_id, app=kallithea.CELERY_APP) if task_result.failed(): raise HTTPInternalServerError(task_result.traceback) repo = Repository.get_by_repo_name(repo_name) if repo and repo.repo_state == Repository.STATE_CREATED: if repo.clone_uri: h.flash(_('Created repository %s from %s') % (repo.repo_name, repo.clone_uri_hidden), category='success') else: repo_url = h.link_to( repo.repo_name, h.url('summary_home', repo_name=repo.repo_name)) fork = repo.fork if fork is not None: fork_name = fork.repo_name h.flash(h.HTML(_('Forked repository %s as %s')) % (fork_name, repo_url), category='success') else: h.flash(h.HTML(_('Created repository %s')) % repo_url, category='success') return {'result': True} return {'result': False}
def __call__(self, environ, start_response): try: return self._handle_request(environ, start_response) except Exception: log.exception("Exception while handling request") appenlight.track_exception(environ) return HTTPInternalServerError()(environ, start_response) finally: meta.Session.remove()
def _init_default_config(self): if not self.storage: return config = self.storage.get_config() self.cookie_secret = config.data["web"].get("cookie_secret") try: if self.cookie_secret is None: self.cookie_secret = new_secret() config.data["web"]["cookie_secret"] = self.cookie_secret config.save() # store the absolute root url (useful when in CLI) if not config.data["web"].get("root_url"): config.data["web"]["root_url"] = self.req.host_url + self.root_url.href config.save() except IOError: e = HTTPInternalServerError() self.template_vars.update({'scripts': [], 'stylesheets': []}) e.body = self.render('error_writeconfig.html') raise e
def track_request(self, request): request_id = get_request_id(request, _header=self.source_header) if self.source_header is not None and request_id == '-': self.logger.warn('could not find request id in header="%s"', self.source_header) current_thread = threading.current_thread() old_name = current_thread.name try: current_thread.name = 'request=%s' % request_id response = request.get_response(self.app) except Exception: self.logger.exception('unknown exception during request=%s', request_id) response = HTTPInternalServerError() finally: current_thread.name = old_name response.headers[REQUEST_ID_KEY] = request_id return response
def __call__(self, env, start_response): request = webob.Request(env) start = util.monotonic_time() try: resp = self.dispatch(request) except Exception as e: if not isinstance(e, HTTPException): e = HTTPInternalServerError(detail=str(e)) resp = error_response(e) self.log_response(request, resp, util.monotonic_time() - start) return resp(env, start_response)
def exc_handler(app, request, next_handler): try: return next_handler(app, request) except WSGIHTTPException as exc: response = exc except Exception as exc: app.log_exc(request, exc) if app.debug: if app.settings.get('debug.pdb', False): pdb.post_mortem(exc.__traceback__) response = DebugHTTPInternalServerError(traceback.format_exc()) else: response = HTTPInternalServerError() return get_exc_response(app, request, response)
def __call__(self, env, start_response): request = webob.Request(env) req = RequestInfo(request) self.log_start(req) try: resp = self.dispatch(request) except Exception as e: if not isinstance(e, HTTPException): e = HTTPInternalServerError(detail=str(e)) resp = error_response(e) self.log_error(req, resp, e) else: self.log_finish(req, resp) return resp(env, start_response)
def __call__(self, environ, start_response): ''' WSGI interface method. Creates webob and iktomi wrappers and calls `handle` method. ''' request = self.create_request(environ) env = self.create_environment(request) data = VersionedStorage() response = self.handle(env, data) try: result = response(environ, start_response) except Exception: self.handle_error(env) result = HTTPInternalServerError()(environ, start_response) return result
def delete_repos_group_user_perm(self, group_name): """ DELETE an existing repositories group permission user :param group_name: """ try: ReposGroupModel().revoke_user_permission( repos_group=group_name, user=request.POST['user_id']) Session.commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during deletion of group user'), category='error') raise HTTPInternalServerError()
def change_email(self, request): """Changes the user e-mail""" # the body is in plain text email = request.body if not valid_email(email): raise HTTPJsonBadRequest(ERROR_NO_EMAIL_ADDRESS) if not hasattr(request, 'user_password'): raise HTTPBadRequest() if not self.auth.update_field(request.user, request.user_password, 'mail', email): raise HTTPInternalServerError('User update failed.') return text_response(email)
def delete_perm_users_group(self, repo_name): """ DELETE an existing repository permission user group :param repo_name: """ try: RepoModel().revoke_users_group_permission( repo=repo_name, group_name=request.POST['users_group_id']) Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during deletion of repository' ' user groups'), category='error') raise HTTPInternalServerError()
def call(self, request): # Match the Request URL to an action action = self.match(request) for attempts in range(0, 3): try: result = action(request) self.helper.commit() return result except OperationalError, e: if hasattr(e, 'orig') and e.orig.args[0] == 2006: # MySQL server has gone away logger.warning("DB connection error attempt #%d" % attempts, exc_info=True) sleep(2 ** attempts) continue logger.exception("Database Error: %s" % e) raise HTTPInternalServerError("Internal database error") finally:
def __call__(self, env, start_response): clock = util.Clock() clock.start("request") request = webob.Request(env) req = RequestInfo(request) log.debug("START %s", req) try: resp = self.dispatch(request, clock) except Exception as e: if not isinstance(e, HTTPException): e = HTTPInternalServerError(detail=str(e)) resp = error_response(e) self.log_error(req, resp, e, clock) return resp(env, start_response) else: app_iter = resp(env, start_response) res = ResponseInfo(resp) return LoggingAppIter(app_iter, req, res, clock)
def delete_perm_user(self, repo_name): """ DELETE an existing repository permission user :param repo_name: """ try: RepoModel().revoke_user_permission(repo=repo_name, user=request.POST['user_id']) #TODO: implement this #action_logger(self.rhodecode_user, 'admin_revoked_repo_permissions', # repo_name, self.ip_addr, self.sa) Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during deletion of repository user'), category='error') raise HTTPInternalServerError()
def __call__(self, env, start_response): """WSGI Application entry point for the Swift Object Server.""" start_time = time.time() req = Request(env) if not check_utf8(req.path_info): res = HTTPPreconditionFailed(body='Invalid UTF8') else: try: if hasattr(self, req.method): res = getattr(self, req.method)(req) else: res = HTTPMethodNotAllowed() except: res = HTTPInternalServerError(body=traceback.format_exc()) trans_time = time.time() - start_time if req.method in ('PUT', 'DELETE'): slow = self.slow - trans_time if slow > 0: sleep(slow) return res(env, start_response)
def __call__(self, environ, start_response): ''' WSGI interface method. Creates webob and iktomi wrappers and calls `handle` method. ''' # validating Host header to prevent problems with url parsing if not is_host_valid(environ['HTTP_HOST']): logger.warning('Unusual header "Host: {}", return HTTPNotFound'\ .format(environ['HTTP_HOST'])) return HTTPNotFound()(environ, start_response) request = Request(environ, charset='utf-8') env = VersionedStorage(self.env_class, request=request, root=self.root) data = VersionedStorage() response = self.handle(env, data) try: result = response(environ, start_response) except Exception: self.handle_error(env) result = HTTPInternalServerError()(environ, start_response) return result
def handle(self, env, data): ''' Calls application and handles following cases: * catches `webob.HTTPException` errors. * catches unhandled exceptions, calls `handle_error` method and returns 500. * returns 404 if the app has returned None`. ''' try: response = self.handler(env, data) if response is None: logger.debug('Application returned None ' 'instead of Response object') response = HTTPNotFound() except HTTPException as e: response = e except Exception as e: self.handle_error(env) response = HTTPInternalServerError() return response
def dispatch(self): ctx = self.ctx router = ctx.router if not ctx.storage: e = HTTPInternalServerError() ctx.template_vars.update({'scripts': [], 'stylesheets': []}) if 'ASSNET_ROOT' in ctx.req.environ: ctx.template_vars['root'] = ctx.req.environ['ASSNET_ROOT'] e.body = ctx.render('error_notworkingdir.html') else: e.body = ctx.render('error_norootpath.html') raise e self._authenticate() ctx.template_vars["user"] = ctx.user if ctx.user.exists else None # actions: not related to a file or directory # if we are in the root app URL if ctx.url.setvars().href == ctx.root_url.href: action = router.find_action(ctx.req.GET.get('action')) if action is not None: return action(ctx).answer() # check perms f = ctx.file if ctx.object_type == 'directory': if not ctx.user.has_perms(f, f.PERM_LIST): if ctx.user.has_perms(f, f.PERM_IN): raise HTTPForbidden() else: raise HTTPNotFound('File not found') elif not ctx.user.has_perms(f, f.PERM_READ): if ctx.user.has_perms(f, f.PERM_IN): raise HTTPForbidden() else: raise HTTPNotFound('File not found') # normalize paths if ctx.object_type: goodpath = ctx.path if ctx.object_type == 'directory' and not goodpath.endswith('/'): # there should be a trailing slash in the client URL # for directories but not for files goodpath += '/' if ctx.req.path_info != goodpath: root_url = ctx.root_url.url if goodpath.startswith('/'): goodpath = goodpath[1:] if not root_url.endswith('/'): root_url += '/' goodlocation = URL(urlparse.urljoin(root_url, goodpath), vars=ctx.url.vars) ctx.res = HTTPFound(location=quote_url(goodlocation)) return # no object type means no real file exists if ctx.object_type is None: raise HTTPNotFound('File not found') # find the action to forward the request to view, action = router.find_view(f, ctx.req.GET.get('view')) if view and action: # find out current action/view and available views ctx.template_vars['view'] = view.name ctx.template_vars['available_views'] = \ sorted(router.get_available_views(f), key=str) return action(ctx).answer() # action/view not found raise HTTPNotFound('No route found')