Exemplo n.º 1
0
def login(request):
    """Login the user to the system

    If not POSTed then show the form
    If error, display the form with the error message
    If successful, forward the user to their /recent

    Note: the came_from stuff we're not using atm. We'll clean out if we keep
    things this way

    """
    login_url = route_url("login", request)
    referrer = request.url
    if referrer == login_url:
        referrer = u"/"  # never use the login form itself as came_from

    came_from = request.params.get("came_from", referrer)

    message = u""
    login = u""
    password = u""

    if "form.submitted" in request.params:
        login = request.params["login"]
        password = request.params["password"]

        LOG.debug(login)
        auth = UserMgr.get(username=login)
        LOG.debug(auth)
        LOG.debug(UserMgr.get_list())

        if auth and auth.validate_password(password) and auth.activated:
            # We use the Primary Key as our identifier once someone has
            # authenticated rather than the username.  You can change what is
            # returned as the userid by altering what is passed to remember.
            headers = remember(request, auth.id, max_age=60 * 60 * 24 * 30)
            auth.last_login = datetime.utcnow()

            # log the successful login
            AuthLog.login(login, True)

            # we're always going to return a user to their own /recent after a
            # login
            return HTTPFound(location=request.route_url("user_bmark_recent", username=auth.username), headers=headers)

        # log the right level of problem
        if auth and not auth.validate_password(password):
            message = "Your login attempt has failed."
            AuthLog.login(login, False, password=password)

        elif auth and not auth.activated:
            message = "User account deactivated. Please check your email."
            AuthLog.login(login, False, password=password)
            AuthLog.disabled(login)

        elif auth is None:
            message = "Failed login"
            AuthLog.login(login, False, password=password)

    return {"message": message, "came_from": came_from, "login": login, "password": password}
Exemplo n.º 2
0
 def test_get_username(self):
     """Fetching the user by the username"""
     user = UserMgr.get(username='******')
     eq_(user.id, 1,
         "Should have a user id of 1: " + str(user.id))
     eq_(user.username, 'admin',
         "Should have a username of admin: " + user.username)
Exemplo n.º 3
0
Arquivo: api.py Projeto: cambot/Bookie
def suspend_acct(request):
    """Reset a user account to enable them to change their password"""
    params = request.params
    user = request.user

    # we need to get the user from the email
    email = params.get('email', None)

    if email is None and hasattr(request, 'json_body'):
        # try the json body
        email = request.json_body.get('email', None)

    if user is None and email is None:
        request.response.status_int = 406
        return {
            'error':  "Please submit an email address",
        }

    if user is None and email is not None:
        user = UserMgr.get(email=email)

    if user is None:
        request.response.status_int = 404
        return {
            'error':  "Please submit a valid address",
            'email': email
        }

    # check if we've already gotten an activation for this user
    if user.activation is not None:
        request.response.status_int = 406
        return {
            'error':  """You've already marked your account for reactivation.
Please check your email for the reactivation link. Make sure to
check your spam folder.""",
            'username': user.username,
        }

    # mark them for reactivation
    user.reactivate("FORGOTTEN")

    # log it
    AuthLog.reactivate(user.username)

    # and then send an email notification
    # @todo the email side of things
    settings = request.registry.settings
    msg = ReactivateMsg(user.email,
                        "Activate your Bookie account",
                        settings)

    msg.send(request.route_url('reset',
                         username=user.username,
                         reset_key=user.activation.code))

    return {
        'message':  """Your account has been marked for reactivation. Please
                    check your email for instructions to reset your
                    password""",
    }
Exemplo n.º 4
0
Arquivo: api.py Projeto: cambot/Bookie
def invite_user(request):
    """Invite a new user into the system.

    :param username: user that is requested we invite someone
    :param email: email address of the new user

    """
    params = request.params

    email = params.get('email', None)
    user = request.user

    if not email:
        # try to get it from the json body
        email = request.json_body.get('email', None)

    if not email:
        # if still no email, I give up!
        request.response.status_int = 406
        return {
            'username': user.username,
            'error': "Please submit an email address"
        }

    # first see if the user is already in the system
    exists = UserMgr.get(email=email)
    if exists:
        request.response.status_int = 406
        return {
            'username': exists.username,
            'error': "This user is already a Bookie user!"
        }

    new_user = user.invite(email)
    if new_user:
        LOG.error(new_user.username)
        # then this user is able to invite someone
        # log it
        AuthLog.reactivate(new_user.username)

        # and then send an email notification
        # @todo the email side of things
        settings = request.registry.settings
        msg = InvitationMsg(new_user.email,
                            "Enable your Bookie account",
                            settings)

        msg.send(request.route_url('reset',
            username=new_user.username,
            reset_key=new_user.activation.code))
        return {
            'message': 'You have invited: ' + new_user.email
        }
    else:
        # you have no invites
        request.response.status_int = 406
        return {
            'username': user.username,
            'error': "You have no invites left at this time."
        }
Exemplo n.º 5
0
 def test_get_id(self):
     """Fetching user by the id"""
     # the migration adds an initial admin user to the system
     user = UserMgr.get(user_id=1)
     eq_(user.id, 1, "Should have a user id of 1: " + str(user.id))
     eq_(user.username, 'admin',
         "Should have a username of admin: " + user.username)
Exemplo n.º 6
0
def signup_process(request):
    """Process the signup request

    If there are any errors drop to the same template with the error
    information.

    """
    params = request.params
    email = params.get('email', None)

    if not email:
        # if still no email, I give up!
        return {
            'errors': {
                'email': 'Please supply an email address to sign up.'
            }
        }

    # first see if the user is already in the system
    exists = UserMgr.get(email=email)
    if exists:
        return {
            'errors': {
                'email': 'The user has already signed up.'
            }
        }

    new_user = UserMgr.signup_user(email, 'signup')
    if new_user:
        # then this user is able to invite someone
        # log it
        AuthLog.reactivate(new_user.username)

        # and then send an email notification
        # @todo the email side of things
        settings = request.registry.settings

        # Add a queue job to send the user a notification email.
        tasks.email_signup_user.delay(
            new_user.email,
            "Enable your Bookie account",
            settings,
            request.route_url(
                'reset',
                username=new_user.username,
                reset_key=new_user.activation.code
            )
        )

        # And let the user know they're signed up.
        return {
            'message': 'Thank you for signing up from: ' + new_user.email
        }
    else:
        return {
            'errors': {
                'email': 'There was an unknown error signing up.'
            }
        }
Exemplo n.º 7
0
 def test_get_id(self):
     """Fetching user by the id"""
     # the migration adds an initial admin user to the system
     user = UserMgr.get(user_id=1)
     eq_(user.id, 1,
         "Should have a user id of 1: " + str(user.id))
     eq_(user.username, 'admin',
         "Should have a username of admin: " + user.username)
Exemplo n.º 8
0
    def test_get_bad_user(self):
        """We shouldn't get a hit if the user is inactive"""
        user = UserMgr.get(username=u'noexist')

        self.assertEqual(
            user,
            None,
            "Should not find a non-existant user: " + str(user))
Exemplo n.º 9
0
def invite_user(request):
    """Invite a new user into the system.

    :param username: user that is requested we invite someone
    :param email: email address of the new user

    """
    params = request.params

    email = params.get('email', None)
    user = request.user

    if not email:
        # try to get it from the json body
        email = request.json_body.get('email', None)

    if not email:
        # if still no email, I give up!
        request.response.status_int = 406
        return {
            'username': user.username,
            'error': "Please submit an email address"
        }

    # first see if the user is already in the system
    exists = UserMgr.get(email=email)
    if exists:
        request.response.status_int = 406
        return {
            'username': exists.username,
            'error': "This user is already a Bookie user!"
        }

    new_user = user.invite(email)
    if new_user:
        LOG.error(new_user.username)
        # then this user is able to invite someone
        # log it
        AuthLog.reactivate(new_user.username)

        # and then send an email notification
        # @todo the email side of things
        settings = request.registry.settings
        msg = InvitationMsg(new_user.email, "Enable your Bookie account",
                            settings)

        msg.send(
            request.route_url('reset',
                              username=new_user.username,
                              reset_key=new_user.activation.code))
        return {'message': 'You have invited: ' + new_user.email}
    else:
        # you have no invites
        request.response.status_int = 406
        return {
            'username': user.username,
            'error': "You have no invites left at this time."
        }
Exemplo n.º 10
0
def suspend_acct(request):
    """Reset a user account to enable them to change their password"""
    params = request.params
    user = request.user

    # we need to get the user from the email
    email = params.get('email', None)

    if email is None and hasattr(request, 'json_body'):
        # try the json body
        email = request.json_body.get('email', None)

    if user is None and email is None:
        request.response.status_int = 406
        return {
            'error': "Please submit an email address",
        }

    if user is None and email is not None:
        user = UserMgr.get(email=email)

    if user is None:
        request.response.status_int = 404
        return {'error': "Please submit a valid address", 'email': email}

    # check if we've already gotten an activation for this user
    if user.activation is not None:
        request.response.status_int = 406
        return {
            'error': """You've already marked your account for reactivation.
Please check your email for the reactivation link. Make sure to
check your spam folder.""",
            'username': user.username,
        }

    # mark them for reactivation
    user.reactivate("FORGOTTEN")

    # log it
    AuthLog.reactivate(user.username)

    # and then send an email notification
    # @todo the email side of things
    settings = request.registry.settings
    msg = ReactivateMsg(user.email, "Activate your Bookie account", settings)

    msg.send(
        request.route_url('reset',
                          username=user.username,
                          reset_key=user.activation.code))

    return {
        'message':
        """Your account has been marked for reactivation. Please
                    check your email for instructions to reset your
                    password""",
    }
Exemplo n.º 11
0
 def user(self):
     # <your database connection, however you get it, the below line
     # is just an example>
     # dbconn = self.registry.settings['dbconn']
     user_id = unauthenticated_userid(self)
     if user_id is not None:
         # this should return None if the user doesn't exist
         # in the database
         user = UserMgr.get(user_id=user_id)
         return user
Exemplo n.º 12
0
 def user(self):
     # <your database connection, however you get it, the below line
     # is just an example>
     # dbconn = self.registry.settings['dbconn']
     user_id = unauthenticated_userid(self)
     if user_id is not None:
         # this should return None if the user doesn't exist
         # in the database
         user = UserMgr.get(user_id=user_id)
         return user
Exemplo n.º 13
0
def account_activate(request):
    """Reset a user after being suspended

    :param username: required to know what user we're resetting
    :param activation: code needed to activate
    :param password: new password to use for the user

    """
    params = request.params

    username = params.get('username', None)
    activation = params.get('code', None)
    password = params.get('password', None)
    new_username = params.get('new_username', None)

    if username is None and activation is None and password is None:
        # then try to get the same fields out of a json body
        json_body = request.json_body
        username = json_body.get('username', None)
        activation = json_body.get('code', None)
        password = json_body.get('password', None)
        new_username = json_body.get('new_username', None)

    if not UserMgr.acceptable_password(password):
        request.response.status_int = 406
        return _api_response(request, {
            'error': "Come on, pick a real password please",
        })

    res = ActivationMgr.activate_user(username, activation, password)

    if res:
        # success so respond nicely
        AuthLog.reactivate(username, success=True, code=activation)

        # if there's a new username and it's not the same as our current
        # username, update it
        if new_username and new_username != username:
            try:
                user = UserMgr.get(username=username)
                user.username = new_username
            except IntegrityError, exc:
                request.response.status_int = 500
                return _api_response(
                    request, {
                        'error':
                        'There was an issue setting your new username',
                        'exc': str(exc)
                    })

        return _api_response(request, {
            'message': "Account activated, please log in.",
            'username': username,
        })
Exemplo n.º 14
0
 def test_get_username(self):
     """Fetching the user by the username"""
     user = UserMgr.get(username=u'admin')
     self.assertEqual(
         user.id,
         1,
         "Should have a user id of 1: " + str(user.id))
     self.assertEqual(
         user.username,
         'admin',
         "Should have a username of admin: " + user.username)
Exemplo n.º 15
0
Arquivo: api.py Projeto: cambot/Bookie
def account_activate(request):
    """Reset a user after being suspended

    :param username: required to know what user we're resetting
    :param activation: code needed to activate
    :param password: new password to use for the user

    """
    params = request.params

    username = params.get('username', None)
    activation = params.get('code', None)
    password = params.get('password', None)
    new_username = params.get('new_username', None)

    if username is None and activation is None and password is None:
        # then try to get the same fields out of a json body
        json_body = request.json_body
        username = json_body.get('username', None)
        activation = json_body.get('code', None)
        password = json_body.get('password', None)
        new_username = json_body.get('new_username', None)

    if not UserMgr.acceptable_password(password):
        request.response.status_int = 406
        return {
            'error': "Come on, pick a real password please",
        }

    res = ActivationMgr.activate_user(username, activation, password)

    if res:
        # success so respond nicely
        AuthLog.reactivate(username, success=True, code=activation)

        # if there's a new username and it's not the same as our current
        # username, update it
        if new_username and new_username != username:
            try:
                user = UserMgr.get(username=username)
                user.username = new_username
            except IntegrityError, exc:
                request.response.status_int = 500
                return {
                    'error': 'There was an issue setting your new username',
                    'exc': str(exc)
                }

        return {
            'message': "Account activated, please log in.",
            'username': username,
        }
Exemplo n.º 16
0
    def user(self):
        # <your database connection, however you get it, the below line
        # is just an example>
        # dbconn = self.registry.settings['dbconn']
        LOG.debug('in Request with Attribute')
        user_id = unauthenticated_userid(self)
        LOG.debug(user_id)
        if user_id is not None:
            LOG.debug('user_id is not none')

            # this should return None if the user doesn't exist
            # in the database
            user = UserMgr.get(user_id=user_id)
            LOG.debug(user)
            return user
Exemplo n.º 17
0
def account(request):
    """Index of account page

    You can only load your own account page. If you try to view someone else's
    you'll just end up with your own.

    """
    # if auth fails, it'll raise an HTTPForbidden exception
    with ReqAuthorize(request):
        user = UserMgr.get(username=request.user.username)

        return {
            'user': user,
            'username': user.username,
        }
Exemplo n.º 18
0
def home(request):
    """Inital / view for now until we find a better one"""
    rdict = request.matchdict
    username = rdict.get('username', None)

    if not username:
        return HTTPFound(location=request.route_url("bmark_recent"))
    else:
        # we need to see if we have a user by this name
        user = UserMgr.get(username=username)

        if not user:
            return HTTPNotFound()
        else:
            return HTTPFound(location=request.route_url("user_bmark_recent",
                                                        username=username))
Exemplo n.º 19
0
def del_user(request):
    """Remove a bad user from the system via the api.

    For admin use only.

    Removes all of a user's bookmarks before removing the user.

    """
    mdict = request.matchdict

    # Submit a username.
    del_username = mdict.get('username', None)

    if del_username is None:
        LOG.error('No username to remove.')
        request.response.status_int = 400
        return _api_response(request, {
            'error': 'Bad Request: No username to remove.',
        })

    u = UserMgr.get(username=del_username)

    if not u:
        LOG.error('Username not found.')
        request.response.status_int = 404
        return _api_response(request, {
            'error': 'User not found.',
        })

    try:
        # Delete all of the bmarks for this year.
        Bmark.query.filter(Bmark.username == u.username).delete()
        DBSession.delete(u)
        return _api_response(request, {
            'success': True,
            'message': 'Removed user: '******'error': 'Bad Request: ' + str(exc)
        })
Exemplo n.º 20
0
def signup_process(request):
    """Process the signup request

    If there are any errors drop to the same template with the error
    information.

    """
    params = request.params
    email = params.get('email', None)

    if not email:
        # if still no email, I give up!
        return {
            'errors': {
                'email': 'Please supply an email address to sign up.'
            }
        }

    # first see if the user is already in the system
    exists = UserMgr.get(email=email)
    if exists:
        return {'errors': {'email': 'The user has already signed up.'}}

    new_user = UserMgr.signup_user(email, 'signup')
    if new_user:
        # then this user is able to invite someone
        # log it
        AuthLog.reactivate(new_user.username)

        # and then send an email notification
        # @todo the email side of things
        settings = request.registry.settings

        # Add a queue job to send the user a notification email.
        tasks.email_signup_user.delay(
            new_user.email, "Enable your Bookie account", settings,
            request.route_url('reset',
                              username=new_user.username,
                              reset_key=new_user.activation.code))

        # And let the user know they're signed up.
        return {'message': 'Thank you for signing up from: ' + new_user.email}
    else:
        return {'errors': {'email': 'There was an unknown error signing up.'}}
Exemplo n.º 21
0
def home(request):
    """Inital / view for now until we find a better one"""
    rdict = request.matchdict
    username = rdict.get('username', None)

    if not request.user:
        return {}
    else:
        if not username:
            return HTTPFound(location=request.route_url("bmark_recent"))
        else:
            # we need to see if we have a user by this name
            user = UserMgr.get(username=username)

            if not user:
                return HTTPNotFound()
            else:
                return HTTPFound(location=request.route_url(
                    "user_bmark_recent", username=username))
Exemplo n.º 22
0
def reset(request):
    """Once deactivated, allow for changing the password via activation key"""
    rdict = request.matchdict
    params = request.params

    # This is an initial request to show the activation form.
    username = rdict.get('username', None)
    activation_key = rdict.get('reset_key', None)
    user = ActivationMgr.get_user(username, activation_key)

    if user is None:
        # just 404 if we don't have an activation code for this user
        raise HTTPNotFound()

    if 'code' in params:
        # This is a posted form with the activation, attempt to unlock the
        # user's account.
        username = params.get('username', None)
        activation = params.get('code', None)
        password = params.get('new_password', None)
        new_username = params.get('new_username', None)
        error = None

        if not UserMgr.acceptable_password(password):
            # Set an error message to the template.
            error = "Come on, pick a real password please."
        else:
            res = ActivationMgr.activate_user(username, activation, password)
            if res:
                # success so respond nicely
                AuthLog.reactivate(username, success=True, code=activation)

                # if there's a new username and it's not the same as our current
                # username, update it
                if new_username and new_username != username:
                    try:
                        user = UserMgr.get(username=username)
                        user.username = new_username
                    except IntegrityError, exc:
                        error = 'There was an issue setting your new username'
            else:
                AuthLog.reactivate(username, success=False, code=activation)
                error = 'There was an issue attempting to activate this account.'
Exemplo n.º 23
0
def del_user(request):
    """Remove a bad user from the system via the api.

    For admin use only.

    Removes all of a user's bookmarks before removing the user.

    """
    mdict = request.matchdict

    # Submit a username.
    del_username = mdict.get('username', None)

    if del_username is None:
        LOG.error('No username to remove.')
        request.response.status_int = 400
        return _api_response(request, {
            'error': 'Bad Request: No username to remove.',
        })

    u = UserMgr.get(username=del_username)

    if not u:
        LOG.error('Username not found.')
        request.response.status_int = 404
        return _api_response(request, {
            'error': 'User not found.',
        })

    try:
        # Delete all of the bmarks for this year.
        Bmark.query.filter(Bmark.username == u.username).delete()
        DBSession.delete(u)
        return _api_response(request, {
            'success': True,
            'message': 'Removed user: '******'error': 'Bad Request: ' + str(exc)})
Exemplo n.º 24
0
def reset(request):
    """Once deactivated, allow for changing the password via activation key"""
    rdict = request.matchdict
    params = request.params

    # This is an initial request to show the activation form.
    username = rdict.get('username', None)
    activation_key = rdict.get('reset_key', None)
    user = ActivationMgr.get_user(username, activation_key)

    if user is None:
        # just 404 if we don't have an activation code for this user
        raise HTTPNotFound()

    if 'code' in params:
        # This is a posted form with the activation, attempt to unlock the
        # user's account.
        username = params.get('username', None)
        activation = params.get('code', None)
        password = params.get('new_password', None)
        new_username = params.get('new_username', None)
        error = None

        if not UserMgr.acceptable_password(password):
            # Set an error message to the template.
            error = "Come on, pick a real password please."
        else:
            res = ActivationMgr.activate_user(username, activation, password)
            if res:
                # success so respond nicely
                AuthLog.reactivate(username, success=True, code=activation)

                # if there's a new username and it's not the same as our current
                # username, update it
                if new_username and new_username != username:
                    try:
                        user = UserMgr.get(username=username)
                        user.username = new_username
                    except IntegrityError, exc:
                        error = 'There was an issue setting your new username'
            else:
                AuthLog.reactivate(username, success=False, code=activation)
                error = 'There was an issue attempting to activate this account.'
Exemplo n.º 25
0
def reset_password(username, password):
    """Reset a user's password"""
    require('hosts', provided_by=[sample])
    require('ini', provided_by=[sample])

    parse_ini(env["ini_file"])

    import transaction
    from bookie.models import initialize_sql
    initialize_sql(dict(env.ini.items('app:main')))

    from bookie.models import DBSession
    from bookie.models.auth import UserMgr
    sess = DBSession()

    u = UserMgr.get(username=username)
    u.password = password
    sess.flush()
    transaction.commit()
Exemplo n.º 26
0
def _reset_password(args):
    """Reset a user's password"""

    if not args.username:
        args.username = raw_input('username? ')

    if not args.password:
        args.password = raw_input('password? ')

    if not args.username or not args.password:
        raise Exception('Must supply a username and password')

    import transaction
    _init_sql(args)
    from bookie.models import DBSession
    sess = DBSession()

    u = UserMgr.get(username=unicode(args.username))
    u.password = args.password
    sess.flush()
    transaction.commit()
Exemplo n.º 27
0
def accounts_invites_add(request):
    """Set the number of invites a user has available.

    :matchdict username: The user to give these invites to.
    :matchdict count: The number of invites to give them.
    """
    rdict = request.matchdict
    username = rdict.get('username', None)
    count = rdict.get('count', None)

    if username is not None and count is not None:
        user = UserMgr.get(username=username)

        if user:
            user.invite_ct = count
            return dict(user)
        else:
            request.response.status_int = 404
            ret = {'error': "Invalid user account."}
            return ret
    else:
        request.response.status_int = 400
        ret = {'error': "Bad request, missing parameters"}
        return ret
Exemplo n.º 28
0
Arquivo: api.py Projeto: cambot/Bookie
def accounts_invites_add(request):
    """Set the number of invites a user has available.

    :matchdict username: The user to give these invites to.
    :matchdict count: The number of invites to give them.
    """
    rdict = request.matchdict
    username = rdict.get('username', None)
    count = rdict.get('count', None)

    if username is not None and count is not None:
        user = UserMgr.get(username=username)

        if user:
            user.invite_ct = count
            return dict(user)
        else:
            request.response.status_int = 404
            ret = {'error': "Invalid user account."}
            return ret
    else:
        request.response.status_int = 400
        ret = {'error': "Bad request, missing parameters"}
        return ret
Exemplo n.º 29
0
def reset(request):
    """Once deactivated, allow for changing the password via activation key"""
    rdict = request.matchdict
    params = request.params

    # This is an initial request to show the activation form.
    username = rdict.get('username', None)
    activation_key = rdict.get('reset_key', None)
    user = ActivationMgr.get_user(username, activation_key)

    if user is None:
        # just 404 if we don't have an activation code for this user
        raise HTTPNotFound()

    if 'code' in params:
        # This is a posted form with the activation, attempt to unlock the
        # user's account.
        username = params.get('username', None)
        activation = params.get('code', None)
        password = params.get('new_password', None)
        new_username = params.get('new_username', None)
        error = None

        if not UserMgr.acceptable_password(password):
            # Set an error message to the template.
            error = "Come on, pick a real password please."
        else:
            res = ActivationMgr.activate_user(username, activation, password)
            if res:
                # success so respond nicely
                AuthLog.reactivate(username, success=True, code=activation)

                # if there's a new username and it's not the same as our
                # current username, update it
                if new_username and new_username != username:
                    try:
                        user = UserMgr.get(username=username)
                        user.username = new_username
                    except IntegrityError:
                        error = 'There was an issue setting your new username'
            else:
                AuthLog.reactivate(username, success=False, code=activation)
                error = ('There was an issue attempting to activate'
                         'this account.')

        if error:
            return {'message': error, 'user': user}
        else:
            # Log the user in and move along.
            headers = remember(request, user.id, max_age=60 * 60 * 24 * 30)
            user.last_login = datetime.utcnow()

            # log the successful login
            AuthLog.login(user.username, True)

            # we're always going to return a user to their own /recent after a
            # login
            return HTTPFound(location=request.route_url(
                'user_bmark_recent', username=user.username),
                             headers=headers)

    else:
        LOG.error("CHECKING")
        LOG.error(username)

        if user is None:
            # just 404 if we don't have an activation code for this user
            raise HTTPNotFound()

        LOG.error(user.username)
        LOG.error(user.email)
        return {
            'user': user,
        }
Exemplo n.º 30
0
def login(request):
    """Login the user to the system

    If not POSTed then show the form
    If error, display the form with the error message
    If successful, forward the user to their /recent

    Note: the came_from stuff we're not using atm. We'll clean out if we keep
    things this way

    """
    login_url = route_url('login', request)
    referrer = request.url
    if referrer == login_url:
        referrer = '/'  # never use the login form itself as came_from

    came_from = request.params.get('came_from', referrer)

    message = ''
    login = ''
    password = ''

    if 'form.submitted' in request.params:
        login = request.params['login']
        password = request.params['password']

        LOG.debug(login)
        auth = UserMgr.get(username=login)
        LOG.debug(auth)
        LOG.debug(UserMgr.get_list())

        if auth and auth.validate_password(password) and auth.activated:
            # We use the Primary Key as our identifier once someone has
            # authenticated rather than the username.  You can change what is
            # returned as the userid by altering what is passed to remember.
            headers = remember(request, auth.id, max_age=60 * 60 * 24 * 30)
            auth.last_login = datetime.utcnow()

            # log the successful login
            AuthLog.login(login, True)

            # we're always going to return a user to their own /recent after a
            # login
            return HTTPFound(location=request.route_url(
                'user_bmark_recent', username=auth.username),
                             headers=headers)

        # log the right level of problem
        if auth and not auth.validate_password(password):
            message = "Your login attempt has failed."
            AuthLog.login(login, False, password=password)

        elif auth and not auth.activated:
            message = "User account deactivated. Please check your email."
            AuthLog.login(login, False, password=password)
            AuthLog.disabled(login)

        elif auth is None:
            message = "Failed login"
            AuthLog.login(login, False, password=password)

    return {
        'message': message,
        'came_from': came_from,
        'login': login,
        'password': password,
    }
Exemplo n.º 31
0
def importer_process_worker(import_id):
    """Do the real import work

    :param import_id: import id we need to pull and work on

    """
    trans = transaction.begin()
    import_job = ImportQueueMgr.get(import_id)
    logger.info("IMPORT: RUNNING for {username}".format(**dict(import_job)))

    try:
        # process the file using the import script
        import_file = open(import_job.file_path)
        importer = Importer(
            import_file,
            import_job.username)
        importer.process()

        # Processing kills off our transaction so we need to start a new one
        # to update that our import is complete.
        trans = transaction.begin()
        import_job = ImportQueueMgr.get(import_id)
        import_job.mark_done()
        user = UserMgr.get(username=import_job.username)
        from bookie.lib.message import UserImportSuccessMessage
        msg = UserImportSuccessMessage(
            user.email,
            'Bookie: Your requested import has completed.',
            INI)
        msg.send({
            'username': import_job.username,
        })

        logger.info(
            "IMPORT: COMPLETE for {username}".format(**dict(import_job)))
        trans.commit()

    except Exception, exc:
        # We need to log this and probably send an error email to the
        # admin
        from bookie.lib.message import ImportFailureMessage
        from bookie.lib.message import UserImportFailureMessage

        trans = transaction.begin()
        import_job = ImportQueueMgr.get(import_id)
        user = UserMgr.get(username=import_job.username)

        msg = ImportFailureMessage(
            INI.get('email.from'),
            'Import failure!',
            INI)
        msg.send({
            'username': import_job.username,
            'file_path': import_job.file_path,
            'exc': str(exc)
        })

        # Also send an email to the user that their import failed.
        msg = UserImportFailureMessage(
            user.email,
            'Bookie: We are sorry, your import failed.',
            INI)
        msg.send({
            'username': import_job.username,
            'exc': str(exc)
        })

        logger.error(exc)
        logger.error(str(exc))
        import_job.mark_error()
        logger.info(
            "IMPORT: ERROR for {username}".format(**dict(import_job)))
        logger.info(exc)
        trans.commit()
Exemplo n.º 32
0
def reset(request):
    """Once deactivated, allow for changing the password via activation key"""
    rdict = request.matchdict
    params = request.params

    # This is an initial request to show the activation form.
    username = rdict.get("username", None)
    activation_key = rdict.get("reset_key", None)
    user = ActivationMgr.get_user(username, activation_key)

    if user is None:
        # just 404 if we don't have an activation code for this user
        raise HTTPNotFound()

    if "code" in params:
        # This is a posted form with the activation, attempt to unlock the
        # user's account.
        username = params.get("username", None)
        activation = params.get("code", None)
        password = params.get("new_password", None)
        new_username = params.get("new_username", None)
        error = None

        if not UserMgr.acceptable_password(password):
            # Set an error message to the template.
            error = "Come on, pick a real password please."
        else:
            res = ActivationMgr.activate_user(username, activation, password)
            if res:
                # success so respond nicely
                AuthLog.reactivate(username, success=True, code=activation)

                # if there's a new username and it's not the same as our
                # current username, update it
                if new_username and new_username != username:
                    try:
                        user = UserMgr.get(username=username)
                        user.username = new_username
                    except IntegrityError:
                        error = "There was an issue setting your new username"
            else:
                AuthLog.reactivate(username, success=False, code=activation)
                error = "There was an issue attempting to activate" "this account."

        if error:
            return {"message": error, "user": user}
        else:
            # Log the user in and move along.
            headers = remember(request, user.id, max_age=60 * 60 * 24 * 30)
            user.last_login = datetime.utcnow()

            # log the successful login
            AuthLog.login(user.username, True)

            # we're always going to return a user to their own /recent after a
            # login
            return HTTPFound(location=request.route_url("user_bmark_recent", username=user.username), headers=headers)

    else:
        LOG.error("CHECKING")
        LOG.error(username)

        if user is None:
            # just 404 if we don't have an activation code for this user
            raise HTTPNotFound()

        LOG.error(user.username)
        LOG.error(user.email)
        return {"user": user}