예제 #1
0
def remind_me(request):
    """
      To save the Reminder, User wants to create
    :param request:
    :param mobile: 10 digit Mobile number
    :param email: EMail Address
    :param message: Any Message String (Required)
    :param date_time : date and time(Required) to send the reminder and
                       Here I am assuming the user can select the time with time interval of 30 Minute
    :return: 201 or 400
    """
    # Ensure User provides Either Email or Mobile
    if not request.data.get('mobile') and not request.data.get('email'):
        return Response('Please enter either email or mobile', status=400)
    # Ensure Email is valid
    try:
        validate_email(request.data.get('email'))
    except ValidationError:
        return Response('Enter Valid Email ID', status=400)
    # Ensure User Provides some message because sending blank reminder would not be good idea
    if not request.data.get('message'):
        return Response('Please give some message', status=400)
    serializer = RemindMeSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #2
0
파일: add_user.py 프로젝트: suipnice/pod
    def handle_noargs(self, **options):
        """ Encode all pending streams """
        members = open('import_user.csv', "r")
        data = csv.reader(members, delimiter=';', quotechar='"')
        # data = csv.DictReader(members)
        i = 0
        for row in data:
            i = i + 1
            if i % 10 == 0:
                print "----- i : %s" % i
                time.sleep(480)
            # print u'%s' %row
            prenom = unicode(row[0], "utf8")
            nom = unicode(row[1], "utf8")
            email = unicode(row[2], "utf8")
            is_staff = True if row[3] == "1" else False
            detail = unicode(row[4], "utf8")
            print nom, prenom, email, is_staff, detail
            try:
                validate_email(email)
                tokens = email.split('@')
                username = tokens[0]
                print "email valide : %s" % username
                add_user(nom, prenom, username, email, is_staff, detail)
            except ValidationError:
                print "%s %s => invalid email" % (nom, prenom)

        members.close()
예제 #3
0
def get_valid_student_email(identifier):
    """
    Helper function to get an user email from an identifier and validate it.

    In the UI a Coach can enroll users using both an email and an username.
    This function takes care of:
    - in case the identifier is an username, extracting the user object from
        the DB and then the associated email
    - validating the email

    Arguments:
        identifier (str): Username or email of the user to enroll

    Returns:
        str: A validated email for the user to enroll

    Raises:
        CCXUserValidationException: if the username is not found or the email
            is not valid.
    """
    user = email = None
    try:
        user = get_student_from_identifier(identifier)
    except User.DoesNotExist:
        email = identifier
    else:
        email = user.email
    try:
        validate_email(email)
    except ValidationError:
        raise CCXUserValidationException('Could not find a user with name or email "{0}" '.format(identifier))
    return email
예제 #4
0
def ccx_student_management(request, course, ccx=None):
    """Manage the enrollment of individual students in a CCX
    """
    if not ccx:
        raise Http404

    action = request.POST.get('student-action', None)
    student_id = request.POST.get('student-id', '')
    user = email = None
    try:
        user = get_student_from_identifier(student_id)
    except User.DoesNotExist:
        email = student_id
    else:
        email = user.email

    course_key = CCXLocator.from_course_locator(course.id, ccx.id)
    try:
        validate_email(email)
        if action == 'add':
            # by decree, no emails sent to students added this way
            # by decree, any students added this way are auto_enrolled
            enroll_email(course_key, email, auto_enroll=True, email_students=False)
        elif action == 'revoke':
            unenroll_email(course_key, email, email_students=False)
    except ValidationError:
        log.info('Invalid user name or email when trying to enroll student: %s', email)

    url = reverse(
        'ccx_coach_dashboard',
        kwargs={'course_id': course_key}
    )
    return redirect(url)
예제 #5
0
def validate_user_email_allowed_domains(value):
    validators.validate_email(value)

    domain_name = value.split("@")[1]

    if settings.USER_EMAIL_ALLOWED_DOMAINS and domain_name not in settings.USER_EMAIL_ALLOWED_DOMAINS:
        raise ValidationError(_("You email domain is not allowed"))
예제 #6
0
    def has_perms(self, permission_name, user=None):
        '''
        Return whether a given user has a given permission name
        '''
        isanon = user and user.is_anonymous()

        if permission_name == 'receive_email_updates':
            from django.core.validators import validate_email
            from django.core.exceptions import ValidationError
            try:
                validate_email(self.user.email)
            except ValidationError:
                return False
            return self.email_updates 
        elif permission_name == 'receive_mail':
            from django.core.validators import validate_email
            from django.core.exceptions import ValidationError
            if user.is_anonymous():
                return False
            # only admins of the agora the user is in can send the user an email
            if not user.administrated_agoras.only('id').filter(
                    id__in=self.user.agoras.only('id').all().query).exists():
                return False
            try:
                validate_email(self.user.email)
            except ValidationError:
                return False
            return not isanon
        else:
            return False
예제 #7
0
파일: models.py 프로젝트: YLAsce/ojp
    def _checkInfo(self):
        # Check Name
        if len(self.name) < Const.CONTESTANT_NAME_MIN_LENGTH or len(self.name) > Const.CONTESTANT_NAME_MAX_LENGTH:
            raise Exception(u'姓名不合法!')

        # Check Email
        from django.core.validators import validate_email
        from django.core.exceptions import ValidationError
        try:
            validate_email(self.email)
        except ValidationError:
            raise Exception(u'Email不合法!')

        # Check IDs
        validSet = "0123456789"
        for token in self.student_id:
            if not token in validSet:
                raise Exception(u'学号不合法!')
        for token in self.class_id:
            if not token in validSet:
                raise Exception(u'班级不合法!')
        
        # Check whether the team has been full
        members = Contestant.objects.filter(team = self.team)
        if len(members) >= 3:
            raise Exception(u'队伍已经满员!')

        return True
예제 #8
0
파일: views.py 프로젝트: nveid/class2go
def save_piazza_opts(request):
    email = request.POST.get('email')
    name = request.POST.get('name')
    str_id = request.POST.get('id')
    try:
        validate_email(email)
    except ValidationError:
        return HttpResponseBadRequest('You did not enter a valid email address.')
    try:
        nameValidator = RegexValidator(regex=r'^[\w -]+$')
        nameValidator(name.strip())
    except ValidationError:
        return HttpResponseBadRequest('Names on Piazza should only contain letters, numbers, underscores, hyphens, and spaces.')
    try:
        int_id = int(str_id)
    except ValueError:
        return HttpResponseBadRequest('Not a integer id')
    try:
        user = User.objects.get(id=str_id)
    except User.DoesNotExist:
        return HttpResponseBadRequest('User not found')

    profile=user.get_profile()
    profile.piazza_name=name
    profile.piazza_email=email
    profile.save()
    return HttpResponse("Successfully Saved Piazza Options")
예제 #9
0
파일: views.py 프로젝트: bmetge/Surveyvor
def register(request):
    if request.method == "POST":
        #Preparing the user to store in the database
        user = User(
            username=request.POST.get('username'),
            password=make_password(request.POST.get('password')),
            email=request.POST.get('email'),
            isWarned=False,
            isAdmin=False,
            activationLink="".join( [random.choice(string.letters) for i in xrange(32)] ),
            registrationDate=timezone.now()
        )

        #Preparing the response
        response_data = {}
        response_data['username_already_taken'] = 'false'
        response_data['invalid_email']='false'
        response_data['email_already_taken'] = 'false'
        response_data['result'] = 'success'

        #Checking if the username exists in the database
        try:
            User.objects.get(username=user.username)
            usernameTaken = True
        except User.DoesNotExist:
            usernameTaken = False

        if usernameTaken==False:
            try:
                validate_email(user.email)
                user.save()
                #Preparing the email to send
                subject, from_email, to = 'SurveyVor Activation', '*****@*****.**', user.email
                html_content = render_to_string('Account/activation_mail.html', {'activationLink':user.activationLink})
                text_content = """
Congratulations!

Your registration is almost complete. To be able to access your account, click on the activation link bellow:
http://www.okarrakchou.com/account/activate/%s

Regards,
The Surveyvor Team
""" % (user.activationLink)
                # create the email, and attach the HTML version as well.
                msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
                msg.attach_alternative(html_content, "text/html")
                msg.send()
            except ValidationError:
                response_data['result'] = 'failure'
                response_data['invalid_email']='true'
            except IntegrityError:
                response_data['result'] = 'failure'
                response_data['email_already_taken']='true'
        else:
            response_data['result'] = 'failure'
            response_data['username_already_taken']='true'

        return HttpResponse(json.dumps(response_data), mimetype="application/json")
    else:
        return HttpResponse(0)
예제 #10
0
    def clean_harvard_email(self):
        harvard_email = self.cleaned_data.get('harvard_email')

        if harvard_email is None:
            raise ValidationError(_('A Harvard email is required.'), code='invalid')

        harvard_email = harvard_email.strip().lower()

        if harvard_email == '':
            raise ValidationError(_('A Harvard email is required.'), code='invalid')

        # make sure it's a valid email address
        validate_email(harvard_email)

        # make sure no existing users have this address
        qs = Person.objects.filter(Q(email=harvard_email) | Q(harvard_email=harvard_email))
        if self.instance.pk is not None:
            qs = qs.exclude(pk=self.instance.pk)

        if qs:
            raise ValidationError(_('A member with this email address already exists.'), code='invalid')

        # make sure it's a valid harvard address
        try:
            if harvard_email.split('@', 1)[1] not in settings.VALID_HARVARD_DOMAINS:
                raise ValidationError(('Please enter a valid Harvard email address.'), code='invalid')
        except IndexError:
            raise ValidationError(('Please enter a valid Harvard email address.'), code='invalid')

        return harvard_email
예제 #11
0
    def post(self, request, *args, **kwargs):
        status_code = 400
        invitees = json.loads(request.body.decode())
        response = {'valid': [], 'invalid': []}
        if isinstance(invitees, list):
            for invitee in invitees:
                try:
                    validate_email(invitee)
                    CleanEmailMixin().validate_invitation(invitee)
                    invite = Invitation.create(invitee)
                except(ValueError, KeyError):
                    pass
                except(ValidationError):
                    response['invalid'].append({
                        invitee: 'invalid email'})
                except(AlreadyAccepted):
                    response['invalid'].append({
                        invitee: 'already accepted'})
                except(AlreadyInvited):
                    response['invalid'].append(
                        {invitee: 'pending invite'})
                except(UserRegisteredEmail):
                    response['invalid'].append(
                        {invitee: 'user registered email'})
                else:
                    invite.send_invitation(request)
                    response['valid'].append({invitee: 'invited'})

        if response['valid']:
            status_code = 201

        return HttpResponse(
            json.dumps(response),
            status=status_code, content_type='application/json')
예제 #12
0
def _is_valid_email(email):
    try:
        validate_email(email)
        return True
    except:
        pass
    return False
예제 #13
0
파일: auth.py 프로젝트: WHELLINCK/frePPLe
  def authenticate(self, username=None, password=None):
    try:
      validate_email(username)
      # The user name looks like an email address
      user = User.objects.get(email=username)
      if user.check_password(password):
        return user
    except User.DoesNotExist:
      return None
    except ValidationError:
      # The user name isn't an email address
      try:
        user = User.objects.get(username=username)
        if user.check_password(password):
          return user
      except User.DoesNotExist:
        return None


    def get_user(self, user_id):
      '''
      This is identical to django.contrib.auth.backends.ModelBackend.get_user
      with a small performance optimization.
      '''
      try:
        return User.objects.get(pk=user_id)
      except User.DoesNotExist:
        return None
예제 #14
0
	def send_email(self, to_addr=None):
		""" Send the contact information to an email address

		:param to_addr: The email address to send to
		:type to_addr: str
		:returns: int

		"""
		if to_addr:
			if not isinstance(to_addr, str):
				raise TypeError('to_addr must be a string')

			try:
				validators.validate_email(to_addr)
			except:
				raise ValueError('to_addr must be a valid email address')
		else:
			to_addr = settings.DEFAULT_FROM_EMAIL

		fdate = self.date_created.strftime('%B %d, %Y at %I:%M:%S %p')

		return send_mail(
			subject='Elite Dodgeball Contact Form - %s' % self.subject,
			message='%s\r\n\r\n%s (%s) said:\r\n\r\n%s' % (
				fdate, self.name, self.email, self.body),
			from_email='%s <%s>' % (self.name, self.email),
			recipient_list=[to_addr],
			fail_silently=False if settings.DEBUG else True,
			html_message='%s<br /><br />%s (<a href="mailto:%s?%s">%s</a>) said:<br /><br />%s' % (
				fdate, self.name, self.email, parse.urlencode(query={
					'subject': 'RE: Elite Dodgeball Contact Form - %s' % self.subject
				}), self.email, html.escape(s=self.body).replace('\n', '<br />')))
예제 #15
0
def create_user(username, email, fname=None, lname=None):
	"""
	Attempts to create a user using the provided information.
	"""
	
	#Next, check to make sure that the username meets the criteria
	if len(username) < 5:
		raise inventory.exceptions.InvalidUsernameError(username)
	elif User.objects.filter(username=username).exists():
		raise inventory.exceptions.UnavailableUsernameError(username)
	
	
	try:
		validate_email(email)
	except ValidationError:
		raise inventory.exceptions.InvalidEmailError(email)
	
	try:
		#build the account object
		user = User.objects.create_user(username, email, 'thou art a knave')
		defaults.create_user_defaults(user)
	
		#this will fail if the provided email is invalid
		temporary_password = reset_password(user)
	except inventory.exceptions.InvalidEmailError as exception:
		#Did not work out, assign a generic password
		change_password(user, 'password')
		return (user, False, 'password')
	except Exception as exception:
		#Did not work out for some other reason; delete the user and continue
		user.delete()
		raise exception
	
	
	return (user, True, None)
예제 #16
0
    def _validate_email(self, email):
        try:
            validate_email(email)
            return True

        except ValidationError:
            return False
예제 #17
0
파일: models.py 프로젝트: groundupnews/gu
def validate_email_list(email_string_list):
    email_list = email_string_list.split(",")
    for email in email_list:
        try:
            validate_email(email.strip())
        except ValidationError:
            raise ValidationError("Email address is invalid: {}".format(email))
예제 #18
0
파일: views.py 프로젝트: irfan007/BLOG
def add_subscriber(request, email=None):
	if request.method == 'POST':
		email = request.POST['email_field']
		try:
			validate_email(email)					
		except:
			msg = ""
			return HttpResponse(msg)
		
		try:
			instance = Subscriber.objects.get(email=email)
			msg ="email already exits"
			return HttpResponse(msg)	
		except:
			time = datetime.now().isoformat()
			plain = email + '\0' + time
			token = sha1(plain)
			linktoken=token.hexdigest()
			e = Subscriber.objects.create(email=email , token = linktoken)
			mail_msg='''
            Hi 
            
            click the following link to Subscribe"+"http://127.0.0.1:8002/activate/?token={token}
            
            Thanks & Regards,
            Moocs Mentors Team
            '''.format(
                       token=linktoken,
            ) 

			send_mail('Subcription Mail', mail_msg, 'Brentwoods',[email], fail_silently=False)
			msg = "{0} added activate from Your mail".format(email)	 
		return HttpResponse(msg)
예제 #19
0
파일: forms.py 프로젝트: ZijianHe/zhihu
    def clean(self):
        identifier = self.cleaned_data.get('identifier')
        password = self.cleaned_data.get('password')

        if identifier and password:
            try:
                validate_email(identifier)
                try:
                    _username = TheUser.objects.get(email__iexact=identifier).email
                except ObjectDoesNotExist:
                    raise forms.ValidationError(
                        self.error_messages['invalid_login'],
                        code='invalid_login',
                    )
            except EmailValidationError:
                try:
                    _username = TheUser.objects.get(username__iexact=identifier).email
                except ObjectDoesNotExist:
                    raise forms.ValidationError(
                        self.error_messages['invalid_login'],
                        code='invalid_login',
                    )

            self.user_cache = authenticate(username=_username, password=password)

            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data
예제 #20
0
 def clean_mail_host(self):
     mail_host = self.cleaned_data['mail_host']
     try:
         validate_email('mail@' + mail_host)
     except:
         raise forms.ValidationError(_("Please enter a valid domain name"))
     return mail_host
예제 #21
0
 def _is_login_email(self, login):
     try:
         validators.validate_email(login)
         ret = True
     except exceptions.ValidationError:
         ret = False
     return ret
예제 #22
0
def report_problem(request):
    ret = {}
    if request.method == 'POST':
        email = request.POST.get("email")
        description = request.POST.get("description")
        please_reply = request.POST.get("please_reply", False)
        feelings = request.POST.get("feelings")
        if hasattr(request, "browser") and request.browser:
            # Don't use browser ID user provided - it either matches request.browser or is completely bogus.
            bid_public = request.browser.bid_public
        else:
            bid_public = "-"
        ret["email"] = email
        ret["description"] = description
        ret["please_reply"] = please_reply
        dont_send = False
        try:
            validate_email(email)
        except:
            if please_reply:
                dont_send = True
                messages.warning(request, "If you want a reply to your report, please enter proper email address")
        if not dont_send:
            ret["report_sent"] = True
            contents = "%s: feelings %s with %s. [%s] reply.\n\n%s" % (email, feelings, bid_public, please_reply, description)
            mail_admins("Bug report from login service", contents)
            custom_log(request, "Received feedback from user: %s" % contents, level="warn")
    return render_to_response("login_frontend/report_problem.html", ret, context_instance=RequestContext(request))
예제 #23
0
파일: user.py 프로젝트: AthinaB/synnefo
def users_create(request):
    user_id = request.user_uniq
    req = api.utils.get_json_body(request)
    logger.info('users_create: %s request: %s', user_id, req)

    user_data = req.get('user', {})
    email = user_data.get('username', None)

    first_name = user_data.get('first_name', None)
    last_name = user_data.get('last_name', None)
    affiliation = user_data.get('affiliation', None)
    password = user_data.get('password', None)
    metadata = user_data.get('metadata', {})

    password_gen = AstakosUser.objects.make_random_password
    if not password:
        password = password_gen()

    try:
        validate_email(email)
    except ValidationError:
        raise faults.BadRequest("Invalid username (email format required)")

    if AstakosUser.objects.verified_user_exists(email):
        raise faults.Conflict("User '%s' already exists" % email)

    if not first_name:
        raise faults.BadRequest("Invalid first_name")

    if not last_name:
        raise faults.BadRequest("Invalid last_name")

    has_signed_terms = True

    try:
        user = make_local_user(email, first_name=first_name,
                               last_name=last_name, password=password,
                               has_signed_terms=has_signed_terms)
        if metadata:
            # we expect a unique local auth provider for the user
            provider = user.auth_providers.get()
            provider.info = metadata
            provider.affiliation = affiliation
            provider.save()

        user = AstakosUser.objects.get(pk=user.pk)
        code = user.verification_code
        ver_res = activation_backend.handle_verification(user, code)
        if ver_res.is_error():
            raise Exception(ver_res.message)

        # in case of auto moderation user moderation is handled within the
        # verification process, no need to reapply moderation process
        if not user.moderated:
            mod_res = activation_backend.handle_moderation(user, accept=True)
            if mod_res.is_error():
                raise Exception(ver_res.message)

    except Exception, e:
        raise faults.BadRequest(e.message)
예제 #24
0
    def handle(self, *args, **options):
        usage = 'Required arguments: source-address destination-address [--create-domain]'
        if len(args) != 3:
            raise CommandError(usage)

        fqdn = args[0].strip().lower()
        source = args[1].strip().lower()

        if fqdn.startswith('@'):
            fqdn = fqdn[1:]

        destination = args[2].strip().lower()
        try:
            validate_email(destination)
        except ValidationError:
            msg = 'Improperly formatted email address: {0}.'.format(destination)
            raise CommandError(msg)

        try:
            domain = Domain.objects.get(fqdn=fqdn)
        except Domain.DoesNotExist:
            if options['create_domain']:
                domain = Domain.objects.create(fqdn=fqdn)
                self.stdout.write('Created domain: {0}.\n'.format(str(domain)))
            else:
                raise CommandError("Domain '{0}', does not exist.".format(fqdn))

        try:
            Alias.objects.create(domain=domain, source=source,
                                 destination=destination)
        except IntegrityError:
            raise CommandError('Alias exists already.')

        self.stdout.write('Success.\n')
예제 #25
0
def subscribe(request):
    """
    Takes POST data (``email`` and optional ``next`` fields), submitting the ``email`` field to
    the newsletter provider for subscription to a mailing list, and redirecting the user to the value
    of ``next`` (this can also be provided in the querystring), or the homepage if no follow-on URL is
    supplied, with a message in the ``django.contrib.messages`` queue to let them know it was successful.
    
    If the email address is invalid or the subscription process was unsuccessful, the user is redirected
    to the follow-on URL and a message placed in the ``django.contrib.messages`` queue letting them know
    what the issue was.
    """
    
    email = request.POST.get('email')
    next = request.POST.get('next', request.GET.get('next', '/'))
    valid = False
    
    if not email:
        messages.error(request, u'Please enter your email address')
    else:
        try:
            validate_email(email)
            valid = True
        except ValidationError:
            messages.error(request, u'Please enter a valid email address')
    
    if valid:
        shortcuts.subscribe(email, list_id = 'newsletter')
        messages.success(request, u'Thanks for subscribing to our newsletter.')
    
    return HttpResponseRedirect(next)
예제 #26
0
 def _is_email(self, email):
     """Returns True if given string is valid e-mail address"""
     try:
         validate_email(email)
         return True
     except ValidationError:
         return False
예제 #27
0
def register_ajax(request):
  User = get_user_model()
  email = request.POST.get('email',None)
  _Q = Q(email=email)|Q(username=email)
  for f in getattr(settings,"EXTRA_AUTH_FIELDS",[]):
    _Q = _Q | Q(**{f:email})
  matching_users = list(User.objects.filter(_Q))
  if email and 'password' in request.POST:
    user = authenticate(username=email,password=request.POST['password'])
    if user:
      login(request,user)
      return JsonResponse({'user': {'id': user.id, 'username': user.username, 'email': user.email } })
  if matching_users:
    return JsonResponse({"error": "A user with that email already exists. Please login or use another"},status=400)
  try:
    validate_email(email)
  except forms.ValidationError:
    return JsonResponse({"error": "Please enter a valid email address"},status=400)
  if not ('password' in request.POST and len(request.POST['password']) > 7):
    return JsonResponse({"error": "Please enter a password at least 8 characters long"},status=400)
  username = email.split("@")[0]
  while User.objects.filter(username=username):
    username = email.split("@")[0] + str(random.randint(0000,10000))
  user = User(
    email=email,
    username=username,
  )
  user.set_password(request.POST['password'])
  user.save()
  user.backend='django.contrib.auth.backends.ModelBackend'
  login(request,user)
  return JsonResponse({'user': {'id': user.id, 'username': user.username, 'email': user.email } })
예제 #28
0
파일: core_tags.py 프로젝트: taroved/fk
def is_email(value):
    try:
        validate_email(value)
    except ValidationError:
        return False
    else:
        return True
예제 #29
0
 def clean_mail_host(self):
     mail_host = self.cleaned_data['mail_host']
     try:
         validate_email('mail@' + mail_host)
     except:
         raise forms.ValidationError(_("Enter a valid Mail Host"))
     return mail_host
예제 #30
0
파일: forms.py 프로젝트: NaturalGIS/geonode
    def clean_user_identifiers(self):
        value = self.cleaned_data["user_identifiers"]
        new_members, errors = [], []

        for ui in value.split(","):
            ui = ui.strip()

            try:
                validate_email(ui)
                try:
                    new_members.append(get_user_model().objects.get(email=ui))
                except get_user_model().DoesNotExist:
                    new_members.append(ui)
            except ValidationError:
                try:
                    new_members.append(
                        get_user_model().objects.get(
                            username=ui))
                except get_user_model().DoesNotExist:
                    errors.append(ui)

        if errors:
            message = (
                "The following are not valid email addresses or "
                "usernames: %s; not added to the group" %
                ", ".join(errors))
            raise forms.ValidationError(message)

        return new_members
예제 #31
0
def multimail_validate(val):
    s = val.split(',')
    for part in s:
        validate_email(part.strip())
    return s
예제 #32
0
def submit_feedback(request):
    """
    Create a Zendesk ticket or if not available, send an email with the
    feedback form fields.

    If feedback submission is not enabled, any request will raise `Http404`.
    If any configuration parameter (`ZENDESK_URL`, `ZENDESK_USER`, or
    `ZENDESK_API_KEY`) is missing, any request will raise an `Exception`.
    The request must be a POST request specifying `subject` and `details`.
    If the user is not authenticated, the request must also specify `name` and
    `email`. If the user is authenticated, the `name` and `email` will be
    populated from the user's information. If any required parameter is
    missing, a 400 error will be returned indicating which field is missing and
    providing an error message. If Zendesk ticket creation fails, 500 error
    will be returned with no body; if ticket creation succeeds, an empty
    successful response (200) will be returned.
    """
    if not settings.FEATURES.get('ENABLE_FEEDBACK_SUBMISSION', False):
        raise Http404()
    if request.method != "POST":
        return HttpResponseNotAllowed(["POST"])

    def build_error_response(status_code, field, err_msg):
        return HttpResponse(json.dumps({
            "field": field,
            "error": err_msg
        }),
                            status=status_code)

    required_fields = ["subject", "details"]

    if not request.user.is_authenticated():
        required_fields += ["name", "email"]

    required_field_errs = {
        "subject": "Please provide a subject.",
        "details": "Please provide details.",
        "name": "Please provide your name.",
        "email": "Please provide a valid e-mail.",
    }
    for field in required_fields:
        if field not in request.POST or not request.POST[field]:
            return build_error_response(400, field, required_field_errs[field])

    if not request.user.is_authenticated():
        try:
            validate_email(request.POST["email"])
        except ValidationError:
            return build_error_response(400, "email",
                                        required_field_errs["email"])

    success = False
    context = get_feedback_form_context(request)

    #Update the tag info with 'enterprise_learner' if the user belongs to an enterprise customer.
    enterprise_learner_data = enterprise_api.get_enterprise_learner_data(
        site=request.site, user=request.user)
    if enterprise_learner_data:
        context["tags"]["learner_type"] = "enterprise_learner"

    support_backend = configuration_helpers.get_value(
        'CONTACT_FORM_SUBMISSION_BACKEND', SUPPORT_BACKEND_ZENDESK)

    if support_backend == SUPPORT_BACKEND_EMAIL:
        try:
            send_mail(subject=render_to_string(
                'emails/contact_us_feedback_email_subject.txt', context),
                      message=render_to_string(
                          'emails/contact_us_feedback_email_body.txt',
                          context),
                      from_email=context["support_email"],
                      recipient_list=[context["support_email"]],
                      fail_silently=False)
            success = True
        except SMTPException:
            log.exception(
                'Error sending feedback to contact_us email address.')
            success = False

    else:
        if not settings.ZENDESK_URL or not settings.ZENDESK_USER or not settings.ZENDESK_API_KEY:
            raise Exception("Zendesk enabled but not configured")

        custom_fields = None
        if settings.ZENDESK_CUSTOM_FIELDS:
            custom_field_context = _get_zendesk_custom_field_context(
                request, learner_data=enterprise_learner_data)
            custom_fields = _format_zendesk_custom_fields(custom_field_context)

        success = _record_feedback_in_zendesk(
            context["realname"],
            context["email"],
            context["subject"],
            context["details"],
            context["tags"],
            context["additional_info"],
            support_email=context["support_email"],
            custom_fields=custom_fields)

    _record_feedback_in_datadog(context["tags"])

    return HttpResponse(status=(200 if success else 500))
예제 #33
0
def validateEmail(mail):
    try:
        validate_email(mail)
        return True
    except ValidationError:
        return False
예제 #34
0
def social_associate_user_helper(backend: BaseAuth, return_data: Dict[str, Any],
                                 *args: Any, **kwargs: Any) -> Optional[UserProfile]:
    """Responsible for doing the Zulip-account lookup and validation parts
    of the Zulip Social auth pipeline (similar to the authenticate()
    methods in most other auth backends in this file).

    Returns a UserProfile object for successful authentication, and None otherwise.
    """
    subdomain = backend.strategy.session_get('subdomain')
    try:
        realm = get_realm(subdomain)
    except Realm.DoesNotExist:
        return_data["invalid_realm"] = True
        return None
    return_data["realm_id"] = realm.id

    if not auth_enabled_helper([backend.auth_backend_name], realm):
        return_data["auth_backend_disabled"] = True
        return None

    if 'auth_failed_reason' in kwargs.get('response', {}):
        return_data["social_auth_failed_reason"] = kwargs['response']["auth_failed_reason"]
        return None
    elif hasattr(backend, 'get_verified_emails'):
        # Some social backends, like GitHubAuthBackend, don't
        # guarantee that the `details` data is validated (i.e., it's
        # possible users can put any string they want in the "email"
        # field of the `details` object).  For those backends, we have
        # custom per-backend code to properly fetch only verified
        # email addresses from the appropriate third-party API.
        verified_emails = backend.get_verified_emails(*args, **kwargs)
        verified_emails_length = len(verified_emails)
        if verified_emails_length == 0:
            # TODO: Provide a nice error message screen to the user
            # for this case, rather than just logging a warning.
            logging.warning("Social auth (%s) failed because user has no verified emails" %
                            (backend.auth_backend_name,))
            return_data["email_not_verified"] = True
            return None

        if verified_emails_length == 1:
            chosen_email = verified_emails[0]
        else:
            chosen_email = backend.strategy.request_data().get('email')

        if not chosen_email:
            return render(backend.strategy.request, 'zerver/social_auth_select_email.html', context = {
                'primary_email': verified_emails[0],
                'verified_non_primary_emails': verified_emails[1:],
                'backend': 'github'
            })

        try:
            validate_email(chosen_email)
        except ValidationError:
            return_data['invalid_email'] = True
            return None

        if chosen_email not in verified_emails:
            # If a user edits the submit value for the choose email form, we might
            # end up with a wrong email associated with the account. The below code
            # takes care of that.
            logging.warning("Social auth (%s) failed because user has no verified"
                            " emails associated with the account" %
                            (backend.auth_backend_name,))
            return_data["email_not_associated"] = True
            return None

        validated_email = chosen_email
    else:  # nocoverage
        # This code path isn't used by GitHubAuthBackend
        validated_email = kwargs["details"].get("email")

    if not validated_email:  # nocoverage
        # This code path isn't used with GitHubAuthBackend, but may be relevant for other
        # social auth backends.
        return_data['invalid_email'] = True
        return None

    return_data["valid_attestation"] = True
    return_data['validated_email'] = validated_email
    user_profile = common_get_active_user(validated_email, realm, return_data)

    if 'fullname' in kwargs["details"]:
        return_data["full_name"] = kwargs["details"]["fullname"]
    else:
        # If we add support for any of the social auth backends that
        # don't provide this feature, we'll need to add code here.
        raise AssertionError("Social auth backend doesn't provide fullname")

    return user_profile
예제 #35
0
def is_valid_email(email: str) -> bool:
    try:
        validate_email(email)
    except ValidationError:
        return False
    return True
예제 #36
0
def create_user(request):
    first_name = request.POST['first_name']
    last_name = request.POST['last_name']
    username = request.POST['username']
    email = request.POST['email']
    height = float(request.POST['height'])
    weight = float(request.POST['weight'])
    gender = request.POST['gender']
    waist_circumference = float(
        request.POST['waist']) if request.POST['waist'] != '' else None
    date_of_birth = request.POST['dob']
    password = request.POST['password']
    password_repeat = request.POST['password_repeat']

    # validation on different fields
    if password != password_repeat:
        raise ValidationError('Please ensure the password repeat is matched')
    validate_password(password)
    validate_email(email)
    if not '1900-01-01' <= date_of_birth <= '2010-12-31':
        raise ValidationError('Invalid date of birth')
    if height not in range(130, 281):
        raise ValidationError('height must be between 130 and 280')
    if weight not in range(30, 636):
        raise ValidationError('weight must be between 30 and 635')
    bound = {
        'Male': range(70, 131),
        'Female': range(65, 116),
        'Prefer_not_to_say': range(65, 131)
    }[gender]
    if waist_circumference is not None and waist_circumference not in bound:
        raise ValidationError(
            f'waist circumference must be between {bound.start} and {bound.stop}'
        )

    # creating user on the database
    new_user = User.objects.create_user(username,
                                        email,
                                        password,
                                        first_name=first_name,
                                        last_name=last_name,
                                        is_active=False)
    UserProfile.objects.create(user=new_user,
                               date_of_birth=date_of_birth,
                               gender=gender,
                               height=height,
                               weight=weight,
                               waist_circumference=waist_circumference,
                               profile_picture='profile_image/default.png')

    # send out the verification email
    domain = get_current_site(request).domain
    uid = urlsafe_base64_encode(force_bytes(new_user.id))
    token = account_activation_token.make_token(new_user)
    send_mail(
        'Health Tracker: Verification required', f'''
        Thank you for registering. 
        Please click the link below to verify account
        http://{domain}/activate/{uid}/{token}
        ''', settings.EMAIL_HOST_USER, [email])

    return 'Account created successfully. Please check your email to activate your account.'
예제 #37
0
def accounts_register(request):
    # type: (HttpRequest) -> HttpResponse
    key = request.POST['key']
    confirmation = Confirmation.objects.get(confirmation_key=key)
    prereg_user = confirmation.content_object
    email = prereg_user.email
    realm_creation = prereg_user.realm_creation
    try:
        existing_user_profile = get_user_profile_by_email(email)
    except UserProfile.DoesNotExist:
        existing_user_profile = None

    validators.validate_email(email)
    # If OPEN_REALM_CREATION is enabled all user sign ups should go through the
    # special URL with domain name so that REALM can be identified if multiple realms exist
    unique_open_realm = get_unique_open_realm()
    if unique_open_realm is not None:
        realm = unique_open_realm
    elif prereg_user.referred_by:
        # If someone invited you, you are joining their realm regardless
        # of your e-mail address.
        realm = prereg_user.referred_by.realm
    elif prereg_user.realm:
        # You have a realm set, even though nobody referred you. This
        # happens if you sign up through a special URL for an open realm.
        realm = prereg_user.realm
    elif realm_creation:
        # For creating a new realm, there is no existing realm or domain
        realm = None
    elif settings.REALMS_HAVE_SUBDOMAINS:
        realm = get_realm(get_subdomain(request))
    else:
        realm = get_realm_by_email_domain(email)

    if realm and not email_allowed_for_realm(email, realm):
        return render(request,
                      "zerver/closed_realm.html",
                      context={"closed_domain_name": realm.name})

    if realm and realm.deactivated:
        # The user is trying to register for a deactivated realm. Advise them to
        # contact support.
        return render(request,
                      "zerver/deactivated.html",
                      context={
                          "deactivated_domain_name": realm.name,
                          "zulip_administrator": settings.ZULIP_ADMINISTRATOR
                      })

    try:
        if existing_user_profile is not None and existing_user_profile.is_mirror_dummy:
            # Mirror dummy users to be activated must be inactive
            is_inactive(email)
        else:
            # Other users should not already exist at all.
            user_email_is_unique(email)
    except ValidationError:
        return HttpResponseRedirect(
            reverse('django.contrib.auth.views.login') + '?email=' +
            urllib.parse.quote_plus(email))

    name_validated = False
    full_name = None

    if request.POST.get('from_confirmation'):
        try:
            del request.session['authenticated_full_name']
        except KeyError:
            pass
        if realm is not None and realm.is_zephyr_mirror_realm:
            # For MIT users, we can get an authoritative name from Hesiod.
            # Technically we should check that this is actually an MIT
            # realm, but we can cross that bridge if we ever get a non-MIT
            # zephyr mirroring realm.
            hesiod_name = compute_mit_user_fullname(email)
            form = RegistrationForm(
                initial={
                    'full_name': hesiod_name if "@" not in hesiod_name else ""
                })
            name_validated = True
        elif settings.POPULATE_PROFILE_VIA_LDAP:
            for backend in get_backends():
                if isinstance(backend, LDAPBackend):
                    ldap_attrs = _LDAPUser(
                        backend, backend.django_to_ldap_username(email)).attrs
                    try:
                        ldap_full_name = ldap_attrs[
                            settings.AUTH_LDAP_USER_ATTR_MAP['full_name']][0]
                        request.session[
                            'authenticated_full_name'] = ldap_full_name
                        name_validated = True
                        # We don't use initial= here, because if the form is
                        # complete (that is, no additional fields need to be
                        # filled out by the user) we want the form to validate,
                        # so they can be directly registered without having to
                        # go through this interstitial.
                        form = RegistrationForm({'full_name': ldap_full_name})
                        # FIXME: This will result in the user getting
                        # validation errors if they have to enter a password.
                        # Not relevant for ONLY_SSO, though.
                        break
                    except TypeError:
                        # Let the user fill out a name and/or try another backend
                        form = RegistrationForm()
        elif 'full_name' in request.POST:
            form = RegistrationForm(
                initial={'full_name': request.POST.get('full_name')})
        else:
            form = RegistrationForm()
    else:
        postdata = request.POST.copy()
        if name_changes_disabled(realm):
            # If we populate profile information via LDAP and we have a
            # verified name from you on file, use that. Otherwise, fall
            # back to the full name in the request.
            try:
                postdata.update(
                    {'full_name': request.session['authenticated_full_name']})
                name_validated = True
            except KeyError:
                pass
        form = RegistrationForm(postdata)
        if not password_auth_enabled(realm):
            form['password'].field.required = False

    if form.is_valid():
        if password_auth_enabled(realm):
            password = form.cleaned_data['password']
        else:
            # SSO users don't need no passwords
            password = None

        if realm_creation:
            string_id = form.cleaned_data['realm_subdomain']
            realm_name = form.cleaned_data['realm_name']
            org_type = int(form.cleaned_data['realm_org_type'])
            realm = do_create_realm(string_id, realm_name,
                                    org_type=org_type)[0]

            set_default_streams(realm, settings.DEFAULT_NEW_REALM_STREAMS)

        full_name = form.cleaned_data['full_name']
        short_name = email_to_username(email)
        first_in_realm = len(
            UserProfile.objects.filter(realm=realm, is_bot=False)) == 0

        timezone = u""
        if 'timezone' in request.POST and request.POST[
                'timezone'] in get_all_timezones():
            timezone = request.POST['timezone']

        # FIXME: sanitize email addresses and fullname
        if existing_user_profile is not None and existing_user_profile.is_mirror_dummy:
            user_profile = existing_user_profile
            do_activate_user(user_profile)
            do_change_password(user_profile, password)
            do_change_full_name(user_profile, full_name)
            do_set_user_display_setting(user_profile, 'timezone', timezone)
        else:
            user_profile = do_create_user(
                email,
                password,
                realm,
                full_name,
                short_name,
                prereg_user=prereg_user,
                tos_version=settings.TOS_VERSION,
                timezone=timezone,
                newsletter_data={"IP": request.META['REMOTE_ADDR']})

        if first_in_realm:
            do_change_is_admin(user_profile, True)

        if realm_creation and settings.REALMS_HAVE_SUBDOMAINS:
            # Because for realm creation, registration happens on the
            # root domain, we need to log them into the subdomain for
            # their new realm.
            return redirect_and_log_into_subdomain(realm, full_name, email)

        # This dummy_backend check below confirms the user is
        # authenticating to the correct subdomain.
        return_data = {}  # type: Dict[str, bool]
        auth_result = authenticate(username=user_profile.email,
                                   realm_subdomain=realm.subdomain,
                                   return_data=return_data,
                                   use_dummy_backend=True)
        if return_data.get('invalid_subdomain'):
            # By construction, this should never happen.
            logging.error("Subdomain mismatch in registration %s: %s" % (
                realm.subdomain,
                user_profile.email,
            ))
            return redirect('/')
        login(request, auth_result)
        return HttpResponseRedirect(realm.uri +
                                    reverse('zerver.views.home.home'))

    return render(
        request,
        'zerver/register.html',
        context={
            'form': form,
            'email': email,
            'key': key,
            'full_name': request.session.get('authenticated_full_name', None),
            'lock_name': name_validated and name_changes_disabled(realm),
            # password_auth_enabled is normally set via our context processor,
            # but for the registration form, there is no logged in user yet, so
            # we have to set it here.
            'creating_new_team': realm_creation,
            'realms_have_subdomains': settings.REALMS_HAVE_SUBDOMAINS,
            'password_auth_enabled': password_auth_enabled(realm),
            'MAX_REALM_NAME_LENGTH': str(Realm.MAX_REALM_NAME_LENGTH),
            'MAX_NAME_LENGTH': str(UserProfile.MAX_NAME_LENGTH),
            'MAX_PASSWORD_LENGTH': str(form.MAX_PASSWORD_LENGTH),
            'MAX_REALM_SUBDOMAIN_LENGTH': str(Realm.MAX_REALM_SUBDOMAIN_LENGTH)
        })
예제 #38
0
    def handle(self, csvfile, **options):
        verbosity = int(options.get('verbosity', 1))

        try:
            data = csv.DictReader(open(csvfile))
        except csv.Error as e:
            sys.stderr.write("ERROR: Failed to read CSV file.\n")
            sys.exit(1)

        success = 0
        fail_count = 0
        skip = 0
        for user in data:
            fail = False

            if verbosity >= 1:
                print("Attempting to send an invite to user '%s' at '%s'" %
                      (user['username'], user['email']))

            if 'username' not in user:
                sys.stderr.write("Error: Failed to find username column.\n")
                fail = True
            if 'password' not in user:
                sys.stderr.write("Error: Failed to find password column.\n")
                fail = True
            if 'short_name' not in user:
                sys.stderr.write("Error: Failed to find short_name column.\n")
                fail = True
            if 'full_name' not in user:
                sys.stderr.write("Error: Failed to find full_name column.\n")
                fail = True
            if 'email' not in user:
                sys.stderr.write("Error: Failed to find email column.\n")
                fail = True
            if 'institute' not in user:
                sys.stderr.write("Error: Failed to find institute column.\n")
                fail = True
            if 'project' not in user:
                sys.stderr.write("Error: Failed to find project column.\n")
                fail = True

            if not RE_VALID_USERNAME.match(user['username']):
                sys.stderr.write("Error: Username is invalid. "
                                 "Use only letters, digits and underscores.\n")
                fail = True

            try:
                validate_email(user['email'])
            except exceptions.ValidationError:
                sys.stderr.write("Error: E-mail address '%s' is invalid.\n" %
                                 user['email'])
                fail = True

            if fail:
                sys.stderr.write(
                    "Skipping row for username '%s' due to errors\n" %
                    user['username'])
                fail_count += 1
                continue

            try:
                institute = Institute.objects.get(name=user['institute'])
                user['institute'] = institute
            except Institute.DoesNotExist:
                sys.stderr.write(
                    "Error: Institute '%s' does not exist. Skipping\n" %
                    user['institute'])
                fail_count += 1
                continue

            project = None
            if user['project']:
                try:
                    project = Project.objects.get(pid=user['project'])
                except Project.DoesNotExist:
                    sys.stderr.write(
                        "Error: Project '%s' does not exist. Skipping\n" %
                        user['project'])
                    fail_count += 1
                    continue

            applicant, existing_person = get_applicant_from_email(
                user['email'])
            if existing_person:
                print("skipping %s:%s, user already exists" %
                      (user['username'], user['email']))
                skip += 1
                continue

            application = ProjectApplication()
            applicant.short_name = user["short_name"]
            applicant.full_name = user["full_name"]
            applicant.username = user["username"]
            application.applicant = applicant
            application.project = project
            application.state = ProjectApplication.OPEN
            application.header_message = "Please select your institute and hit the 'SAML login' button when prompted"
            application.reopen()

            email_link, is_secret = base.get_email_link(application)
            emails.send_invite_email(application, email_link, is_secret)
            success += 1

        print('')
        print('Added:   %s' % success)
        print('Skipped: %s' % skip)
        print('Failed:  %s' % fail_count)

        sys.exit(0)
예제 #39
0
def accounts_register(request: HttpRequest) -> HttpResponse:
    try:
        key = request.POST.get('key', default='')
        confirmation = Confirmation.objects.get(confirmation_key=key)
    except Confirmation.DoesNotExist:
        return render(request, "zerver/confirmation_link_expired_error.html")

    prereg_user = confirmation.content_object
    if prereg_user.status == confirmation_settings.STATUS_REVOKED:
        return render(request, "zerver/confirmation_link_expired_error.html")
    email = prereg_user.email
    realm_creation = prereg_user.realm_creation
    password_required = prereg_user.password_required

    role = get_role_for_new_user(prereg_user.invited_as, realm_creation)

    try:
        validators.validate_email(email)
    except ValidationError:
        return render(request,
                      "zerver/invalid_email.html",
                      context={"invalid_email": True})

    if realm_creation:
        # For creating a new realm, there is no existing realm or domain
        realm = None
    else:
        if get_subdomain(request) != prereg_user.realm.string_id:
            return render_confirmation_key_error(
                request,
                ConfirmationKeyException(
                    ConfirmationKeyException.DOES_NOT_EXIST))
        realm = prereg_user.realm
        try:
            email_allowed_for_realm(email, realm)
        except DomainNotAllowedForRealmError:
            return render(request,
                          "zerver/invalid_email.html",
                          context={
                              "realm_name": realm.name,
                              "closed_domain": True
                          })
        except DisposableEmailError:
            return render(request,
                          "zerver/invalid_email.html",
                          context={
                              "realm_name": realm.name,
                              "disposable_emails_not_allowed": True
                          })
        except EmailContainsPlusError:
            return render(request,
                          "zerver/invalid_email.html",
                          context={
                              "realm_name": realm.name,
                              "email_contains_plus": True
                          })

        if realm.deactivated:
            # The user is trying to register for a deactivated realm. Advise them to
            # contact support.
            return redirect_to_deactivation_notice()

        try:
            validate_email_not_already_in_realm(realm, email)
        except ValidationError:
            view_url = reverse('django.contrib.auth.views.login')
            redirect_url = add_query_to_redirect_url(
                view_url, 'email=' + urllib.parse.quote_plus(email))
            return HttpResponseRedirect(redirect_url)

    name_validated = False
    full_name = None
    require_ldap_password = False

    if request.POST.get('from_confirmation'):
        try:
            del request.session['authenticated_full_name']
        except KeyError:
            pass

        ldap_full_name = None
        if settings.POPULATE_PROFILE_VIA_LDAP:
            # If the user can be found in LDAP, we'll take the full name from the directory,
            # and further down create a form pre-filled with it.
            for backend in get_backends():
                if isinstance(backend, LDAPBackend):
                    try:
                        ldap_username = backend.django_to_ldap_username(email)
                    except ZulipLDAPExceptionNoMatchingLDAPUser:
                        logging.warning(
                            "New account email %s could not be found in LDAP",
                            email)
                        break

                    # Note that this `ldap_user` object is not a
                    # `ZulipLDAPUser` with a `Realm` attached, so
                    # calling `.populate_user()` on it will crash.
                    # This is OK, since we're just accessing this user
                    # to extract its name.
                    #
                    # TODO: We should potentially be accessing this
                    # user to sync its initial avatar and custom
                    # profile fields as well, if we indeed end up
                    # creating a user account through this flow,
                    # rather than waiting until `manage.py
                    # sync_ldap_user_data` runs to populate it.
                    ldap_user = _LDAPUser(backend, ldap_username)

                    try:
                        ldap_full_name, _ = backend.get_mapped_name(ldap_user)
                    except TypeError:
                        break

                    # Check whether this is ZulipLDAPAuthBackend,
                    # which is responsible for authentication and
                    # requires that LDAP accounts enter their LDAP
                    # password to register, or ZulipLDAPUserPopulator,
                    # which just populates UserProfile fields (no auth).
                    require_ldap_password = isinstance(backend,
                                                       ZulipLDAPAuthBackend)
                    break

        if ldap_full_name:
            # We don't use initial= here, because if the form is
            # complete (that is, no additional fields need to be
            # filled out by the user) we want the form to validate,
            # so they can be directly registered without having to
            # go through this interstitial.
            form = RegistrationForm({'full_name': ldap_full_name},
                                    realm_creation=realm_creation)
            request.session['authenticated_full_name'] = ldap_full_name
            name_validated = True
        elif realm is not None and realm.is_zephyr_mirror_realm:
            # For MIT users, we can get an authoritative name from Hesiod.
            # Technically we should check that this is actually an MIT
            # realm, but we can cross that bridge if we ever get a non-MIT
            # zephyr mirroring realm.
            hesiod_name = compute_mit_user_fullname(email)
            form = RegistrationForm(initial={
                'full_name':
                hesiod_name if "@" not in hesiod_name else ""
            },
                                    realm_creation=realm_creation)
            name_validated = True
        elif prereg_user.full_name:
            if prereg_user.full_name_validated:
                request.session[
                    'authenticated_full_name'] = prereg_user.full_name
                name_validated = True
                form = RegistrationForm({'full_name': prereg_user.full_name},
                                        realm_creation=realm_creation)
            else:
                form = RegistrationForm(
                    initial={'full_name': prereg_user.full_name},
                    realm_creation=realm_creation)
        elif 'full_name' in request.POST:
            form = RegistrationForm(
                initial={'full_name': request.POST.get('full_name')},
                realm_creation=realm_creation,
            )
        else:
            form = RegistrationForm(realm_creation=realm_creation)
    else:
        postdata = request.POST.copy()
        if name_changes_disabled(realm):
            # If we populate profile information via LDAP and we have a
            # verified name from you on file, use that. Otherwise, fall
            # back to the full name in the request.
            try:
                postdata.update(
                    {'full_name': request.session['authenticated_full_name']})
                name_validated = True
            except KeyError:
                pass
        form = RegistrationForm(postdata, realm_creation=realm_creation)

    if not (password_auth_enabled(realm) and password_required):
        form['password'].field.required = False

    if form.is_valid():
        if password_auth_enabled(realm) and form['password'].field.required:
            password = form.cleaned_data['password']
        else:
            # If the user wasn't prompted for a password when
            # completing the authentication form (because they're
            # signing up with SSO and no password is required), set
            # the password field to `None` (Which causes Django to
            # create an unusable password).
            password = None

        if realm_creation:
            string_id = form.cleaned_data['realm_subdomain']
            realm_name = form.cleaned_data['realm_name']
            realm = do_create_realm(string_id, realm_name)
            setup_realm_internal_bots(realm)
        assert (realm is not None)

        full_name = form.cleaned_data['full_name']
        short_name = email_to_username(email)
        default_stream_group_names = request.POST.getlist(
            'default_stream_group')
        default_stream_groups = lookup_default_stream_groups(
            default_stream_group_names, realm)

        timezone = ""
        if 'timezone' in request.POST and request.POST[
                'timezone'] in get_all_timezones():
            timezone = request.POST['timezone']

        if 'source_realm' in request.POST and request.POST[
                "source_realm"] != "on":
            source_profile = get_source_profile(email,
                                                request.POST["source_realm"])
        else:
            source_profile = None

        if not realm_creation:
            try:
                existing_user_profile: Optional[
                    UserProfile] = get_user_by_delivery_email(email, realm)
            except UserProfile.DoesNotExist:
                existing_user_profile = None
        else:
            existing_user_profile = None

        user_profile: Optional[UserProfile] = None
        return_data: Dict[str, bool] = {}
        if ldap_auth_enabled(realm):
            # If the user was authenticated using an external SSO
            # mechanism like Google or GitHub auth, then authentication
            # will have already been done before creating the
            # PreregistrationUser object with password_required=False, and
            # so we don't need to worry about passwords.
            #
            # If instead the realm is using EmailAuthBackend, we will
            # set their password above.
            #
            # But if the realm is using LDAPAuthBackend, we need to verify
            # their LDAP password (which will, as a side effect, create
            # the user account) here using authenticate.
            # pregeg_user.realm_creation carries the information about whether
            # we're in realm creation mode, and the ldap flow will handle
            # that and create the user with the appropriate parameters.
            user_profile = authenticate(request=request,
                                        username=email,
                                        password=password,
                                        realm=realm,
                                        prereg_user=prereg_user,
                                        return_data=return_data)
            if user_profile is None:
                can_use_different_backend = email_auth_enabled(
                    realm) or any_social_backend_enabled(realm)
                if settings.LDAP_APPEND_DOMAIN:
                    # In LDAP_APPEND_DOMAIN configurations, we don't allow making a non-ldap account
                    # if the email matches the ldap domain.
                    can_use_different_backend = can_use_different_backend and (
                        not email_belongs_to_ldap(realm, email))
                if return_data.get(
                        "no_matching_ldap_user") and can_use_different_backend:
                    # If both the LDAP and Email or Social auth backends are
                    # enabled, and there's no matching user in the LDAP
                    # directory then the intent is to create a user in the
                    # realm with their email outside the LDAP organization
                    # (with e.g. a password stored in the Zulip database,
                    # not LDAP).  So we fall through and create the new
                    # account.
                    pass
                else:
                    # TODO: This probably isn't going to give a
                    # user-friendly error message, but it doesn't
                    # particularly matter, because the registration form
                    # is hidden for most users.
                    view_url = reverse('django.contrib.auth.views.login')
                    query = 'email=' + urllib.parse.quote_plus(email)
                    redirect_url = add_query_to_redirect_url(view_url, query)
                    return HttpResponseRedirect(redirect_url)
            elif not realm_creation:
                # Since we'll have created a user, we now just log them in.
                return login_and_go_to_home(request, user_profile)
            else:
                # With realm_creation=True, we're going to return further down,
                # after finishing up the creation process.
                pass

        if existing_user_profile is not None and existing_user_profile.is_mirror_dummy:
            user_profile = existing_user_profile
            do_activate_user(user_profile)
            do_change_password(user_profile, password)
            do_change_full_name(user_profile, full_name, user_profile)
            do_set_user_display_setting(user_profile, 'timezone', timezone)
            # TODO: When we clean up the `do_activate_user` code path,
            # make it respect invited_as_admin / is_realm_admin.

        if user_profile is None:
            user_profile = do_create_user(
                email,
                password,
                realm,
                full_name,
                short_name,
                prereg_user=prereg_user,
                role=role,
                tos_version=settings.TOS_VERSION,
                timezone=timezone,
                newsletter_data={"IP": request.META['REMOTE_ADDR']},
                default_stream_groups=default_stream_groups,
                source_profile=source_profile,
                realm_creation=realm_creation)

        if realm_creation:
            bulk_add_subscriptions([realm.signup_notifications_stream],
                                   [user_profile])
            send_initial_realm_messages(realm)

            # Because for realm creation, registration happens on the
            # root domain, we need to log them into the subdomain for
            # their new realm.
            return redirect_and_log_into_subdomain(
                ExternalAuthResult(user_profile=user_profile,
                                   data_dict={'is_realm_creation': True}))

        # This dummy_backend check below confirms the user is
        # authenticating to the correct subdomain.
        auth_result = authenticate(username=user_profile.delivery_email,
                                   realm=realm,
                                   return_data=return_data,
                                   use_dummy_backend=True)
        if return_data.get('invalid_subdomain'):
            # By construction, this should never happen.
            logging.error(
                "Subdomain mismatch in registration %s: %s",
                realm.subdomain,
                user_profile.delivery_email,
            )
            return redirect('/')

        return login_and_go_to_home(request, auth_result)

    return render(
        request,
        'zerver/register.html',
        context={
            'form': form,
            'email': email,
            'key': key,
            'full_name': request.session.get('authenticated_full_name', None),
            'lock_name': name_validated and name_changes_disabled(realm),
            # password_auth_enabled is normally set via our context processor,
            # but for the registration form, there is no logged in user yet, so
            # we have to set it here.
            'creating_new_team': realm_creation,
            'password_required': password_auth_enabled(realm)
            and password_required,
            'require_ldap_password': require_ldap_password,
            'password_auth_enabled': password_auth_enabled(realm),
            'root_domain_available': is_root_domain_available(),
            'default_stream_groups': get_default_stream_groups(realm),
            'accounts': get_accounts_for_email(email),
            'MAX_REALM_NAME_LENGTH': str(Realm.MAX_REALM_NAME_LENGTH),
            'MAX_NAME_LENGTH': str(UserProfile.MAX_NAME_LENGTH),
            'MAX_PASSWORD_LENGTH': str(form.MAX_PASSWORD_LENGTH),
            'MAX_REALM_SUBDOMAIN_LENGTH':
            str(Realm.MAX_REALM_SUBDOMAIN_LENGTH),
        },
    )
예제 #40
0
def accounts_register(request):
    # type: (HttpRequest) -> HttpResponse
    key = request.POST['key']
    confirmation = Confirmation.objects.get(confirmation_key=key)
    prereg_user = confirmation.content_object
    email = prereg_user.email
    realm_creation = prereg_user.realm_creation
    password_required = prereg_user.password_required
    is_realm_admin = prereg_user.invited_as_admin or realm_creation

    validators.validate_email(email)
    if prereg_user.referred_by:
        # If someone invited you, you are joining their realm regardless
        # of your e-mail address.
        realm = prereg_user.referred_by.realm
    elif realm_creation:
        # For creating a new realm, there is no existing realm or domain
        realm = None
    else:
        realm = get_realm(get_subdomain(request))

    if realm and not email_allowed_for_realm(email, realm):
        return render(request, "zerver/closed_realm.html",
                      context={"closed_domain_name": realm.name})

    if realm and realm.deactivated:
        # The user is trying to register for a deactivated realm. Advise them to
        # contact support.
        return redirect_to_deactivation_notice()

    try:
        validate_email_for_realm(realm, email)
    except ValidationError:
        return HttpResponseRedirect(reverse('django.contrib.auth.views.login') + '?email=' +
                                    urllib.parse.quote_plus(email))

    name_validated = False
    full_name = None

    if request.POST.get('from_confirmation'):
        try:
            del request.session['authenticated_full_name']
        except KeyError:
            pass
        if realm is not None and realm.is_zephyr_mirror_realm:
            # For MIT users, we can get an authoritative name from Hesiod.
            # Technically we should check that this is actually an MIT
            # realm, but we can cross that bridge if we ever get a non-MIT
            # zephyr mirroring realm.
            hesiod_name = compute_mit_user_fullname(email)
            form = RegistrationForm(
                initial={'full_name': hesiod_name if "@" not in hesiod_name else ""},
                realm_creation=realm_creation)
            name_validated = True
        elif settings.POPULATE_PROFILE_VIA_LDAP:
            for backend in get_backends():
                if isinstance(backend, LDAPBackend):
                    ldap_attrs = _LDAPUser(backend, backend.django_to_ldap_username(email)).attrs
                    try:
                        ldap_full_name = ldap_attrs[settings.AUTH_LDAP_USER_ATTR_MAP['full_name']][0]
                        request.session['authenticated_full_name'] = ldap_full_name
                        name_validated = True
                        # We don't use initial= here, because if the form is
                        # complete (that is, no additional fields need to be
                        # filled out by the user) we want the form to validate,
                        # so they can be directly registered without having to
                        # go through this interstitial.
                        form = RegistrationForm({'full_name': ldap_full_name},
                                                realm_creation=realm_creation)
                        # FIXME: This will result in the user getting
                        # validation errors if they have to enter a password.
                        # Not relevant for ONLY_SSO, though.
                        break
                    except TypeError:
                        # Let the user fill out a name and/or try another backend
                        form = RegistrationForm(realm_creation=realm_creation)
        elif 'full_name' in request.POST:
            form = RegistrationForm(
                initial={'full_name': request.POST.get('full_name')},
                realm_creation=realm_creation
            )
        else:
            form = RegistrationForm(realm_creation=realm_creation)
    else:
        postdata = request.POST.copy()
        if name_changes_disabled(realm):
            # If we populate profile information via LDAP and we have a
            # verified name from you on file, use that. Otherwise, fall
            # back to the full name in the request.
            try:
                postdata.update({'full_name': request.session['authenticated_full_name']})
                name_validated = True
            except KeyError:
                pass
        form = RegistrationForm(postdata, realm_creation=realm_creation)
        if not (password_auth_enabled(realm) and password_required):
            form['password'].field.required = False

    if form.is_valid():
        if password_auth_enabled(realm):
            password = form.cleaned_data['password']
        else:
            # SSO users don't need no passwords
            password = None

        if realm_creation:
            string_id = form.cleaned_data['realm_subdomain']
            realm_name = form.cleaned_data['realm_name']
            realm = do_create_realm(string_id, realm_name)
            setup_initial_streams(realm)
        assert(realm is not None)

        full_name = form.cleaned_data['full_name']
        short_name = email_to_username(email)
        default_stream_group_names = request.POST.getlist('default_stream_group')
        default_stream_groups = lookup_default_stream_groups(default_stream_group_names, realm)

        timezone = u""
        if 'timezone' in request.POST and request.POST['timezone'] in get_all_timezones():
            timezone = request.POST['timezone']

        try:
            existing_user_profile = get_user_profile_by_email(email)
        except UserProfile.DoesNotExist:
            existing_user_profile = None

        return_data = {}  # type: Dict[str, bool]
        if ldap_auth_enabled(realm):
            # If the user was authenticated using an external SSO
            # mechanism like Google or GitHub auth, then authentication
            # will have already been done before creating the
            # PreregistrationUser object with password_required=False, and
            # so we don't need to worry about passwords.
            #
            # If instead the realm is using EmailAuthBackend, we will
            # set their password above.
            #
            # But if the realm is using LDAPAuthBackend, we need to verify
            # their LDAP password (which will, as a side effect, create
            # the user account) here using authenticate.
            auth_result = authenticate(request,
                                       username=email,
                                       password=password,
                                       realm_subdomain=realm.subdomain,
                                       return_data=return_data)
            if auth_result is None:
                # TODO: This probably isn't going to give a
                # user-friendly error message, but it doesn't
                # particularly matter, because the registration form
                # is hidden for most users.
                return HttpResponseRedirect(reverse('django.contrib.auth.views.login') + '?email=' +
                                            urllib.parse.quote_plus(email))

            # Since we'll have created a user, we now just log them in.
            return login_and_go_to_home(request, auth_result)
        elif existing_user_profile is not None and existing_user_profile.is_mirror_dummy:
            user_profile = existing_user_profile
            do_activate_user(user_profile)
            do_change_password(user_profile, password)
            do_change_full_name(user_profile, full_name, user_profile)
            do_set_user_display_setting(user_profile, 'timezone', timezone)
            # TODO: When we clean up the `do_activate_user` code path,
            # make it respect invited_as_admin / is_realm_admin.
        else:
            user_profile = do_create_user(email, password, realm, full_name, short_name,
                                          prereg_user=prereg_user, is_realm_admin=is_realm_admin,
                                          tos_version=settings.TOS_VERSION,
                                          timezone=timezone,
                                          newsletter_data={"IP": request.META['REMOTE_ADDR']},
                                          default_stream_groups=default_stream_groups)

        if realm_creation:
            setup_initial_private_stream(user_profile)
            send_initial_realm_messages(realm)

        if realm_creation:
            # Because for realm creation, registration happens on the
            # root domain, we need to log them into the subdomain for
            # their new realm.
            return redirect_and_log_into_subdomain(realm, full_name, email)

        # This dummy_backend check below confirms the user is
        # authenticating to the correct subdomain.
        auth_result = authenticate(username=user_profile.email,
                                   realm_subdomain=realm.subdomain,
                                   return_data=return_data,
                                   use_dummy_backend=True)
        if return_data.get('invalid_subdomain'):
            # By construction, this should never happen.
            logging.error("Subdomain mismatch in registration %s: %s" % (
                realm.subdomain, user_profile.email,))
            return redirect('/')

        return login_and_go_to_home(request, auth_result)

    return render(
        request,
        'zerver/register.html',
        context={'form': form,
                 'email': email,
                 'key': key,
                 'full_name': request.session.get('authenticated_full_name', None),
                 'lock_name': name_validated and name_changes_disabled(realm),
                 # password_auth_enabled is normally set via our context processor,
                 # but for the registration form, there is no logged in user yet, so
                 # we have to set it here.
                 'creating_new_team': realm_creation,
                 'password_required': password_auth_enabled(realm) and password_required,
                 'password_auth_enabled': password_auth_enabled(realm),
                 'root_domain_available': is_root_domain_available(),
                 'default_stream_groups': get_default_stream_groups(realm),
                 'MAX_REALM_NAME_LENGTH': str(Realm.MAX_REALM_NAME_LENGTH),
                 'MAX_NAME_LENGTH': str(UserProfile.MAX_NAME_LENGTH),
                 'MAX_PASSWORD_LENGTH': str(form.MAX_PASSWORD_LENGTH),
                 'MAX_REALM_SUBDOMAIN_LENGTH': str(Realm.MAX_REALM_SUBDOMAIN_LENGTH)
                 }
    )
예제 #41
0
def validar_participantes(acta):
    errores = []
    obtener_config()

    participante_organizador = acta.get('participante_organizador', {})
    participantes = acta.get('participantes', [])
    config = obtener_config()

    # tienen que existir la cantidad de participantes aceptada
    if participante_organizador == {}:
        errores.append('Error en el formato del participante organizador.')

    if type(participantes) != list \
            or not (config['participantes_min'] <= len(participantes) <= config['participantes_max']):
        errores.append('Error en el formato de los participantes.')

    if len(errores) > 0:
        return errores

    errores += _validar_participante(participante_organizador, 0)
    for i, participante in enumerate(participantes):
        errores += _validar_participante(participante, i + 1)

    if len(errores) > 0:
        return errores

    ruts_participantes = [p['rut'] for p in participantes]
    ruts_participantes.append(participante_organizador['rut'])

    # validar emailstry:
    try:
        validate_email(participante_organizador['email'])
        for participante in participantes:
            validate_email(participante['email'])
    except ValidationError as e:
        errores.append('Existen emails inválidos.')

    # Ruts diferentes
    ruts = set(ruts_participantes)
    if len(ruts) != len(ruts_participantes):
        return ['Existen RUTs repetidos.']

    for rut in ruts:
        if not verificar_rut(rut):
            errores.append('Existen RUTs inválidos.')
            return errores

    if len(errores) > 0:
        return errores

    # Verificar que el encargado haya subido solo un encuentro del tipo
    encargado_dbs = Participante.objects.filter(
        rut=participante_organizador['rut'])
    if len(encargado_dbs) > 0:  # El encargado esta en la base de datos
        encargado_db = encargado_dbs.first()
        encuentros_db = Encuentro.objects.filter(encargado_id=encargado_db.pk)
        if len(
                encuentros_db
        ) > 0:  # Buscamos los encuentros con id del encargado y si tiene encuentros encargados...
            for encuentro in encuentros_db:  # Vemos si algun encuentro tiene el mismo tipo
                if encuentro.tipo_encuentro.tipo == acta['tipo']:
                    errores.append(
                        'El encargado de rut {0:s} ya organizo un encuentro de este tipo.'
                        .format(encargado_db.rut))

    # Verificar que los participantes no hayan enviado un acta antes
    if acta['tipo'] == 'Encuentro autoconvocado':
        participantes_en_db = Participante.objects.filter(rut__in=list(ruts))
        if len(participantes_en_db) > 0:
            participantes_ids = set([p.pk for p in participantes_en_db])
            participa_participantes = Participa.objects.filter(
                participante_id__in=list(participantes_ids))
            for participa in participa_participantes:
                if participa.encuentro.tipo_encuentro.tipo == acta['tipo']:
                    errores.append(
                        'El RUT {0:s} ya participó de este tipo de encuentro.'.
                        format(
                            participantes_en_db.filter(
                                pk=participa.participante_id).first().rut))

    errores += verificar_cedula(participante_organizador['rut'],
                                participante_organizador['serie_cedula'])
    return errores
예제 #42
0
 def validate(self, emails: List[str]) -> None:
     """Check if value consists only of valid emails."""
     super().validate(emails)
     for email in emails:
         validate_email(email)
예제 #43
0
def is_pku_mail(email):
    try:
        validate_email(email)
        return email.endswith("pku.edu.cn")
    except ValidationError as e:
        return False
예제 #44
0
def login(request):
    print '============================', request.data
    serializer = LoginSerializer(data=request.data)
    if serializer.is_valid():
        try:
            validate_email(serializer.validated_data['username'])
            user = authenticate(username=serializer.validated_data['username'],
                                password=serializer.validated_data['password'])
        except Exception:
            try:
                userprofile = UserProfile.objects.get(
                    employee_id=serializer.validated_data['username'])
                user = authenticate(
                    username=userprofile.email,
                    password=serializer.validated_data['password'])
            except Exception:
                user = None

        if user is not None:

            user_profile = user.userprofile
            print user_profile, user_profile.status

            if (user_profile.status == 'ACTIVE'):

                devicedetail_obj = DeviceDetail.objects.filter(
                    user_id=user.userprofile.id,
                    imei_no=serializer.validated_data['imei_no'])
                print 'device object', devicedetail_obj

                if len(devicedetail_obj) > 0:

                    user_info = UserProfileToJSON(user_profile,
                                                  devicedetail_obj[0])
                    print '=============>', user_info
                    #                    try:

                    Token.objects.filter(user=user).delete()
                    token = Token.objects.create(user=user)
                    print 'token no==>', token

                    return Response(
                        {
                            "result": "success",
                            "message": "LogIn Successful.",
                            "responsedata": user_info,
                            "authorization": "Token " + str(token)
                        },
                        status=status.HTTP_200_OK)

                else:
                    return Response(
                        {
                            "result": "failure",
                            "responsedata": invalid_imei_number
                        },
                        status=status.HTTP_403_FORBIDDEN)

            else:
                return Response(
                    {
                        "result": "failure",
                        "responsedata": account_not_activated
                    },
                    status=status.HTTP_403_FORBIDDEN)
        else:
            return Response(
                {
                    "result": "failure",
                    "responsedata": username_password_missmatch
                },
                status=status.HTTP_403_FORBIDDEN)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #45
0
 def check_email(self, email):
     try:
         validate_email(email)
         return True
     except forms.ValidationError:
         return False
예제 #46
0
def valid_email(email):
    try:
        validate_email(email)
        return True
    except:
        return False
예제 #47
0
def contact(request):

    user = user_get_owner()
    blog = blog_get_or_create(user)

    warning_form = False
    success_form = False
    error_form, error_form_msg = False, ''

    error_name, error_name_msg = False, ''
    error_email, error_email_msg = False, ''
    error_message, error_message_msg = False, ''

    if (request.method == 'POST' and 'name' in request.POST
            and 'email' in request.POST and 'message' in request.POST):
        name = request.POST['name']
        email = request.POST['email']
        message = request.POST['message']

        if not re.match('^.+$', name):
            error_name, error_name_msg = True, 'Please, enter your name.'
            warning_form = True

        try:
            validate_email(email)
        except ValidationError:
            error_email, error_email_msg = True, 'Please, enter a valid e-mail address.'
            warning_form = True

        if len(message) == 0:
            error_message, error_message_msg = True, 'Please, write a message for i reply you.'
            warning_form = True

        # get (separated) current year, month and day
        year, month, day = datetime.now().strftime('%Y %m %d').split(' ')
        today_start = datetime(int(year), int(month), int(day), 0, 0, 0)
        today_end = datetime(int(year), int(month), int(day), 23, 59, 59)

        # get number of messages from email address today
        num_max_messages_for_day = 3
        # number of messages by email
        num_messages_today_email = Message.objects.filter(
            email__iexact=email, date__gte=today_start,
            date__lte=today_end).count()
        # number of messages by ip address
        num_messages_today_ip = Message.objects.filter(
            ip__iexact=request.META['REMOTE_ADDR'],
            date__gte=today_start,
            date__lte=today_end).count()

        # check if a same email address is sending multiple messages
        if (num_messages_today_email >= num_max_messages_for_day
                or num_messages_today_ip >= num_max_messages_for_day):
            error_form = True
            error_form_msg = 'You have sent %d messages today, maximum number allowed.' % num_max_messages_for_day

        if not warning_form and not error_form:
            msg = Message(user=user,
                          ip=request.META['REMOTE_ADDR'],
                          author=name,
                          email=email,
                          content=message)
            msg.save()
            success_form = True
            # send email if this is a production environment
            if settings.PRODUCTION_ENVIRONMENT:
                # retrieve all unread message and send them
                unread_messages = Message.objects.filter(
                    user__id=user.id, is_readed=False).order_by('-date')
                for u_m in unread_messages:
                    try:
                        from_email = settings.ADMINS[0][1]
                        subject = 'New message from %s' % (
                            settings.BASE_URL.replace('http://', ''))
                        message = """On %s, %s <%s> wrote:
                        
                        %s""" % (u_m.date.strftime('%B %d, %Y at %H:%M'),
                                 u_m.author, u_m.email, u_m.content)

                        # remove tabs from message
                        s = ''
                        for line in message.split('\n'):
                            temp = line.strip()
                            s += temp if len(temp) > 0 else '\n\n'
                        message = s

                        send_mail(subject,
                                  message,
                                  from_email, [user.email],
                                  fail_silently=True)

                        msg = u_m
                        msg.is_readed = True
                        msg.save()
                    except:
                        pass

    return render_to_response('itsme/contact.html', {
        'user': user,
        'blog': blog,
        'request': request,
        'warning_form': warning_form,
        'success_form': success_form,
        'error_form': error_form,
        'error_form_msg': error_form_msg,
        'error_name': error_name,
        'error_name_msg': error_name_msg,
        'error_email': error_email,
        'error_email_msg': error_email_msg,
        'error_message': error_message,
        'error_message_msg': error_message_msg,
        'nav_active': 'contact',
    },
                              context_instance=RequestContext(request))
예제 #48
0
 def to_internal_value(self, data):  # POST
     if data:
         validate_email(data)
     return data
예제 #49
0
def send_pdf(request, report_id):
    to_return = {
        "status": "success",
        "message": "",
        "logMessages": [],
        "validRecipients": []
    }

    user = get_current_user()
    recipients = request.POST.get('to')
    comments = request.POST.get('comments', '')

    # recipient can't be empty
    if recipients.strip() == '':
        to_return["status"] = "error"
        to_return["message"] = _("Add a valid email address.")
        return JsonHttpResponse(to_return)

    recipients = re.compile("[\\s,;]+").split(recipients)

    valid_recipients = []
    for recipient in recipients:
        recipient = recipient.strip()
        if not recipient:
            continue
        try:
            validate_email(recipient)
            valid_recipients.append(recipient)
        except ValidationError:
            to_return["status"] = "error"
            to_return["message"] = _("There were errors.")
            to_return["logMessages"].append(
                _("'{email}' is not a valid email address.").format(
                    email=recipient))
            continue
    #if no valid emails, no need to proceed
    if len(valid_recipients) == 0:
        return JsonHttpResponse(to_return)

    # Only set visibility as private if user is auth and visibility POST param is private
    if request.fmsuser.is_pro() and "private" == request.POST.get(
            'visibility'):
        pro_version = True
    else:
        pro_version = False

    report = get_object_or_404(Report, id=report_id)
    #generate the pdf
    pdffile = generate_pdf("reports/pdf.html", {
        'report':
        report,
        'files':
        report.files() if pro_version else report.active_files(),
        'comments':
        report.comments() if pro_version else report.active_comments(),
        'activity_list':
        report.activities.all(),
        'visibility':
        'private' if pro_version else 'public',
        'BACKOFFICE':
        pro_version,
        'base_url':
        getattr(settings, 'RENDER_PDF_BASE_URL', None),
    },
                           context_instance=RequestContext(request))

    subject, html, text = transform_notification_template("mail-pdf",
                                                          report,
                                                          user,
                                                          comment=comments)

    for recipient in valid_recipients:
        msg = EmailMultiAlternatives(subject, text,
                                     settings.DEFAULT_FROM_EMAIL,
                                     (recipient, ))

        if html:
            msg.attach_alternative(html, "text/html")

        #reset the seek to 0 to be able to read multiple times the same file
        pdffile.seek(0)
        name = "export-incident-%s-date-%s.pdf" % (
            report.id, datetime.date.today().isoformat())
        msg.attach(name, pdffile.read(), 'application/pdf')

        msg.send()
        to_return["logMessages"].append(
            _("Successfully sent to '{email}'.").format(email=recipient))
        to_return["validRecipients"].append(recipient)

    if to_return["status"] == "success":
        to_return["message"] = _("PDF sent by email.")
    else:
        to_return["message"] = _("There were errors.")

    event = ReportEventLog(
        report=report,
        event_type=ReportEventLog.PDF_HISTORY,
        user=user,
        text=", ".join(valid_recipients),
    )
    event.save()

    return JsonHttpResponse(to_return)
예제 #50
0
 def validate_email(self, value):
     try:
         validate_email(value)
     except ValidationError as e:
         raise serializers.ValidationError('Enter a valid email address.')
     return value
예제 #51
0
def social_associate_user_helper(backend: BaseAuth, return_data: Dict[str, Any],
                                 *args: Any, **kwargs: Any) -> Optional[UserProfile]:
    """Responsible for doing the Zulip-account lookup and validation parts
    of the Zulip Social auth pipeline (similar to the authenticate()
    methods in most other auth backends in this file).
    """
    subdomain = backend.strategy.session_get('subdomain')
    realm = get_realm(subdomain)
    if realm is None:
        return_data["invalid_realm"] = True
        return None
    return_data["realm_id"] = realm.id

    if not auth_enabled_helper([backend.auth_backend_name], realm):
        return_data["auth_backend_disabled"] = True
        return None

    if 'auth_failed_reason' in kwargs.get('response', {}):
        return_data["social_auth_failed_reason"] = kwargs['response']["auth_failed_reason"]
        return None
    elif hasattr(backend, 'get_verified_emails'):
        # Some social backends, like GitHubAuthBackend, don't guarantee that
        # the `details` data is validated.
        verified_emails = backend.get_verified_emails(*args, **kwargs)
        if len(verified_emails) == 0:
            # TODO: Provide a nice error message screen to the user
            # for this case, rather than just logging a warning.
            logging.warning("Social auth (%s) failed because user has no verified emails" %
                            (backend.auth_backend_name,))
            return_data["email_not_verified"] = True
            return None
        # TODO: ideally, we'd prompt the user for which email they
        # want to use with another pipeline stage here.
        validated_email = verified_emails[0]
    else:  # nocoverage
        # This code path isn't used by GitHubAuthBackend
        validated_email = kwargs["details"].get("email")

    if not validated_email:  # nocoverage
        # This code path isn't used with GitHubAuthBackend, but may be relevant for other
        # social auth backends.
        return_data['invalid_email'] = True
        return None
    try:
        validate_email(validated_email)
    except ValidationError:
        return_data['invalid_email'] = True
        return None

    return_data["valid_attestation"] = True
    return_data['validated_email'] = validated_email
    user_profile = common_get_active_user(validated_email, realm, return_data)

    if 'fullname' in kwargs["details"]:
        return_data["full_name"] = kwargs["details"]["fullname"]
    else:
        # If we add support for any of the social auth backends that
        # don't provide this feature, we'll need to add code here.
        raise AssertionError("Social auth backend doesn't provide fullname")

    return user_profile
예제 #52
0
def find_account(
    request: HttpRequest,
    raw_emails: Optional[str] = REQ("emails", default=None)
) -> HttpResponse:
    url = reverse("find_account")

    emails: List[str] = []
    if request.method == "POST":
        form = FindMyTeamForm(request.POST)
        if form.is_valid():
            emails = form.cleaned_data["emails"]
            for i in range(len(emails)):
                try:
                    rate_limit_request_by_ip(request,
                                             domain="find_account_by_ip")
                except RateLimited as e:
                    assert e.secs_to_freedom is not None
                    return render(
                        request,
                        "zerver/rate_limit_exceeded.html",
                        context={"retry_after": int(e.secs_to_freedom)},
                        status=429,
                    )

            # Django doesn't support __iexact__in lookup with EmailField, so we have
            # to use Qs to get around that without needing to do multiple queries.
            emails_q = Q()
            for email in emails:
                emails_q |= Q(delivery_email__iexact=email)

            user_profiles = UserProfile.objects.filter(
                emails_q,
                is_active=True,
                is_bot=False,
                realm__deactivated=False)

            # We organize the data in preparation for sending exactly
            # one outgoing email per provided email address, with each
            # email listing all of the accounts that email address has
            # with the current Zulip server.
            context: Dict[str, Dict[str, Any]] = {}
            for user in user_profiles:
                key = user.delivery_email.lower()
                context.setdefault(key, {})
                context[key].setdefault("realms", [])
                context[key]["realms"].append(user.realm)
                context[key]["external_host"] = settings.EXTERNAL_HOST
                # This value will end up being the last user ID among
                # matching accounts; since it's only used for minor
                # details like language, that arbitrary choice is OK.
                context[key]["to_user_id"] = user.id

            for delivery_email, realm_context in context.items():
                realm_context["email"] = delivery_email
                send_email(
                    "zerver/emails/find_team",
                    to_user_ids=[realm_context["to_user_id"]],
                    context=realm_context,
                    from_address=FromAddress.SUPPORT,
                    request=request,
                )

            # Note: Show all the emails in the result otherwise this
            # feature can be used to ascertain which email addresses
            # are associated with Zulip.
            data = urllib.parse.urlencode({"emails": ",".join(emails)})
            return redirect(add_query_to_redirect_url(url, data))
    else:
        form = FindMyTeamForm()
        # The below validation is perhaps unnecessary, in that we
        # shouldn't get able to get here with an invalid email unless
        # the user hand-edits the URLs.
        if raw_emails:
            for email in raw_emails.split(","):
                try:
                    validators.validate_email(email)
                    emails.append(email)
                except ValidationError:
                    pass

    return render(
        request,
        "zerver/find_account.html",
        context={
            "form": form,
            "current_url": lambda: url,
            "emails": emails
        },
    )
예제 #53
0
def valid_email(value):
    try:
        validate_email(value)
        return True
    except ValidationError:
        return False
예제 #54
0
def validate_view_processor(request, e_name):
    # For easy testing try the following
    # return {"which_version": "no email"}
    # return {"which_version": "no experiment"}
    # return {"which_version": "already participated"}
    # return {"which_version": "couldn't send email"}
    # return {"which_version": "validate"}

    # Get the experiment data
    exp = None
    try:
        exp = Experiment.objects.get(url_name=e_name)
    except:
        return {"which_version": "no experiment", "e_name": e_name, "pretty_name": exp.pretty_name.lower()}

    try:
        validate_email(request.POST.get("email"))
    except ValidationError:
        return {"which_version": "no email", "e_name": e_name, "pretty_name": exp.pretty_name.lower()}

    user_email = request.POST.get("email")
    permission = request.POST.get("permission_to_contact")
    permission = permission == "on"

    # Set session
    request.session['email'] = user_email
    request.session['submitted'] = False

    # Create variable we'll contain the user information in
    user = None
    # Make sure there's not already a user before creating one
    try:
        user = User.objects.get(email=user_email)
        # There is a user. Check to see if the permission
        # needs changing.
    except: # There was no user, so create one
        user = User(email=user_email)
        user.save()

    if(permission != user.permission_to_contact):
        user.permission_to_contact = permission
        user.save()

    # Create the participant id number
    pid = create_participant_id(user, e_name, permission)

    # Get the institution for the participant
    institute = user_email.split("@")[1]

    # Check to see if they're already in the database and whether
    # or not they can participate again
    subject=None
    try:
        subject = Participant.objects.get(participant=pid, experiment=exp.id)
    except:
        # Create an access code for the participant
        a_code = create_participant_access_code(pid, e_name, permission)
        subject = Participant(participant=pid,
                            experiment=exp,
                            institution=institute,
                            access_code=a_code,
                            participation_time=0,
                            time_last_participated=timezone.now(),)
        subject.save()

    if((subject.participation_time == 0) or (exp.repeat == "t")):
        if(subject.participation_time > 0): #They've already participated
            #Check that they've waited enough time
            time_to_participate = None
            if exp.repeat_delay_units=="hours":
                time_to_participate = subject.time_last_participated + datetime.timedelta(hours=exp.repeat_delay)
            elif exp.repeat_delay_units=="days":
                time_to_participate = subject.time_last_participated + datetime.timedelta(days=exp.repeat_delay)
            elif exp.repeat_delay_units=="months":
                time_to_participate = subject.time_last_participated + datetime.timedelta(days=exp.repeat_delay*30)
            else: #Years
                time_to_participate = subject.time_last_participated + datetime.timedelta(days=exp.repeat_delay*365)
            if time_to_participate > timezone.now():
                time_string = time_to_participate.strftime("%I:%M %p, %B %d, %Y")
                return {"which_version": "have to wait", "e_name": e_name, "pretty_name": exp.pretty_name.lower(),
                        "time_to_participate": time_string}
            elif subject.access_code == 'ZZZZZZZZZZ': #They can participate, but they'll need a new access code
                a_code = create_participant_access_code(pid, e_name, permission)
                subject.access_code = a_code
                subject.save()
    else:
        return {"which_version": "already participated", "e_name": e_name, "pretty_name": exp.pretty_name.lower()}

    # send an email informing participants containing the access_code
    send_access_code_email(user, subject, exp)

    return {"which_version": "validate", "e_name": e_name, "pretty_name": exp.pretty_name.lower()}
예제 #55
0
def _signup(request, eamap, retfun=None):
    """
    Present form to complete for signup via external authentication.
    Even though the user has external credentials, he/she still needs
    to create an account on the edX system, and fill in the user
    registration form.

    eamap is an ExternalAuthMap object, specifying the external user
    for which to complete the signup.

    retfun is a function to execute for the return value, if immediate
    signup is used.  That allows @ssl_login_shortcut() to work.
    """
    # save this for use by student.views.create_account
    request.session['ExternalAuthMap'] = eamap

    if settings.FEATURES.get('AUTH_USE_CERTIFICATES_IMMEDIATE_SIGNUP', ''):
        # do signin immediately, by calling create_account, instead of asking
        # student to fill in form.  MIT students already have information filed.
        username = eamap.external_email.split('@', 1)[0]
        username = username.replace('.', '_')
        post_vars = dict(username=username,
                         honor_code=u'true',
                         terms_of_service=u'true')
        log.info(u'doing immediate signup for %s, params=%s', username,
                 post_vars)
        student.views.create_account(request, post_vars)
        # should check return content for successful completion before
        if retfun is not None:
            return retfun()
        else:
            return redirect('/')

    # default conjoin name, no spaces, flattened to ascii b/c django can't handle unicode usernames, sadly
    # but this only affects username, not fullname
    username = re.sub(r'\s',
                      '',
                      _flatten_to_ascii(eamap.external_name),
                      flags=re.UNICODE)

    context = {
        'has_extauth_info': True,
        'show_signup_immediately': True,
        'extauth_domain': eamap.external_domain,
        'extauth_id': eamap.external_id,
        'extauth_email': eamap.external_email,
        'extauth_username': username,
        'extauth_name': eamap.external_name,
        'ask_for_tos': True,
    }

    # Some openEdX instances can't have terms of service for shib users, like
    # according to Stanford's Office of General Counsel
    uses_shibboleth = (
        settings.FEATURES.get('AUTH_USE_SHIB')
        and eamap.external_domain.startswith(SHIBBOLETH_DOMAIN_PREFIX))
    if uses_shibboleth and settings.FEATURES.get('SHIB_DISABLE_TOS'):
        context['ask_for_tos'] = False

    # detect if full name is blank and ask for it from user
    context['ask_for_fullname'] = eamap.external_name.strip() == ''

    # validate provided mail and if it's not valid ask the user
    try:
        validate_email(eamap.external_email)
        context['ask_for_email'] = False
    except ValidationError:
        context['ask_for_email'] = True

    log.info(u'EXTAUTH: Doing signup for %s', eamap.external_id)

    return student.views.register_user(request, extra_context=context)
예제 #56
0
    def clean_voucher_request_data(cls, request_data, partner):
        """
        Helper method to return cleaned request data for voucher creation or
        raise validation error with error code.

        Arguments:
            request (dict): request's data with voucher data
            partner (str): the request's site's partner

        """
        benefit_type = request_data.get('benefit_type')
        category_data = request_data.get('category')
        code = request_data.get('code')
        course_catalog_data = request_data.get('course_catalog')
        enterprise_customer_data = request_data.get('enterprise_customer')
        course_seat_types = request_data.get('course_seat_types')
        max_uses = request_data.get('max_uses')
        stock_record_ids = request_data.get('stock_record_ids')
        voucher_type = request_data.get('voucher_type')
        program_uuid = request_data.get('program_uuid')
        notify_email = request_data.get('notify_email')

        if benefit_type not in (
                Benefit.PERCENTAGE,
                Benefit.FIXED,
        ):
            raise ValidationError(
                'Benefit type [{type}] is not allowed'.format(
                    type=benefit_type))

        if code and Voucher.does_exist(code):
            validation_message = 'A coupon with code {code} already exists.'.format(
                code=code)
            raise ValidationError(validation_message)

        if course_seat_types:
            try:
                course_seat_types = prepare_course_seat_types(
                    course_seat_types)
            except (AttributeError, TypeError) as exception:
                validation_message = 'Invalid course seat types data: {}'.format(
                    six.text_type(exception))
                raise ValidationError(validation_message)

        try:
            category = Category.objects.get(name=category_data['name'])
        except Category.DoesNotExist:
            validation_message = 'Category "{category_name}" not found.'.format(
                category_name=category_data['name'])
            # FIXME 404 is the wrong response code to use here.
            raise ValidationError(validation_message,
                                  code=status.HTTP_404_NOT_FOUND)
        except (KeyError, TypeError):
            validation_message = 'Invalid Coupon Category data.'
            raise ValidationError(validation_message)

        try:
            course_catalog = course_catalog_data[
                'id'] if course_catalog_data else None
        except (KeyError, TypeError):
            validation_message = 'Unexpected catalog data format received for coupon.'
            raise ValidationError(validation_message)

        try:
            enterprise_customer = enterprise_customer_data[
                'id'] if enterprise_customer_data else None
            enterprise_customer_name = enterprise_customer_data.get(
                'name') if enterprise_customer_data else None
        except (KeyError, TypeError):
            validation_message = 'Unexpected EnterpriseCustomer data format received for coupon.'
            raise ValidationError(validation_message)

        if notify_email:
            try:
                validate_email(notify_email)
            except ValidationError:
                raise ValidationError(
                    'Notification email must be a valid email address.')

        coupon_catalog = cls.get_coupon_catalog(stock_record_ids, partner)

        return {
            'benefit_type':
            benefit_type,
            'benefit_value':
            request_data.get('benefit_value'),
            'coupon_catalog':
            coupon_catalog,
            'catalog_query':
            request_data.get('catalog_query'),
            'category':
            category,
            'code':
            code,
            'course_catalog':
            course_catalog,
            'course_seat_types':
            course_seat_types,
            'email_domains':
            request_data.get('email_domains'),
            'end_datetime':
            request_data.get('end_datetime'),
            'enterprise_customer':
            enterprise_customer,
            'enterprise_customer_name':
            enterprise_customer_name,
            'enterprise_customer_catalog':
            request_data.get('enterprise_customer_catalog'),
            'max_uses':
            max_uses,
            'note':
            request_data.get('note'),
            'partner':
            partner,
            'price':
            request_data.get('price'),
            'quantity':
            request_data.get('quantity'),
            'start_datetime':
            request_data.get('start_datetime'),
            'title':
            request_data.get('title'),
            'voucher_type':
            voucher_type,
            'program_uuid':
            program_uuid,
            'notify_email':
            notify_email,
            'contract_discount_type':
            request_data.get('contract_discount_type'),
            'contract_discount_value':
            request_data.get('contract_discount_value'),
            'prepaid_invoice_amount':
            request_data.get('prepaid_invoice_amount'),
        }
예제 #57
0
def validate_login_email(email: str) -> None:
    try:
        validate_email(email)
    except ValidationError as err:
        raise JsonableError(str(err.message))
예제 #58
0
    def parse_job(self):
        self.valid_email = False
        if self.bs.find(class_='c-list--def'):
            for email in self.bs.find(class_='c-list--def').find_all(
                    class_='c-list--def__val'):
                try:
                    validate_email(email.get_text().strip())
                    self.valid_email = email.get_text().strip()
                    break
                except Exception:
                    pass

        if self.valid_email == False:
            return None

        job = {}

        id = re.findall(
            '\d+',
            self.bs.find(class_='c-hero__etablissement__ref').get_text())

        job['job_id'] = id[0]

        print(job['job_id'])

        job['job_email'] = self.valid_email

        title = self.bs.find(
            class_='c-hero__etablissement__info__name u-typo-h5').get_text(
            ).strip().split(',')

        job['job_title'] = title[0]
        job['job_contrats_list'] = self._get_contrat(title[-1].strip())

        job['job_company'] = self.bs.find(
            class_=
            'c-hero__inner__infoplus__item c-hero__inner__infoplus__item--name'
        ).get_text().strip().split('(')[0].strip()

        bs_image = self.bs.find(class_='c-hero__etablissement__logo')
        if bs_image:
            job['job_url_image'] = "http://jobs-stages.letudiant.fr" + bs_image.find(
                'img')['src']
        else:
            job['job_url_image'] = "https://xxxx.amazonaws.com/media/pro/default.jpg"

        job['job_description'] = ""

        for elem in self.bs.find(class_='s-editorial').find_all(['h5', 'p']):
            if elem.get_text().strip() == "Postuler":
                break
            job['job_description'] = job['job_description'] + elem.prettify()

        #job['job_contrats_list'] = self.parse_contract(job['job_description'])
        job['job_contrats_list'] = [3]

        job['job_study'] = self._get_study(
            self.parse_study(job['job_description']))
        job['job_experience'] = self._get_experience(
            self.parse_experience(job['job_description']))

        job['job_location'] = self.bs.find(
            class_=
            'c-hero__inner__infoplus__item c-hero__inner__infoplus__item--localisation'
        ).get_text().strip()

        if self.bs.find(class_='c-list--def').find_all(
                class_='c-list--def__name')[-1].get_text().strip(
                ) == "Contact :":
            job['job_contact'] = self.bs.find(class_='c-list--def').find_all(
                class_='c-list--def__val')[-1].get_text().strip()

        job['job_scraper_site'] = "letudiant"
        job['job_scraper_url'] = self.url_job

        self.data['job'] = job
예제 #59
0
 def clean_email(self, valor):
     try:
         validate_email(valor)
     except forms.ValidationError:
         self.add_error('valor', 'No es un email válido')
예제 #60
0
def signupuser(request):
    if request.user.is_authenticated:
        return redirect('todowoo:currenttodos')
    if request.method == 'GET':
        return render(request, 'todowoo/signupuser.html',
                      {'form': UserCreationForm()})
    else:
        username = request.POST['username'].strip()
        emailId = request.POST['emailid'].strip()
        password1 = request.POST['password1'].strip()
        password2 = request.POST['password2'].strip()

        #checking the username validation
        if username == "":
            return render(request, 'todowoo/signupuser.html', {
                'form': UserCreationForm(),
                'error': "User name can't be blank!"
            })

        #checking the email validation
        if emailId == "":
            return render(request, 'todowoo/signupuser.html', {
                'form': UserCreationForm(),
                'error': "Email id can't be blank!"
            })
        try:
            user = User.objects.get(email=emailId)
            return render(
                request, 'todowoo/signupuser.html', {
                    'form': UserCreationForm(),
                    'error': 'This id is already registered, please try login!'
                })
        except:
            try:
                validate_email(emailId)
            except:
                return render(
                    request, 'todowoo/signupuser.html', {
                        'form': UserCreationForm(),
                        'error': 'Email format is not correct!'
                    })

        #checking the password validation
        if request.POST['password1'] == request.POST['password2']:
            try:
                a = validate_password(password=password1, user=username)
                print(a)
            except:
                return render(
                    request, 'todowoo/signupuser.html', {
                        'form':
                        UserCreationForm(),
                        'error':
                        'Password should meet the policy creteria!<ul><li>Your password can’t be too similar to your other personal information.</li><li>Your password must contain at least 8 characters.</li><li>Your password can’t be a commonly used password.</li><li>Your password can’t be entirely numeric.</li></ul>'
                    })
            #Create a new user
            try:
                user = User.objects.create_user(username,
                                                emailId,
                                                password=password1)
                user.save()
                login(request, user)
                return redirect('todowoo:currenttodos')
            except IntegrityError:
                return render(
                    request, 'todowoo/signupuser.html', {
                        'form':
                        UserCreationForm(),
                        'error':
                        'User name is not available, please try with another user name'
                    })
        else:
            return render(request, 'todowoo/signupuser.html', {
                'form': UserCreationForm(),
                'error': 'Passwords did not match'
            })