def add_user(request): if not request.session.get('admin_login'): return HttpResponseRedirect("/login/") else: if request.method == "POST": name = request.POST['name'] username = request.POST['uname'].strip() password = str(''.join( random.choices(string.ascii_uppercase + string.digits, k=8))) # password = request.POST['psw'] branch = request.POST['branch'] check = User.objects.filter(username=username) if check: msg = {'invalidate': "User already exists."} return render(request, 'add_student.html', msg) # return HttpResponseRedirect('/tnp_admin/add_user') # print("Username already exists") else: addUser = User(name=name, username=username, password=password, branch=branch) addUser.save() send_mail( 'Placement Portal', 'Id: ' + username + '\nPassword: '******'.', '*****@*****.**', [username], fail_silently=False, ) msg = {'validate': "Added successfully."} return render(request, 'add_student.html', msg) else: return render(request, 'add_student.html')
def add_excel(request): if not request.session.get('admin_login'): return HttpResponseRedirect("/login/") else: student = request.FILES['excel_student'] check = student.name if check.endswith('.xls') or check.endswith('.xlsx') or check.endswith( '.XLS') or check.endswith('.XLSX'): wb = openpyxl.load_workbook(student) worksheet = wb["Sheet1"] excel_data = list() msg = [] no = 0 yes = 0 for i, row in enumerate(worksheet.iter_rows()): row_data = list() if i == 0: continue for cell in row: row_data.append(str(cell.value)) excel_data.append(row_data) for add in excel_data: name = add[0] username = add[1] branch = add[2] if User.objects.filter(username=username).exists( ) or name == "" or username == "" or branch == "" or ( not username.endswith('@somaiya.edu')): no = no + 1 else: password = str(''.join( random.choices(string.ascii_uppercase + string.digits, k=8))) addUser = User(name=name, username=username, password=password, branch=branch) addUser.save() send_mail( 'Placement Portal', 'Id: ' + username + '\nPassword: '******'.', '*****@*****.**', [username], fail_silently=False, ) yes = yes + 1 msg = { "yes": yes, "no": no, } else: msg = { "invalidate": "Invalid file format.", } return render(request, 'add_student.html', msg)
def _validate_password(password, username=None, email=None): """Validate the format of the user's password. Passwords cannot be the same as the username of the account, so we create a temp_user using the username and email to test the password against. This user is never saved. Arguments: password (unicode): The proposed password. username (unicode): The username associated with the user's account. email (unicode): The email associated with the user's account. Returns: None Raises: errors.AccountPasswordInvalid """ try: _validate_type(password, six.string_types, accounts.PASSWORD_BAD_TYPE_MSG) temp_user = User(username=username, email=email) if username else None validate_password(password, user=temp_user) except errors.AccountDataBadType as invalid_password_err: raise errors.AccountPasswordInvalid(text_type(invalid_password_err)) except ValidationError as validation_err: raise errors.AccountPasswordInvalid(' '.join(validation_err.messages))
def create_user_and_user_profile(self, email, username, password, custom_field, complete_name, first_name, last_name): """ Create a new user, add a new Registration instance for letting user verify its identity and create a user profile. :param email: user's email address :param username: user's username :param name: user's name :param country: user's country :param password: user's password :return: User instance of the new user. """ user = User( username=username, email=email, is_active=True, first_name=first_name, last_name=last_name, ) user.set_password(password) user.save() registration = Registration() registration.register(user) """ reg = Registration() reg.register(user) """ #user.save() profile = UserProfile(user=user) profile.custom_field = json.dumps(custom_field) profile.name = complete_name profile.save() return user
def register(): # 已经导入request包不用再在参数里添加 if request.method == "POST": form_data = request.form username = form_data.get("username") password = form_data.get("password") identity = form_data.get("identity") user = User() user.username = username user.password = spw(password) user.identity = identity user.save() return redirect('/login/') return render_template('register.html', **locals())
def create_account(username, password, email): """Create a new user account. This will implicitly create an empty profile for the user. WARNING: This function does NOT yet implement all the features in `student/views.py`. Until it does, please use this method ONLY for tests of the account API, not in production code. In particular, these are currently missing: * 3rd party auth * External auth (shibboleth) * Complex password policies (ENFORCE_PASSWORD_POLICY) In addition, we assume that some functionality is handled at higher layers: * Analytics events * Activation email * Terms of service / honor code checking * Recording demographic info (use profile API) * Auto-enrollment in courses (if invited via instructor dash) Args: username (unicode): The username for the new account. password (unicode): The user's password. email (unicode): The email address associated with the account. Returns: unicode: an activation key for the account. Raises: AccountUserAlreadyExists AccountUsernameInvalid AccountEmailInvalid AccountPasswordInvalid UserAPIInternalError: the operation failed due to an unexpected error. """ # Validate the username, password, and email # This will raise an exception if any of these are not in a valid format. _validate_username(username) _validate_password(password, username) _validate_email(email) # Create the user account, setting them to "inactive" until they activate their account. user = User(username=username, email=email, is_active=False) user.set_password(password) try: user.save() except IntegrityError: raise AccountUserAlreadyExists # Create a registration to track the activation process # This implicitly saves the registration. registration = Registration() registration.register(user) # Create an empty user profile with default values UserProfile(user=user).save() # Return the activation key, which the caller should send to the user return registration.activation_key
def create_account(username, password, email): """Create a new user account. This will implicitly create an empty profile for the user. WARNING: This function does NOT yet implement all the features in `student/views.py`. Until it does, please use this method ONLY for tests of the account API, not in production code. In particular, these are currently missing: * 3rd party auth * External auth (shibboleth) * Complex password policies (ENFORCE_PASSWORD_POLICY) In addition, we assume that some functionality is handled at higher layers: * Analytics events * Activation email * Terms of service / honor code checking * Recording demographic info (use profile API) * Auto-enrollment in courses (if invited via instructor dash) Args: username (unicode): The username for the new account. password (unicode): The user's password. email (unicode): The email address associated with the account. Returns: unicode: an activation key for the account. Raises: errors.AccountUserAlreadyExists errors.AccountUsernameInvalid errors.AccountEmailInvalid errors.AccountPasswordInvalid errors.UserAPIInternalError: the operation failed due to an unexpected error. """ # Check if ALLOW_PUBLIC_ACCOUNT_CREATION flag turned off to restrict user account creation if not configuration_helpers.get_value( 'ALLOW_PUBLIC_ACCOUNT_CREATION', settings.FEATURES.get('ALLOW_PUBLIC_ACCOUNT_CREATION', True)): return HttpResponseForbidden(_("Account creation not allowed.")) if waffle().is_enabled(PREVENT_AUTH_USER_WRITES): raise errors.UserAPIInternalError(SYSTEM_MAINTENANCE_MSG) # Validate the username, password, and email # This will raise an exception if any of these are not in a valid format. _validate_username(username) _validate_password(password, username) _validate_email(email) # Create the user account, setting them to "inactive" until they activate their account. user = User(username=username, email=email, is_active=False) user.set_password(password) try: user.save() except IntegrityError: raise errors.AccountUserAlreadyExists # Create a registration to track the activation process # This implicitly saves the registration. registration = Registration() registration.register(user) # Create an empty user profile with default values UserProfile(user=user).save() # Return the activation key, which the caller should send to the user return registration.activation_key
def create_account(username, password, email): """Create a new user account. This will implicitly create an empty profile for the user. WARNING: This function does NOT yet implement all the features in `student/views.py`. Until it does, please use this method ONLY for tests of the account API, not in production code. In particular, these are currently missing: * 3rd party auth * External auth (shibboleth) * Complex password policies (ENFORCE_PASSWORD_POLICY) In addition, we assume that some functionality is handled at higher layers: * Analytics events * Activation email * Terms of service / honor code checking * Recording demographic info (use profile API) * Auto-enrollment in courses (if invited via instructor dash) Args: username (unicode): The username for the new account. password (unicode): The user's password. email (unicode): The email address associated with the account. Returns: unicode: an activation key for the account. Raises: errors.AccountUserAlreadyExists errors.AccountUsernameInvalid errors.AccountEmailInvalid errors.AccountPasswordInvalid errors.UserAPIInternalError: the operation failed due to an unexpected error. """ # Check if ALLOW_PUBLIC_ACCOUNT_CREATION flag turned off to restrict user account creation if not configuration_helpers.get_value( 'ALLOW_PUBLIC_ACCOUNT_CREATION', settings.FEATURES.get('ALLOW_PUBLIC_ACCOUNT_CREATION', True) ): return HttpResponseForbidden(_("Account creation not allowed.")) if waffle().is_enabled(PREVENT_AUTH_USER_WRITES): raise errors.UserAPIInternalError(SYSTEM_MAINTENANCE_MSG) # Validate the username, password, and email # This will raise an exception if any of these are not in a valid format. _validate_username(username) _validate_password(password, username) _validate_email(email) # Create the user account, setting them to "inactive" until they activate their account. user = User(username=username, email=email, is_active=False) user.set_password(password) try: user.save() except IntegrityError: raise errors.AccountUserAlreadyExists # Create a registration to track the activation process # This implicitly saves the registration. registration = Registration() registration.register(user) # Create an empty user profile with default values UserProfile(user=user).save() # Return the activation key, which the caller should send to the user return registration.activation_key