Example #1
0
    def create_client_portal_credentials(self, requester: User):
        if self.client_user_obj is None:
            client_user_manager = UserManager()
            password = client_user_manager.make_random_password()
            client_user_obj = client_user_manager.create_user(
                customer=requester.customer,
                username=self.primary_email,
                first_name="un_assigned"
                if self.first_name is None else self.first_name,
                last_name="un_assigned"
                if self.first_name is None else self.first_name,
                email=self.primary_email,
                phone="un_assigned"
                if self.first_name is None else self.first_name,
                password=password,
                is_client=True,
                region_code=requester.region_code,
                timezone=requester.timezone,
            )
            ActivityStream(customer=requester.customer,
                           actor=requester.username,
                           verb='created_client_portal_access_credentials',
                           action_object=self.__str__()).save()

            self.client_user_obj = client_user_obj
            self.save()
            emailer.send_client_credential_email(self, password, requester)
 def save(self, commit=True):
     # Save the provided password in hashed format
     user = super(UserForm, self).save(commit=False)
     user.email = UserManager.normalize_email(self.cleaned_data['email'])
     user.set_password(self.cleaned_data['password'])
     if commit:
         user.save()
     return user
Example #3
0
    def post(self, request):
        form = RegisterForm(request.POST or None)
        if form.is_valid():
            formdata = form.cleaned_data.copy()
            formdata.pop('password2')
            formdata.pop('password')
            tenant = Customer()
            tenant.username = form.cleaned_data['username']
            tenant.first_name = form.cleaned_data['first_name']
            tenant.last_name = form.cleaned_data['last_name']
            tenant.email = form.cleaned_data['email']
            tenant.phone = form.cleaned_data['phone']
            tenant.timezone = form.cleaned_data['timezone']
            ph = parse(form.cleaned_data['phone'])
            region_code = region_code_for_country_code(ph.country_code)
            tenant.region_code = region_code
            tenant.save()
            print(tenant.__dict__)

            user_manager = UserManager()
            user_manager.create_user(
                customer=tenant,
                username=form.cleaned_data['username'],
                email=form.cleaned_data['email'],
                password=form.cleaned_data['password'],
                first_name=form.cleaned_data['first_name'],
                last_name=form.cleaned_data['last_name'],
                phone=form.cleaned_data['phone'],
                is_owner=True,
                is_clinician=True,
                is_scheduler=True,
                is_biller=True,
                region_code=tenant.region_code,
                timezone=tenant.timezone,
            )
            ActivityStream(customer=tenant,
                           actor=form.cleaned_data['username'],
                           verb='signed up').save()
            return redirect('login')  # to be changed later
        context = {'form': form}
        return render(request, self.template, context)
Example #4
0
    def post(self, request, *args, **kwargs):
        ctxt = {}

        if 'login' in request.POST:  # Check if login button is clicked
            login_form = LoginForm(
                request.POST)  # Assign login form fields to variable

            if login_form.is_valid(
            ):  # Return True if the form has no errors, or False otherwise
                try:
                    user = User.authenticate_from_form(login_form)
                except User.DoesNotExist:
                    messages.error(request, 'Incorrect login')

                if not user:  # Check if credentials are valid and User object exist
                    messages.error(request, 'Invalid login details given.')
                else:
                    if not user.is_active:  # Report error if user is not active
                        messages.error(request, 'Your account is inactive.')
                    else:
                        auth_login(request, user)  # Log in user
                        user.set_session_expiration(request)
                        next_url = request.GET.get('next')
                        if next_url:
                            return HttpResponseRedirect(next_url)

                        hello = user.first_name if user.first_name else user.username
                        messages.success(request, 'Welcome {}'.format(hello))
                        return redirect(
                            self.page_to_redirect)  # Go to index view

        elif 'register' in request.POST:

            registration_form = RegisterForm(
                request.POST)  # Assign register form fields to variable

            if registration_form.is_valid(
            ):  # Return True if the form has no errors, or False otherwise
                user = UserManager.create_from_form(registration_form)
                user.send_activation_link(request)
                messages.success(
                    request,
                    'Please confirm your email address to complete the registration.'
                )
            else:
                ctxt['registration_form'] = registration_form

        return render(request, self.template_name,
                      self.get_context_data(**ctxt))
Example #5
0
    def post(self, request, *args, **kwargs):

        kwargs = super().get_context_data(request, **kwargs)

        # Stop proceeding if any of form is incorrectly completed
        if self.invalid_forms:
            return render(request, self.template_name, kwargs)
        else:
            if not self.has_all_billing_data:
                self.user.update_from_form(self.billing_form)
            elif self.create_account:
                self.user = UserManager.create_from_form(self.billing_form)

            self.cart.book()
            self.shipment = self.assign_new_shipment()

            if not self.shipment:
                messages.error(request,
                               'There was a problem creating the shipment. Administrator has been informed.')
            else:
                self.cart.update_after_shipment_creating(self.user, self.billing_form.cleaned_data['email'])
                self.send_checkout_email(request)

                # Save user and shipment after successful updating cart and sending checkout email
                if self.create_account:
                    self.user.save()

                self.shipment.save()

                if request.user.is_authenticated:
                    return redirect(reverse('summary', kwargs={'ref_code': self.cart.ref_code,
                                                               'oidb64': urlsafe_base64_encode(
                                                                   force_bytes(self.cart.id)), }))

            # Redirect newly created user or user without account to index page and display proper message
            return redirect(reverse('index'))
Example #6
0
 def get_queryset(self, request):
     queryset = UserManager.get_queryset(self, request)
     return queryset
Example #7
0
class User(AbstractBaseUser, PermissionsMixin):
    """
    An abstract base class implementing a fully featured User model with
    admin-compliant permissions.

    Username and password are required. Other fields are optional.
    """
    username_validator = UnicodeUsernameValidator()

    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=
        _('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'
          ),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=150, blank=True)
    email = models.EmailField(_('email address'), blank=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_(
            'Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting registration.'),
    )
    dealer = models.ForeignKey(
        Dealer,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        default=None,
    )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        """
        Return the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        """Return the short name for the user."""
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)
Example #8
0
 def test_user_manager_fails_without_email_address(self):
     manager = UserManager()
     with self.assertRaises(ValueError):
         manager._create_user(password='******')
def show_user(request):
    users = User.objects.filter(admin=True)
    s_message = ""
    fail_message = ""
    if request.method == "POST":
        action = request.POST.get('action')
        print(action)
        user_id = request.POST.get('user_id')
        if action == "Edit":
            user_to_edit = User.objects.filter(id=user_id)
            return render(request,
                          'admin/edit_models/forms/edit_form_admin.html',
                          {"user_to_edit": user_to_edit[0]})
        elif action == "Change_password":
            print("CHANGE " + user_id)
            user_to_edit = User.objects.filter(id=user_id)
            return render(request,
                          'admin/edit_models/forms/change_password.html', {
                              "user_to_edit": user_to_edit[0],
                              "model": "model_user"
                          })
        elif action == "Delete":
            User.objects.filter(id=user_id).delete()
            users = User.objects.filter(admin=True)
            s_message = "User was deleted successfully "
        elif action == "Update":
            username = request.POST.get("username")
            name = request.POST.get("name")
            second_name = request.POST.get("second_name")
            surname = request.POST.get("surname")
            user_to_edit = User.objects.filter(id=user_id)
            user_to_edit = user_to_edit[0]
            user_to_edit.username = username
            user_to_edit.name = name
            user_to_edit.second_name = second_name
            user_to_edit.surname = surname
            print(user_to_edit)
            user_to_edit.save()
            s_message = "User was updated successfully"
            users = User.objects.filter(admin=True)
        elif action == "Add_admin":
            return render(request,
                          'admin/edit_models/forms/add_form_user.html')
        elif action == "Do_change_password":
            user_to_edit = User.objects.filter(id=user_id)
            user_to_edit = user_to_edit[0]
            new_password = request.POST.get("new_password")
            confirm_new_password = request.POST.get("confirm_new_password")
            if new_password == confirm_new_password:
                user_to_edit.set_password(new_password)
                user_to_edit.save()
                s_message = "Password was changed successfully"
                users = User.objects.filter(admin=True)
            else:
                fail_message = "Passwords are not the same"
        elif action == "Do_add_user":
            username = request.POST.get("username")
            name = request.POST.get("name")
            second_name = request.POST.get("second_name")
            surname = request.POST.get("surname")
            password = request.POST.get("password")
            manager = UserManager()
            manager.create_superuser(username=username,
                                     password=password,
                                     active=True,
                                     name=name,
                                     surname=surname,
                                     snmae=second_name)
            users = User.objects.filter(admin=True)
    return render(request, 'admin/edit_models/tab_user.html', {
        "admins": users,
        "s_message": s_message,
        "fail_message": fail_message
    })
def show_teacher(request):
    teachers = Teacher.objects.all()
    s_message = ""
    fail_message = ""
    if request.method == "POST":
        action = request.POST.get("action")
        user_id = request.POST.get('user_id')
        if action == "Edit":
            teacher = Teacher.objects.filter(user_id=user_id)[0]
            faculties = Faculty.objects.exclude(id=teacher.faculty.id)
            return render(request,
                          'admin/edit_models/forms/edit_form_teacher.html', {
                              "faculties": faculties,
                              "teacher": teacher
                          })
        elif action == "Change_password":
            teacher = Teacher.objects.filter(user_id=user_id)
            return render(request,
                          'admin/edit_models/forms/change_password.html', {
                              "teacher": teacher[0],
                              "model": "model_teacher"
                          })
        elif action == "Delete":
            Teacher.objects.filter(user_id=user_id).delete()
            User.objects.filter(id=user_id).delete()
            teachers = Teacher.objects.all()
            s_message = "User was deleted successfully "
        elif action == "Update":
            username = request.POST.get("username")
            name = request.POST.get("name")
            second_name = request.POST.get("second_name")
            surname = request.POST.get("surname")
            faculty = request.POST.get('faculty')
            teacher = Teacher.objects.filter(user_id=user_id)[0]
            teacher.user.username = username
            teacher.user.name = name
            teacher.user.second_name = second_name
            teacher.user.surname = surname
            teacher.user.save()
            if faculty:
                teacher.faculty = Faculty.objects.filter(id=faculty)[0]
            teacher.save()
            s_message = "Editing teacher finished with success"
            teachers = Teacher.objects.all()
        elif action == "Add_teacher":
            faculties = Faculty.objects.all()
            return render(request,
                          'admin/edit_models/forms/add_form_teacher.html',
                          {"faculties": faculties})
        elif action == "Do_change_password":
            user_to_edit = User.objects.filter(id=user_id)
            user_to_edit = user_to_edit[0]
            new_password = request.POST.get("new_password")
            confirm_new_password = request.POST.get("confirm_new_password")
            if new_password == confirm_new_password:
                user_to_edit.set_password(new_password)
                user_to_edit.save()
                s_message = "Password was changed successfully"
                teachers = Teacher.objects.all()
            else:
                fail_message = "Passwords are not the same"
        elif action == "Do_add_teacher":
            username = request.POST.get("username")
            name = request.POST.get("name")
            second_name = request.POST.get("second_name")
            surname = request.POST.get("surname")
            password = request.POST.get("password")
            faculty = request.POST.get('faculty')
            manager = UserManager()
            user = manager.create_teacher(username=username,
                                          password=password,
                                          active=True,
                                          name=name,
                                          surname=surname,
                                          sname=second_name)
            teacher = Teacher()
            teacher.user = user
            if faculty:
                teacher.faculty = Faculty.objects.filter(id=faculty)[0]
            teacher.save()
            s_message = "Adding new teacher finished with success"
            teachers = Teacher.objects.all()
        elif action == "Add_to_subject":
            pass
    return render(request, 'admin/edit_models/tab_teacher.html', {
        "teachers": teachers,
        "s_message": s_message,
        "fail_message": fail_message
    })
def show_student(request):
    students = Student.objects.all()
    s_message = ""
    fail_message = ""
    if request.method == "POST":
        action = request.POST.get("action")
        user_id = request.POST.get('user_id')
        if action == "Edit" and user_id:
            student_to_edit = Student.objects.filter(user_id=user_id)
            fields_of_study = FieldOfStudy.objects.all().exclude(
                id=student_to_edit[0].fieldOfStudy.id)
            plans = Plan.objects.filter(
                fieldOfStudy=student_to_edit[0].fieldOfStudy,
                semester=student_to_edit[0].semester)
            return render(
                request, 'admin/edit_models/forms/edit_form_student.html', {
                    "student": student_to_edit[0],
                    "fields_of_study": fields_of_study,
                    "plans": plans
                })
        elif action == "Change_password" and user_id:
            student_to_edit = Student.objects.filter(user_id=user_id)
            return render(request,
                          'admin/edit_models/forms/change_password.html', {
                              "student_to_edit": student_to_edit[0],
                              "model": "model_student"
                          })
        elif action == "Delete" and user_id:
            Student.objects.filter(user_id=user_id).delete()
            User.objects.filter(id=user_id).delete()
            students = Student.objects.all()
            s_message = "User was deleted successfully "
        elif action == "Update" and user_id:
            #try:
            username = request.POST.get("username")
            name = request.POST.get("name")
            second_name = request.POST.get("second_name")
            surname = request.POST.get("surname")
            field_of_study = request.POST.get("field_of_study")
            semester = request.POST.get("semester")
            plan = request.POST.get("plan_id")
            student_to_edit = Student.objects.filter(user_id=user_id)
            student_to_edit = student_to_edit[0]
            student_to_edit.user.username = username
            student_to_edit.user.name = name
            student_to_edit.user.second_name = second_name
            student_to_edit.user.surname = surname
            student_to_edit.semester = semester
            if plan:
                student_to_edit.plan = Plan.objects.filter(id=plan)[0]
            if field_of_study:
                student_to_edit.fieldOfStudy = FieldOfStudy.objects.filter(
                    id=field_of_study)[0]
            student_to_edit.user.save()
            student_to_edit.save()
            students = Student.objects.all()
            s_message = "Student was edited successfully"
            #except Exception:
            #    fail_message = "Something went wrong"
        elif action == "Add_student":
            fields = FieldOfStudy.objects.all()
            return render(request,
                          'admin/edit_models/forms/add_form_student.html',
                          {"fields_of_study": fields})
        elif action == "Do_change_password":
            user_to_edit = User.objects.filter(id=user_id)
            user_to_edit = user_to_edit[0]
            new_password = request.POST.get("new_password")
            confirm_new_password = request.POST.get("confirm_new_password")
            if new_password == confirm_new_password:
                user_to_edit.set_password(new_password)
                user_to_edit.save()
                s_message = "Password was changed successfully"
                students = Student.objects.all()
            else:
                fail_message = "Passwords are not the same"
        elif action == "Do_add_user":
            try:
                username = request.POST.get("username")
                name = request.POST.get("name")
                second_name = request.POST.get("second_name")
                surname = request.POST.get("surname")
                password = request.POST.get("password")
                field_of_study = request.POST.get("field_of_study")
                semester = request.POST.get("semester")
                user = UserManager().create_student(username=username,
                                                    password=password,
                                                    active=True,
                                                    name=name,
                                                    sname=second_name,
                                                    surname=surname)
                user.save()
                student_to_add = Student()
                student_to_add.user = user
                student_to_add.semester = semester
                if field_of_study:
                    student_to_add.fieldOfStudy = FieldOfStudy.objects.filter(
                        id=field_of_study)[0]
                student_to_add.user.save()
                student_to_add.save()
                students = Student.objects.all()
                s_message = "Student was edited successful"
            except Exception:
                fail_message = "Something went wrong"
        else:
            fail_message = "You should choose student before " + action.lower()
    return render(request, 'admin/edit_models/tab_student.html', {
        'students': students,
        "s_message": s_message,
        "fail_message": fail_message
    })
def sign(request):
    user_manager = UserManager()
    user_manager.create_staffuser(request.GET['phone'], request.GET['password'])
    return Response({'success': 'success'},
                    status=HTTP_200_OK)