<commit_before>import datetime, random, sha
from django.db import models
from django.core.mail import send_mail
from django.template import Context, loader
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.conf import settings


class RegistrationManager(models.Manager):
    """
    Custom manager for the RegistrationProfile model,
    making it easier to manage profiles.
    
    """
    def create_inactive_user(self, username, password, email, send_email=True):
        """
        Creates a new User and a new RegistrationProfile
        for that User, generates an activation key, and mails
        it.

        Pass ``send_email=False`` to disable sending the email.
        
        """
        # Create the user.
        new_user = User.objects.create_user(username, email, password)
        new_user.is_active = False
        new_user.save()
        
        # Generate a salted SHA1 hash to use as a key.
        salt = sha.new(str(random.random())).hexdigest()[:5]
        activation_key = sha.new(salt+new_user.username).hexdigest()

        # Create the profile.
        new_profile = self.create(user=new_user,
                                  activation_key=activation_key)

        if send_email:
            # Send the activation email.
            current_domain = Site.objects.get_current().domain
            subject = "Activate your new account at %s" % current_domain
            message_template = loader.get_template('registration/activation_email.txt')
            message_context = Context({ 'site_url': 'http://%s/' % current_domain,
                                        'activation_key': activation_key,
                                        'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS })
            message = message_template.render(message_context)
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
        return new_user

    def activate_user(self, activation_key):
        """
        Given the activation key, makes a User's account active if
        the activation key is valid and has not expired.
        
        Returns the User if successful, or False if the account was
        not found or the key had expired.
        
        """
        try:
            user_profile = self.get(activation_key=activation_key)
        except self.model.DoesNotExist:
            return False
        if not user_profile.activation_key_expired():
            # Account exists and has a non-expired key. Activate it.
            user = user_profile.user
            user.is_active = True
            user.save()
            return user
        return False


class RegistrationProfile(models.Model):
    """<commit_msg>Avoid DB hits on obviously invalid activation keys<commit_after>import datetime, random, re, sha
from django.db import models
from django.core.mail import send_mail
from django.template import Context, loader
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.conf import settings


class RegistrationManager(models.Manager):
    """
    Custom manager for the RegistrationProfile model,
    making it easier to manage profiles.
    
    """
    def activate_user(self, activation_key):
        """
        Given the activation key, makes a User's account active if
        the activation key is valid and has not expired.
        
        Returns the User if successful, or False if the account was
        not found or the key had expired.
        
        """
        # Make sure the key we're trying conforms to the pattern of a
        # SHA1 hash; if it doesn't, no point even trying to look it up
        # in the DB.
        if re.match('[a-f0-9]{40}', activation_key):
            try:
                user_profile = self.get(activation_key=activation_key)
            except self.model.DoesNotExist:
                return False
            if not user_profile.activation_key_expired():
                # Account exists and has a non-expired key. Activate it.
                user = user_profile.user
                user.is_active = True
                user.save()
                return user
        return False

    def create_inactive_user(self, username, password, email, send_email=True):
        """
        Creates a new User and a new RegistrationProfile
        for that User, generates an activation key, and mails
        it.

        Pass ``send_email=False`` to disable sending the email.
        
        """
        # Create the user.
        new_user = User.objects.create_user(username, email, password)
        new_user.is_active = False
        new_user.save()
        
        # Generate a salted SHA1 hash to use as a key.
        salt = sha.new(str(random.random())).hexdigest()[:5]
        activation_key = sha.new(salt+new_user.username).hexdigest()

        # Create the profile.
        new_profile = self.create(user=new_user,
                                  activation_key=activation_key)

        if send_email:
            # Send the activation email.
            current_domain = Site.objects.get_current().domain
            subject = "Activate your new account at %s" % current_domain
            message_template = loader.get_template('registration/activation_email.txt')
            message_context = Context({ 'site_url': 'http://%s/' % current_domain,
                                        'activation_key': activation_key,
                                        'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS })
            message = message_template.render(message_context)
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
        return new_user


class RegistrationProfile(models.Model):
    """
{'fraction_non_alphanumeric': 0.07519834425664022, 'fraction_numerical': 0.001552259399793032, 'mean_word_length': 2.129519697787372, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5030755', 'n_tokens_mistral': 1496, 'n_tokens_neox': 1438, 'n_words': 457}