예제 #1
0
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)
예제 #2
0
def bad_auth(request):
    """
    Handles incorrect login flow
    """
    request.session.flash(_('Incorrect username or password'), 'warning')
    return HTTPFound(location=request.route_url('register'),
                     headers=request.context.headers)
예제 #3
0
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}
예제 #4
0
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 = UserService.by_id(request.matchdict.get("user_id"))
    if user:
        users = UserService.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
예제 #5
0
def handle_auth_error(request, result):
    # Login procedure finished with an error.
    request.session.pop('zigg.social_auth', None)
    request.session.flash(_('Something went wrong when we tried to '
                            'authorize you via external provider. '
                            'Please try again.'), 'warning')

    return HTTPFound(location=request.route_url('/'))
예제 #6
0
def handle_auth_error(request, result):
    # Login procedure finished with an error.
    request.session.pop("zigg.social_auth", None)
    request.session.flash(
        _("Something went wrong when we tried to "
          "authorize you via external provider. "
          "Please try again."),
        "warning",
    )

    return HTTPFound(location=request.route_url("/"))
예제 #7
0
def alert_channels_authorize(request):
    """
    Performs alert channel authorization based on auth code sent in email
    """
    user = request.user
    for channel in user.alert_channels:
        security_code = request.params.get("security_code", "")
        if channel.channel_json_conf["security_code"] == security_code:
            channel.channel_validated = True
            request.session.flash(_("Your email was authorized."))
    return HTTPFound(location=request.route_url("/"))
예제 #8
0
def alert_channels_POST(request):
    """
    Creates a new email alert channel for user, sends a validation email
    """
    user = request.user
    form = forms.EmailChannelCreateForm(MultiDict(request.unsafe_json_body),
                                        csrf_context=request)
    if not form.validate():
        return HTTPUnprocessableEntity(body=form.errors_json)

    email = form.email.data.strip()
    channel = EmailAlertChannel()
    channel.channel_name = "email"
    channel.channel_value = email
    security_code = generate_random_string(10)
    channel.channel_json_conf = {"security_code": security_code}
    user.alert_channels.append(channel)

    email_vars = {
        "user": user,
        "email": email,
        "request": request,
        "security_code": security_code,
        "email_title": "AppEnlight :: "
        "Please authorize your email",
    }

    UserService.send_email(
        request,
        recipients=[email],
        variables=email_vars,
        template="/email_templates/authorize_email.jinja2",
    )
    request.session.flash(_("Your alert channel was " "added to the system."))
    request.session.flash(
        _("You need to authorize your email channel, a message was "
          "sent containing necessary information."),
        "warning",
    )
    DBSession.flush()
    channel.get_dict()
예제 #9
0
def alert_channel_DELETE(request):
    """
    Removes alert channel from users channel
    """
    user = request.user
    channel = None
    for chan in user.alert_channels:
        if (chan.channel_name == request.params.get('channel_name') and
                    chan.channel_value == request.params.get('channel_value')):
            channel = chan
            break
    if channel:
        user.alert_channels.remove(channel)
        request.session.flash(_('Your channel was removed.'))
        return True
    return False
예제 #10
0
def users_password(request):
    """
    Sets new password for user account
    """
    user = request.user
    form = forms.ChangePasswordForm(MultiDict(request.unsafe_json_body),
                                    csrf_context=request)
    form.old_password.user = user
    if form.validate():
        UserService.regenerate_security_code(user)
        UserService.set_password(user, form.new_password.data)
        msg = ("Your password got updated. "
               "Next time log in with your new credentials.")
        request.session.flash(_(msg))
        return True
    else:
        return HTTPUnprocessableEntity(body=form.errors_json)
    return False
예제 #11
0
def users_self(request):
    """
    Updates user personal information
    """

    if request.method == 'PATCH':
        form = forms.gen_user_profile_form()(
            MultiDict(request.unsafe_json_body),
            csrf_context=request)
        if form.validate():
            form.populate_obj(request.user)
            request.session.flash(_('Your profile got updated.'))
        else:
            return HTTPUnprocessableEntity(body=form.errors_json)
    return request.user.get_dict(
        exclude_keys=['security_code_date', 'notes', 'security_code',
                      'user_password'],
        extended_info=True)
예제 #12
0
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')
예제 #13
0
def sign_in(request):
    """
    Performs sign in by sending proper user identification headers
    Regenerates CSRF token
    """
    user = request.context.user
    if user.status == 1:
        request.session.new_csrf_token()
        user.last_login_date = datetime.datetime.utcnow()
        social_data = request.session.get('zigg.social_auth')
        if social_data:
            handle_social_data(request, user, social_data)
    else:
        request.session.flash(_('Account got disabled'))

    if request.context.came_from != '/':
        return HTTPFound(location=request.context.came_from,
                         headers=request.context.headers)
    else:
        return HTTPFound(location=request.route_url('/'),
                         headers=request.context.headers)
예제 #14
0
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)
예제 #15
0
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
    }
예제 #16
0
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,
    }