def users_create(request): """ Returns users list """ form = forms.UserCreateForm(MultiDict(request.safe_json_body or {}), csrf_context=request) if form.validate(): log.info("registering user") # probably not needed in the future since this requires root anyways # lets keep this here in case we lower view permission in the future # if request.registry.settings['appenlight.disable_registration']: # return HTTPUnprocessableEntity(body={'error': 'Registration is currently disabled.'}) user = User() # insert new user here DBSession.add(user) form.populate_obj(user) UserService.regenerate_security_code(user) UserService.set_password(user, user.user_password) user.status = 1 if form.status.data else 0 request.session.flash(_("User created")) DBSession.flush() return user.get_dict(exclude_keys=[ "security_code_date", "notes", "security_code", "user_password", ]) else: return HTTPUnprocessableEntity(body=form.errors_json)
def user_resource_permission_create(request): """ Set new permissions for user for a resource """ resource = request.context.resource user_name = request.unsafe_json_body.get('user_name') user = User.by_user_name(user_name) if not user: user = User.by_email(user_name) if not user: return False for perm_name in request.unsafe_json_body.get('permissions', []): permission = UserResourcePermission.by_resource_user_and_perm( user.id, perm_name, resource.resource_id) if not permission: permission = UserResourcePermission(perm_name=perm_name, user_id=user.id) resource.user_permissions.append(permission) DBSession.flush() perms = [ p.perm_name for p in resource.perms_for_user(user) if p.type == 'user' ] result = {'user_name': user.user_name, 'permissions': list(set(perms))} return result
def search_users(request): """ Returns a list of users for autocomplete """ user = request.user items_returned = [] like_condition = request.params.get('user_name', '') + '%' # first append used if email is passed found_user = User.by_email(request.params.get('user_name', '')) if found_user: name = '{} {}'.format(found_user.first_name, found_user.last_name) items_returned.append({'user': found_user.user_name, 'name': name}) for found_user in User.user_names_like(like_condition).limit(20): name = '{} {}'.format(found_user.first_name, found_user.last_name) items_returned.append({'user': found_user.user_name, 'name': name}) return items_returned
def auth_tokens_POST(request): """ Lists all available alert channels """ if request.matched_route.name == 'users_self_property': user = request.user else: user = User.by_id(request.matchdict.get('user_id')) if not user: return HTTPNotFound() req_data = request.safe_json_body or {} if not req_data.get('expires'): req_data.pop('expires', None) form = forms.AuthTokenCreateForm(MultiDict(req_data), csrf_context=request) if not form.validate(): return HTTPUnprocessableEntity(body=form.errors_json) token = AuthToken() form.populate_obj(token) if token.expires: interval = h.time_deltas.get(token.expires)['delta'] token.expires = datetime.datetime.utcnow() + interval user.auth_tokens.append(token) DBSession.flush() return token.get_dict()
def lost_password(request): """ Presents lost password page - sends password reset link to specified email address. This link is valid only for 10 minutes """ form = forms.LostPasswordForm(request.POST, csrf_context=request) if request.method == 'POST' and form.validate(): user = User.by_email(form.email.data) if user: user.regenerate_security_code() user.security_code_date = datetime.datetime.utcnow() email_vars = { 'user': user, 'request': request, 'email_title': "AppEnlight :: New password request" } UserService.send_email( request, recipients=[user.email], variables=email_vars, template='/email_templates/lost_password.jinja2') msg = 'Password reset email had been sent. ' \ 'Please check your mailbox for further instructions.' request.session.flash(_(msg)) return HTTPFound(location=request.route_url('lost_password')) return {"form": form}
def assign_users(request): """ Assigns specific report group to user for review - send email notification """ report_group = request.context.report_group application = request.context.resource currently_assigned = [u.user_name for u in report_group.assigned_users] new_assigns = request.unsafe_json_body # first unassign old users for user_name in new_assigns['unassigned']: if user_name in currently_assigned: user = User.by_user_name(user_name) report_group.assigned_users.remove(user) comment = ReportComment(owner_id=request.user.id, report_time=report_group.first_timestamp) comment.body = 'Unassigned group from @%s' % user_name report_group.comments.append(comment) # assign new users for user_name in new_assigns['assigned']: if user_name not in currently_assigned: user = User.by_user_name(user_name) if user in report_group.assigned_users: report_group.assigned_users.remove(user) DBSession.flush() assignment = ReportAssignment( owner_id=user.id, report_time=report_group.first_timestamp, group_id=report_group.id) DBSession.add(assignment) comment = ReportComment(owner_id=request.user.id, report_time=report_group.first_timestamp) comment.body = 'Assigned report_group to @%s' % user_name report_group.comments.append(comment) email_vars = {'user': user, 'request': request, 'application': application, 'report_group': report_group, 'email_title': "AppEnlight :: Assigned Report"} UserService.send_email(request, recipients=[user.email], variables=email_vars, template='/email_templates/assigned_report.jinja2') return True
def users_DELETE(request): """ Removes a user permanently from db - makes a check to see if after the operation there will be at least one admin left """ msg = _('There needs to be at least one administrator in the system') user = User.by_id(request.matchdict.get('user_id')) if user: users = User.users_for_perms(['root_administration']).all() if len(users) < 2 and user.id == users[0].id: request.session.flash(msg, 'warning') else: DBSession.delete(user) request.session.flash(_('User removed')) return True request.response.status = 422 return False
def users_resource_permissions_list(request): """ Get list of permissions assigned to specific resources """ user = User.by_id(request.matchdict.get('user_id')) if not user: return HTTPNotFound() return [permission_tuple_to_dict(perm) for perm in user.resources_with_possible_perms()]
def auth_tokens_list(request): """ Lists all available alert channels """ if request.matched_route.name == 'users_self_property': user = request.user else: user = User.by_id(request.matchdict.get('user_id')) if not user: return HTTPNotFound() return [c.get_dict() for c in user.auth_tokens]
def groups_users_add(request): """ Get list of permissions assigned to specific resources """ group = GroupService.by_id(request.matchdict.get('group_id')) user = User.by_user_name(request.unsafe_json_body.get('user_name')) if not user: user = User.by_email(request.unsafe_json_body.get('user_name')) if not group or not user: return HTTPNotFound() if user not in group.users: group.users.append(user) group.member_count = group.users_dynamic.count() props = [ 'user_name', 'id', 'first_name', 'last_name', 'email', 'last_login_date', 'status' ] u_dict = user.get_dict(include_keys=props) u_dict['gravatar_url'] = user.gravatar_url(s=20) return u_dict
def default_user(): from appenlight.models import DBSession from appenlight.models.user import User from appenlight.models.auth_token import AuthToken transaction.begin() session = DBSession() user = User(id=1, user_name="testuser", status=1, email="*****@*****.**") session.add(user) token = AuthToken(token="1234") user.auth_tokens.append(token) session.execute("SELECT nextval('users_id_seq')") transaction.commit() return user
def default_user(): from appenlight.models.user import User from appenlight.models.auth_token import AuthToken transaction.begin() user = User(id=1, user_name='testuser', status=1, email='*****@*****.**') DBSession.add(user) token = AuthToken(token='1234') user.auth_tokens.append(token) DBSession.flush() transaction.commit() return user
def get_user(request): if not request.path_info.startswith('/static'): user_id = unauthenticated_userid(request) try: user_id = int(user_id) except Exception: return None if user_id: user = User.by_id(user_id) if user: request.environ['appenlight.username'] = '******' % ( user_id, user.user_name) return user else: return None
def auth_tokens_DELETE(request): """ Lists all available alert channels """ if request.matched_route.name == 'users_self_property': user = request.user else: user = User.by_id(request.matchdict.get('user_id')) if not user: return HTTPNotFound() for token in user.auth_tokens: if token.token == request.params.get('token'): user.auth_tokens.remove(token) return True return False
def groups_users_remove(request): """ Get list of permissions assigned to specific resources """ group = GroupService.by_id(request.matchdict.get('group_id')) user = User.by_user_name(request.GET.get('user_name')) if not group or not user: return HTTPNotFound() if len(group.users) > 1: group.users.remove(user) msg = "User removed from group" request.session.flash(msg) group.member_count = group.users_dynamic.count() return True msg = "Administrator group needs to contain at least one user" request.session.flash(msg, 'warning') return False
def lost_password_generate(request): """ Shows new password form - perform time check and set new password for user """ user = User.by_user_name_and_security_code( request.GET.get('user_name'), request.GET.get('security_code')) if user: delta = datetime.datetime.utcnow() - user.security_code_date if user and delta.total_seconds() < 600: form = forms.NewPasswordForm(request.POST, csrf_context=request) if request.method == "POST" and form.validate(): user.set_password(form.new_password.data) request.session.flash(_('You can sign in with your new password.')) return HTTPFound(location=request.route_url('register')) else: return {"form": form} else: return Response('Security code expired')
def application_ownership_transfer(request): """ Allows application owner to transfer application ownership to other user """ resource = request.context.resource form = forms.ChangeApplicationOwnerForm(MultiDict(request.safe_json_body or {}), csrf_context=request) form.password.user = request.user if form.validate(): user = User.by_user_name(form.user_name.data) user.resources.append(resource) # remove integrations to not leak security data of external applications for integration in resource.integrations[:]: resource.integrations.remove(integration) request.session.flash(_('Application transfered')) else: return HTTPUnprocessableEntity(body=form.errors_json) return True
def user_resource_permission_delete(request): """ Removes user permission from specific resource """ resource = request.context.resource user = User.by_user_name(request.GET.get('user_name')) if not user: return False for perm_name in request.GET.getall('permissions'): permission = UserResourcePermission.by_resource_user_and_perm( user.id, perm_name, resource.resource_id) resource.user_permissions.remove(permission) DBSession.flush() perms = [ p.perm_name for p in resource.perms_for_user(user) if p.type == 'user' ] result = {'user_name': user.user_name, 'permissions': list(set(perms))} return result
def users_create(request): """ Returns users list """ form = forms.UserCreateForm(MultiDict(request.safe_json_body or {}), csrf_context=request) if form.validate(): log.info('registering user') user = User() # insert new user here DBSession.add(user) form.populate_obj(user) user.regenerate_security_code() user.set_password(user.user_password) user.status = 1 if form.status.data else 0 request.session.flash(_('User created')) DBSession.flush() return user.get_dict(exclude_keys=[ 'security_code_date', 'notes', 'security_code', 'user_password' ]) else: return HTTPUnprocessableEntity(body=form.errors_json)
def users_update(request): """ Updates user object """ user = User.by_id(request.matchdict.get('user_id')) if not user: return HTTPNotFound() post_data = request.safe_json_body or {} if request.method == 'PATCH': form = forms.UserUpdateForm(MultiDict(post_data), csrf_context=request) if form.validate(): form.populate_obj(user, ignore_none=True) if form.user_password.data: user.set_password(user.user_password) if form.status.data: user.status = 1 else: user.status = 0 else: return HTTPUnprocessableEntity(body=form.errors_json) return user.get_dict(exclude_keys=['security_code_date', 'notes', 'security_code', 'user_password'])
def relogin_to_user(request): user = User.by_id(request.GET.get('user_id')) if not user: return HTTPNotFound() headers = security.remember(request, user.id) return HTTPFound(location=request.route_url('/'), headers=headers)
def found_username_validator(form, field): user = User.by_user_name(field.data) # sets user to recover in email validator form.field_user = user if not user: raise wtforms.ValidationError('This username does not exist')
def found_username_email_validator(form, field): user = User.by_email(field.data) if not user: raise wtforms.ValidationError('Email is incorrect')
def unique_username_validator(form, field): user = User.by_user_name(field.data) if user: raise wtforms.ValidationError('This username already exists in system')
def unique_email_validator(form, field): user = User.by_email(field.data) if user: raise wtforms.ValidationError('This email already exists in system')
def register(request): """ Render register page with form Also handles oAuth flow for registration """ login_url = request.route_url("ziggurat.routes.sign_in") if request.query_string: query_string = "?%s" % request.query_string else: query_string = "" referrer = "%s%s" % (request.path, query_string) if referrer in [login_url, "/register", "/register?sign_in=1"]: referrer = "/" # never use the login form itself as came_from sign_in_form = forms.SignInForm( came_from=request.params.get("came_from", referrer), csrf_context=request ) # populate form from oAuth session data returned by authomatic social_data = request.session.get("zigg.social_auth") if request.method != "POST" and social_data: log.debug(social_data) user_name = social_data["user"].get("user_name", "").split("@")[0] form_data = {"user_name": user_name, "email": social_data["user"].get("email")} form_data["user_password"] = str(uuid.uuid4()) form = forms.UserRegisterForm(MultiDict(form_data), csrf_context=request) form.user_password.widget.hide_value = False else: form = forms.UserRegisterForm(request.POST, csrf_context=request) if request.method == "POST" and form.validate(): log.info("registering user") # insert new user here if request.registry.settings["appenlight.disable_registration"]: request.session.flash(_("Registration is currently disabled.")) return HTTPFound(location=request.route_url("/")) new_user = User() DBSession.add(new_user) form.populate_obj(new_user) UserService.regenerate_security_code(new_user) new_user.status = 1 UserService.set_password(new_user, new_user.user_password) new_user.registration_ip = request.environ.get("REMOTE_ADDR") if social_data: handle_social_data(request, new_user, social_data) email_vars = { "user": new_user, "request": request, "email_title": "AppEnlight :: Start information", } UserService.send_email( request, recipients=[new_user.email], variables=email_vars, template="/email_templates/registered.jinja2", ) request.session.flash(_("You have successfully registered.")) DBSession.flush() headers = security.remember(request, new_user.id) return HTTPFound(location=request.route_url("/"), headers=headers) settings = request.registry.settings social_plugins = {} if settings.get("authomatic.pr.twitter.key", ""): social_plugins["twitter"] = True if settings.get("authomatic.pr.google.key", ""): social_plugins["google"] = True if settings.get("authomatic.pr.github.key", ""): social_plugins["github"] = True if settings.get("authomatic.pr.bitbucket.key", ""): social_plugins["bitbucket"] = True return { "form": form, "sign_in_form": sign_in_form, "social_plugins": social_plugins, }
def register(request): """ Render register page with form Also handles oAuth flow for registration """ login_url = request.route_url('ziggurat.routes.sign_in') if request.query_string: query_string = '?%s' % request.query_string else: query_string = '' referrer = '%s%s' % (request.path, query_string) if referrer in [login_url, '/register', '/register?sign_in=1']: referrer = '/' # never use the login form itself as came_from sign_in_form = forms.SignInForm(came_from=request.params.get( 'came_from', referrer), csrf_context=request) # populate form from oAuth session data returned by authomatic social_data = request.session.get('zigg.social_auth') if request.method != 'POST' and social_data: log.debug(social_data) user_name = social_data['user'].get('user_name', '').split('@')[0] form_data = { 'user_name': user_name, 'email': social_data['user'].get('email') } form_data['user_password'] = str(uuid.uuid4()) form = forms.UserRegisterForm(MultiDict(form_data), csrf_context=request) form.user_password.widget.hide_value = False else: form = forms.UserRegisterForm(request.POST, csrf_context=request) if request.method == 'POST' and form.validate(): log.info('registering user') # insert new user here if request.registry.settings['appenlight.disable_registration']: request.session.flash(_('Registration is currently disabled.')) return HTTPFound(location=request.route_url('/')) new_user = User() DBSession.add(new_user) form.populate_obj(new_user) new_user.regenerate_security_code() new_user.status = 1 new_user.set_password(new_user.user_password) new_user.registration_ip = request.environ.get('REMOTE_ADDR') if social_data: handle_social_data(request, new_user, social_data) email_vars = { 'user': new_user, 'request': request, 'email_title': "AppEnlight :: Start information" } UserService.send_email(request, recipients=[new_user.email], variables=email_vars, template='/email_templates/registered.jinja2') request.session.flash(_('You have successfully registered.')) DBSession.flush() headers = security.remember(request, new_user.id) return HTTPFound(location=request.route_url('/'), headers=headers) settings = request.registry.settings social_plugins = {} if settings.get('authomatic.pr.twitter.key', ''): social_plugins['twitter'] = True if settings.get('authomatic.pr.google.key', ''): social_plugins['google'] = True if settings.get('authomatic.pr.github.key', ''): social_plugins['github'] = True if settings.get('authomatic.pr.bitbucket.key', ''): social_plugins['bitbucket'] = True return { "form": form, "sign_in_form": sign_in_form, "social_plugins": social_plugins }