<s> import base64 <EOL> import hashlib <EOL> import os <EOL> import re <EOL> import sys <EOL> from django . contrib . auth . models import User <EOL> from django . db import IntegrityError <EOL> def _email_to_username ( email ) : <EOL> email = email . lower ( ) <EOL> converted = email . encode ( '<STR_LIT:utf8>' , '<STR_LIT:ignore>' ) <EOL> return base64 . urlsafe_b64encode ( hashlib . sha256 ( converted ) . digest ( ) ) [ : <NUM_LIT:30> ] <EOL> def get_user ( email , queryset = None ) : <EOL> """<STR_LIT>""" <EOL> if queryset is None : <EOL> queryset = User . objects <EOL> return queryset . get ( username = _email_to_username ( email ) ) <EOL> def user_exists ( email , queryset = None ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> get_user ( email , queryset ) <EOL> except User . DoesNotExist : <EOL> return False <EOL> return True <EOL> _DUPLICATE_USERNAME_ERRORS = ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' <EOL> ) <EOL> def create_user ( email , password = None , is_staff = None , is_active = None ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> user = User . objects . create_user ( email , email , password ) <EOL> except IntegrityError , err : <EOL> regexp = '<STR_LIT:|>' . join ( re . escape ( e ) for e in _DUPLICATE_USERNAME_ERRORS ) <EOL> if re . match ( regexp , err . message ) : <EOL> raise IntegrityError ( '<STR_LIT>' ) <EOL> raise <EOL> if is_active is not None or is_staff is not None : <EOL> if is_active is not None : <EOL> user . is_active = is_active <EOL> if is_staff is not None : <EOL> user . is_staff = is_staff <EOL> user . save ( ) <EOL> return user <EOL> def create_superuser ( email , password ) : <EOL> """<STR_LIT>""" <EOL> return User . objects . create_superuser ( email , email , password ) <EOL> def migrate_usernames ( stream = None , quiet = False ) : <EOL> """<STR_LIT>""" <EOL> stream = stream or ( quiet and open ( os . devnull , '<STR_LIT:w>' ) or sys . stdout ) <EOL> emails = set ( ) <EOL> errors = [ ] <EOL> for user in User . objects . all ( ) : <EOL> if not user . email : <EOL> errors . append ( "<STR_LIT>" <EOL> "<STR_LIT>" % ( user . _username , ) ) <EOL> elif user . email . lower ( ) in emails : <EOL> errors . append ( "<STR_LIT>" <EOL> "<STR_LIT>" % ( user . _username , user . email ) ) <EOL> else : <EOL> emails . add ( user . email . lower ( ) ) <EOL> if errors : <EOL> [ stream . write ( error + '<STR_LIT:\n>' ) for error in errors ] <EOL> raise Exception ( '<STR_LIT>' ) <EOL> total = User . objects . count ( ) <EOL> for user in User . objects . all ( ) : <EOL> user . username = _email_to_username ( user . email ) <EOL> user . save ( ) <EOL> stream . write ( "<STR_LIT>" <EOL> % ( total , ) ) </s>
