def set_new_password(self, password): """This method sets a new password for the User A new salt is also generated This cannot be rolled back """ salt = generate_randomkey(256) hash = SHA.new(salt + password).hexdigest() self.__UserModel.salt = salt self.__UserModel.hash = hash self.__UserModel.put()
def reset_password(): """ This view allows a user that has forgetten their password to request a new one via their case email account """ from application.generate_keys import generate_randomkey from google.appengine.api import mail form = forms.ResetPasswordForm(request.form) if request.method == 'POST' and form.validate(): try: user = accounts.find_users(1, cwruid=('=', form.cwruid.data))[0] new_password = generate_randomkey(16) user.set_new_password(new_password) body = """ Hi %s, Somebody requested a new password for you. You can now use %s when logging in. If you did not request this password change please contact the webmasters immediately. Thanks, The APO Website """ body %= (user.fname, new_password) mail.send_mail(sender="APO Website <*****@*****.**>", to="%s %s <*****@*****.**>" % (user.fname, user.lname, user.cwruid), subject='Your new password', body=body) except IndexError: pass flash( 'If an account with the specified cwru id exists then it should\ receive an email with a new password shortly', 'success') form = forms.ResetPasswordForm() return render_template('accounts/reset_password.html', reset_password_form=form)
def reset_password(): """ This view allows a user that has forgetten their password to request a new one via their case email account """ from application.generate_keys import generate_randomkey from google.appengine.api import mail form = forms.ResetPasswordForm(request.form) if request.method == 'POST' and form.validate(): try: user = accounts.find_users(1, cwruid=('=', form.cwruid.data))[0] new_password = generate_randomkey(16) user.set_new_password(new_password) body = """ Hi %s, Somebody requested a new password for you. You can now use %s when logging in. If you did not request this password change please contact the webmasters immediately. Thanks, The APO Website """ body %= (user.fname, new_password) mail.send_mail(sender="APO Website <*****@*****.**>", to="%s %s <*****@*****.**>" % (user.fname, user.lname, user.cwruid), subject='Your new password', body=body) except IndexError: pass flash('If an account with the specified cwru id exists then it should\ receive an email with a new password shortly', 'success') form = forms.ResetPasswordForm() return render_template('accounts/reset_password.html', reset_password_form=form)
def fb_admin_get_user_access(): """ Main admin view for Facebook settings """ login_url = "https://www.facebook.com/dialog/oauth" access_url = "https://graph.facebook.com/oauth/access_token" if "code" not in request.args: login_params = {} login_params["client_id"] = FACEBOOK_APP_ID login_params["redirect_uri"] = request.base_url login_params["state"] = generate_randomkey(32) login_params[ "scope" ] = "manage_pages,user_groups,publish_actions,publish_stream,user_videos,user_photos,photo_upload,read_stream" resp = make_response(redirect(login_url + "?" + urllib.urlencode(login_params))) resp.set_cookie("state", login_params["state"]) return resp if "state" in request.args and request.cookies["state"] == request.args["state"]: if "error" in request.args: return str(request.args) else: # get an access token access_params = {} access_params["client_id"] = FACEBOOK_APP_ID access_params["redirect_uri"] = request.base_url access_params["client_secret"] = FACEBOOK_APP_SECRET access_params["code"] = request.args["code"] response = urlfetch.fetch(access_url + "?" + urllib.urlencode(access_params)) response_data = urlparse.parse_qs(response.content) # get an extended access token extension_params = {} extension_params["grant_type"] = "fb_exchange_token" extension_params["client_id"] = FACEBOOK_APP_ID extension_params["client_secret"] = FACEBOOK_APP_SECRET extension_params["fb_exchange_token"] = response_data["access_token"][0] response = urlfetch.fetch(access_url + "?" + urllib.urlencode(extension_params)) response_data = urlparse.parse_qs(response.content) access_token = response_data["access_token"][0] try: expires = int(response_data["expires"][0]) except KeyError: expires = 60 * 24 * 60 * 60 expiration_date = dt.datetime.now() + dt.timedelta(0, expires) response = urlfetch.fetch("https://graph.facebook.com/me?access_token=" + access_token) response_data = json.loads(response.content) username = response_data["username"] fb_admin_del_user_access(username) token = models.UserAccessTokenModel( username=username, access_token=access_token, expiration=expiration_date, user_id=response_data["id"] ) token.put() return redirect(url_for("fb_admin_get_assoc_tokens")) else: return str(request.arg)
def create_user(): """ View for creating a user """ from application.generate_keys import generate_randomkey form = forms.CreateUserForm(request.form) form.family.choices = get_family_choices() form.roles.choices = get_role_choices() if request.method == 'POST': if form.validate(): # create the user with information specified in form fname = form.fname.data lname = form.lname.data cwruid = form.cwruid.data # generate a new temporary password password = generate_randomkey(16) # get optional attributes optional_attr = {} if form.mname.data != '': optional_attr['mname'] = form.mname.data if form.family.data != 'none': # look up family instance query = models.FamilyModel.all() query.filter('name =', form.family.data) families = query.fetch(1) if len(families) != 1: form.family.errors.append(u'Family %s does not exist' % form.family.data) return render_template('members/create.html', create_user_form=form) optional_attr['family'] = families[0].key() if form.big.data != '': # look up big instance users = find_users(cwruid=('=', form.big.data)) if len(users) != 1: form.big.errors.append(u'User %s does not exist' % form.big.data) return render_template('members/create.html', create_user_form=form) optional_attr['big'] = users[0].key() if form.avatar.data != '': optional_attr['avatar'] = form.avatar.data try: new_user = accounts.create_user(fname, lname, cwruid, password, **optional_attr) if new_user is None: raise AttributeError('Something went wrong with user creation') # add the case email address to the user email = models.EmailModel(user=new_user.key(), email='*****@*****.**' % new_user.cwruid, name='Case Email') email.put() # add the roles to the user for role in form.roles.data: query = RoleModel.all() query.filter('name =', role) if query.count() != 1: flash('Role %s does not exist' % role, 'error') continue desired_role = query.fetch(1)[0] new_urole = UserRoleModel(user=new_user.key(), role=desired_role.key()) new_urole.put() flash('User created successfully', 'success') form = None form = forms.CreateUserForm() form.family.choices = get_family_choices() form.roles.choices = get_role_choices() send_new_user_mail(fname, lname, cwruid, password) except AttributeError, e: flash(str(e), 'error')
def fb_admin_get_user_access(): """ Main admin view for Facebook settings """ login_url = 'https://www.facebook.com/dialog/oauth' access_url = 'https://graph.facebook.com/oauth/access_token' if 'code' not in request.args: login_params = {} login_params['client_id'] = FACEBOOK_APP_ID login_params['redirect_uri'] = request.base_url login_params['state'] = generate_randomkey(32) login_params[ 'scope'] = 'manage_pages,user_groups,publish_actions,publish_stream,user_videos,user_photos,photo_upload,read_stream' resp = make_response( redirect(login_url + '?' + urllib.urlencode(login_params))) resp.set_cookie('state', login_params['state']) return resp if 'state' in request.args and request.cookies['state'] == request.args[ 'state']: if 'error' in request.args: return str(request.args) else: # get an access token access_params = {} access_params['client_id'] = FACEBOOK_APP_ID access_params['redirect_uri'] = request.base_url access_params['client_secret'] = FACEBOOK_APP_SECRET access_params['code'] = request.args['code'] response = urlfetch.fetch(access_url + '?' + urllib.urlencode(access_params)) response_data = urlparse.parse_qs(response.content) # get an extended access token extension_params = {} extension_params['grant_type'] = 'fb_exchange_token' extension_params['client_id'] = FACEBOOK_APP_ID extension_params['client_secret'] = FACEBOOK_APP_SECRET extension_params['fb_exchange_token'] = response_data[ 'access_token'][0] response = urlfetch.fetch(access_url + '?' + urllib.urlencode(extension_params)) response_data = urlparse.parse_qs(response.content) access_token = response_data['access_token'][0] try: expires = int(response_data['expires'][0]) except KeyError: expires = 60 * 24 * 60 * 60 expiration_date = dt.datetime.now() + dt.timedelta(0, expires) response = urlfetch.fetch( 'https://graph.facebook.com/me?access_token=' + access_token) response_data = json.loads(response.content) username = response_data['username'] fb_admin_del_user_access(username) token = models.UserAccessTokenModel(username=username, access_token=access_token, expiration=expiration_date, user_id=response_data['id']) token.put() return redirect(url_for('fb_admin_get_assoc_tokens')) else: return str(request.arg)
def create_user(fname, lname, cwruid, password, **kwargs): """This method is a factory method for User accounts. It takes in the required fields of fname, lname, and cwruid. It queries the database to make sure that the cwruid is unique. If it is not an AttributeError exception is raised with the message stating that the cwruid is not unique. It then generates a string of salt using the secure random number generator in the Crypto module. The provided password is then hashed with the salt. All of this information is added to an instance of a UserModel class from the application.accounts.models module. If any optional arguments are supplied through the kwargs dictionary they are checked against the attributes of the UserModel class. If the argument matches an attribute in the UserModel and the attribute is modifiable outside of the accounts module and the value is valid for that attribute it is added to the UserModel instance created during the initial steps. If these conditions are not met an AttributeError exception is raised with the message specifying the argument that caused the problem. Finally the entire UserModel instance is saved to the datastore via the UserModel's put method. This UserModel is then stored inside of a new instance of the application.accounts.accounts.User class. If everything was successful the User instance is returned. Otherwise None is returned """ query = UserModel.all() query.filter('cwruid =', cwruid) # If there is already a user in the database # with the same cwruID if(query.count() > 0): raise AttributeError('CWRU ID %s already exists. ' % cwruid + 'CWRU ID must be unique') salt = generate_randomkey(256) hasher = SHA.new(salt + password) user_model = UserModel(fname=fname, lname=lname, cwruid=cwruid, salt=salt, hash=hasher.hexdigest()) for key in kwargs: # the values in non_modifiable_attr # should not be modified by information # from outside of this function if key in User.non_modifiable_attr: raise AttributeError try: if hasattr(user_model, key): user_model.__setattr__(key, kwargs[key]) except BadValueError: raise AttributeError("%s has invalid type" % key) user_model.put() new_user = User() new_user._User__UserModel = user_model # pylint: disable=C0103,W0201 return new_user
def create_user(): """ View for creating a user """ from application.generate_keys import generate_randomkey form = forms.CreateUserForm(request.form) form.family.choices = get_family_choices() form.roles.choices = get_role_choices() if request.method == 'POST': if form.validate(): # create the user with information specified in form fname = form.fname.data lname = form.lname.data cwruid = form.cwruid.data # generate a new temporary password password = generate_randomkey(16) # get optional attributes optional_attr = {} if form.mname.data != '': optional_attr['mname'] = form.mname.data if form.family.data != 'none': # look up family instance query = models.FamilyModel.all() query.filter('name =', form.family.data) families = query.fetch(1) if len(families) != 1: form.family.errors.append(u'Family %s does not exist' % form.family.data) return render_template('members/create.html', create_user_form=form) optional_attr['family'] = families[0].key() if form.big.data != '': # look up big instance users = find_users(cwruid=('=', form.big.data)) if len(users) != 1: form.big.errors.append(u'User %s does not exist' % form.big.data) return render_template('members/create.html', create_user_form=form) optional_attr['big'] = users[0].key() if form.avatar.data != '': optional_attr['avatar'] = form.avatar.data try: new_user = accounts.create_user(fname, lname, cwruid, password, **optional_attr) if new_user is None: raise AttributeError( 'Something went wrong with user creation') # add the case email address to the user email = models.EmailModel(user=new_user.key(), email='*****@*****.**' % new_user.cwruid, name='Case Email') email.put() # add the roles to the user for role in form.roles.data: query = RoleModel.all() query.filter('name =', role) if query.count() != 1: flash('Role %s does not exist' % role, 'error') continue desired_role = query.fetch(1)[0] new_urole = UserRoleModel(user=new_user.key(), role=desired_role.key()) new_urole.put() flash('User created successfully', 'success') form = None form = forms.CreateUserForm() form.family.choices = get_family_choices() form.roles.choices = get_role_choices() send_new_user_mail(fname, lname, cwruid, password) except AttributeError, e: flash(str(e), 'error')
def create_user(fname, lname, cwruid, password, **kwargs): """This method is a factory method for User accounts. It takes in the required fields of fname, lname, and cwruid. It queries the database to make sure that the cwruid is unique. If it is not an AttributeError exception is raised with the message stating that the cwruid is not unique. It then generates a string of salt using the secure random number generator in the Crypto module. The provided password is then hashed with the salt. All of this information is added to an instance of a UserModel class from the application.accounts.models module. If any optional arguments are supplied through the kwargs dictionary they are checked against the attributes of the UserModel class. If the argument matches an attribute in the UserModel and the attribute is modifiable outside of the accounts module and the value is valid for that attribute it is added to the UserModel instance created during the initial steps. If these conditions are not met an AttributeError exception is raised with the message specifying the argument that caused the problem. Finally the entire UserModel instance is saved to the datastore via the UserModel's put method. This UserModel is then stored inside of a new instance of the application.accounts.accounts.User class. If everything was successful the User instance is returned. Otherwise None is returned """ query = UserModel.all() query.filter('cwruid =', cwruid) # If there is already a user in the database # with the same cwruID if (query.count() > 0): raise AttributeError('CWRU ID %s already exists. ' % cwruid + 'CWRU ID must be unique') salt = generate_randomkey(256) hasher = SHA.new(salt + password) user_model = UserModel(fname=fname, lname=lname, cwruid=cwruid, salt=salt, hash=hasher.hexdigest()) for key in kwargs: # the values in non_modifiable_attr # should not be modified by information # from outside of this function if key in User.non_modifiable_attr: raise AttributeError try: if hasattr(user_model, key): user_model.__setattr__(key, kwargs[key]) except BadValueError: raise AttributeError("%s has invalid type" % key) user_model.put() new_user = User() new_user._User__UserModel = user_model # pylint: disable=C0103,W0201 return new_user