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}
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.' } }
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, })
def testSignupWorks(self): """Signing up stores an activation.""" email = '*****@*****.**' UserMgr.signup_user(email, 'testcase') activations = Activation.query.all() self.assertTrue(len(activations) == 1) act = activations[0] self.assertEqual(email, act.user.email, "The activation email is the correct one.")
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, }
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)
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) 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) return { 'message': "Account activated, please log in.", 'username': username, } else: AuthLog.reactivate(username, success=False, code=activation) request.response.status_int = 500 return { 'error': "There was an issue attempting to activate this account.", }
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)
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""", }
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." }
def accounts_invites(request): """Return a list of the accounts that aren't activated.""" user_list = UserMgr.get_list() ret = { 'users': [(u.username, u.invite_ct) for u in user_list], } return ret
def accounts_inactive(request): """Return a list of the accounts that aren't activated.""" user_list = UserMgr.get_list(active=False) ret = { 'count': len(user_list), 'users': [dict(h) for h in user_list], } return ret
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))
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." }
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""", }
def _get_userlist(args): """Fetch a list of users from the system and output to stdout""" _init_sql(args) for user in UserMgr.get_list(): print("{0:<10} {1:<20} {2:<50}".format( user.username, user.name, user.email))
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.'}}
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.'
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
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)
def user_list(request): """Provide list of users in the system. Supported Query params: order, limit """ params = request.params order = params.get('order', None) limit = params.get('limit', None) user_list = UserMgr.get_list(order=order, limit=limit) ret = { 'count': len(user_list), 'users': [dict(h) for h in user_list], } return ret
def user_list(request): """Provide list of users in the system. Supported Query params: order, limit """ params = request.params order = params.get('order', None) limit = params.get('limit', None) user_list = UserMgr.get_list(order=order, limit=limit) ret = { 'count': len(user_list), 'users': [dict(h) for h in user_list], } return _api_response(request, ret)
def test_activation_delete(self): """Make sure removing an activation does not remove a user.""" tst = User() tst.username = gen_random_word(10) tst.activation = Activation('signup') DBSession.add(tst) DBSession.flush() DBSession.delete(tst.activation) users = UserMgr.get_list() # We still have the admin user as well so the count is two. eq_(2, len(users), 'We should have a total of 2 users still: ' + str(len(users)))
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, }
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
def reset_password(request): """Change a user's password from the current string :params current_password: :params new_password: Callable by either a logged in user or the api key for mobile apps/etc """ params = request.params # now also load the password info current = params.get('current_password', None) new = params.get('new_password', None) # if we don't have any password info, try a json_body in case it's a json #POST if current is None and new is None: params = request.json_body current = params.get('current_password', None) new = params.get('new_password', None) user_acct = request.user LOG.error("PASSWD") LOG.error(current) LOG.error(new) if not UserMgr.acceptable_password(new): request.response.status_int = 406 return { 'username': user_acct.username, 'error': "Come on, let's try a real password this time" } # before we change the password, let's verify it if user_acct.validate_password(current): # we're good to change it user_acct.password = new return { 'username': user_acct.username, 'message': "Password changed", } else: request.response.status_int = 403 return { 'username': user_acct.username, 'error': "There was a typo somewhere. Please check your request" }
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))
def test_activation_delete(self): """Make sure removing an activation does not remove a user.""" tst = User() tst.username = gen_random_word(10) tst.activation = Activation(u'signup') DBSession.add(tst) DBSession.flush() DBSession.delete(tst.activation) users = UserMgr.get_list() # We still have the admin user as well so the count is two. self.assertEqual( 2, len(users), 'We should have a total of 2 users still: ' + str(len(users)))
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) })
def test_activation_cascade(self): """Removing a user cascades the activations as well.""" tst = User() tst.username = gen_random_word(10) tst.activation = Activation('signup') DBSession.add(tst) DBSession.flush() DBSession.delete(tst) users = UserMgr.get_list() # We still have the admin user as well so the count is one. eq_(1, len(users), 'We should have a total of 1 user still: ' + str(len(users))) activations = DBSession.query(Activation).all() eq_(0, len(activations), 'There should be no activations left')
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))
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)})
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()
def test_activation_cascade(self): """Removing a user cascades the activations as well.""" tst = User() tst.username = gen_random_word(10) tst.activation = Activation('signup') DBSession.add(tst) DBSession.flush() DBSession.delete(tst) users = UserMgr.get_list() # We still have the admin user as well so the count is one. eq_( 1, len(users), 'We should have a total of 1 user still: ' + str(len(users))) activations = DBSession.query(Activation).all() eq_(0, len(activations), 'There should be no activations left')
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()
def dashboard(self): """A public dashboard of the system""" # Generate some user data and stats user_count = UserMgr.count() pending_activations = ActivationMgr.count() # Generate some bookmark data. bookmark_count = BmarkMgr.count() unique_url_count = BmarkMgr.count(distinct=True) users_with_bookmarks = BmarkMgr.count(distinct_users=True) return { 'bookmark_data': { 'count': bookmark_count, 'unique_count': unique_url_count, }, 'user_data': { 'count': user_count, 'activations': pending_activations, 'with_bookmarks': users_with_bookmarks, } }
def dashboard(request): """A public dashboard of the system """ # Generate some user data and stats user_count = UserMgr.count() pending_activations = ActivationMgr.count() # Generate some bookmark data. bookmark_count = BmarkMgr.count() unique_url_count = BmarkMgr.count(distinct=True) users_with_bookmarks = BmarkMgr.count(distinct_users=True) return { 'bookmark_data': { 'count': bookmark_count, 'unique_count': unique_url_count, }, 'user_data': { 'count': user_count, 'activations': pending_activations, 'with_bookmarks': users_with_bookmarks, } }
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
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, }
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, }
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()
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}