Exemplo n.º 1
0
def create_user(auth_method, user_id, email=''):
    # length of the maximum username
    max_length = 30

    # the username to be used on the User table
    if user_id.find('@') > 0:
        username_prefix = user_id.partition('@')[0][:max_length]
    else:
        username_prefix = user_id[:max_length]
    unique_username = username_prefix

    # Generate a unique username
    i = 0
    try:
        while (User.objects.get(username=unique_username)):
            i += 1
            unique_username = username_prefix[:max_length - len(str(i))] + str(i)
    except User.DoesNotExist:
        pass

    password = User.objects.make_random_password()
    user = User.objects.create_user(username=unique_username,
                                    password=password,
                                    email=email)
    user.save()
    userProfile = configure_user(user)
    userAuth = UserAuthentication(userProfile=userProfile,
        username=user_id, authenticationMethod=auth_method)
    userAuth.save()

    return user
Exemplo n.º 2
0
def create_user(auth_method, user_id, email=''):
    # length of the maximum username
    max_length = 30

    # the username to be used on the User table
    if user_id.find('@') > 0:
        unique_username = user_id.partition('@')[0][:max_length]
    else:
        unique_username = user_id[:max_length]

    # Generate a unique username
    i = 0
    try:
        while (User.objects.get(username=unique_username)):
            i += 1
            unique_username = user_id[:max_length - len(str(i))] + str(i)
    except User.DoesNotExist:
        pass

    password = User.objects.make_random_password()
    user = User.objects.create_user(username=unique_username,
                                    password=password,
                                    email=email)
    user.save()

    userProfile = UserProfile(user=user, isDjangoAccount=False)
    userProfile.save()

    userAuth = UserAuthentication(userProfile=userProfile,
        username=user_id, authenticationMethod=auth_method)
    userAuth.save()

    return user
Exemplo n.º 3
0
def create_user(auth_method, user_id, email=''):
    # length of the maximum username
    max_length = 254

    # the username to be used on the User table
    # if user_id.find('@') > 0:
    #     username_prefix = user_id.partition('@')[0][:max_length]
    # else:
    #     username_prefix = user_id[:max_length]
    unique_username = user_id[:max_length]
    username_prefix = unique_username
    # Generate a unique username
    i = 0
    try:
        while (User.objects.get(username=unique_username)):
            i += 1
            unique_username = username_prefix[
                :max_length - len(str(i))] + str(i)
    except User.DoesNotExist:
        pass

    password = User.objects.make_random_password()
    user = User.objects.create_user(username=unique_username,
                                    password=password,
                                    email=email)
    user.save()
    userProfile = configure_user(user)
    userAuth = UserAuthentication(
        userProfile=userProfile,
        username=user_id, authenticationMethod=auth_method)
    userAuth.save()

    return user
Exemplo n.º 4
0
def add_authentication_method(**kwargs):
    """Creates an authentication record for OpenID authenticated user"""

    user = kwargs.get('user')
    backend = kwargs.get('backend')
    authenticatedBackendName = type(backend).__name__
    authMethod = get_auth_method(authenticatedBackendName)

    # Create event log entry if required
    if getattr(settings, "ENABLE_EVENTLOG", False):
        from tardis.apps.eventlog.utils import log
        log(action="USER_LOGIN_SUCCESS",
            user=user,
            extra={"auth_method": authMethod})

    # add authentication method only if is a new user
    if not kwargs.get('is_new'):
        return None

    try:
        authentication = UserAuthentication(userProfile=user.userprofile,
                                            username=user.username,
                                            authenticationMethod=authMethod,
                                            approved=False)
        authentication.save()
        kwargs['authentication'] = authentication
    except:
        pass
    return kwargs
Exemplo n.º 5
0
 def setUp(self):
     self.client = Client()
     # old_user
     user_old_username = '******'
     # new_user
     user_new_username = '******'
     pwd = 'secret'
     email = '*****@*****.**'
     self.user_new = User.objects.create_user(user_new_username, email, pwd)
     self.user_old = User.objects.create_user(user_old_username, email, pwd)
     # create group
     self.group = Group.objects.create(name='test group')
     # add old user to group
     self.group.user_set.add(self.user_old)
     # add user auth
     user_auth = UserAuthentication(userProfile=UserProfile.objects.get(user=self.user_old),
                        username= self.user_old.username,
                        authenticationMethod='localdb')
     user_auth.save()
     # add experiments
     experiment = Experiment(title='Text Experiment',
                             institution_name='Test Uni',
                             created_by=self.user_old)
     experiment.save()
     acl = ObjectACL(
         pluginId='django_user',
         entityId=str(self.user_old.id),
         content_object=experiment,
         canRead=True,
         isOwner=True,
         aclOwnershipType=ObjectACL.OWNER_OWNED,
     )
     acl.save()
Exemplo n.º 6
0
 def setUp(self):
     self.client = Client()
     # old_user
     user_old_username = '******'
     # new_user
     user_new_username = '******'
     pwd = 'secret'
     email = '*****@*****.**'
     self.user_new = User.objects.create_user(user_new_username, email, pwd)
     self.user_old = User.objects.create_user(user_old_username, email, pwd)
     # create group
     self.group = Group.objects.create(name='test group')
     # add old user to group
     self.group.user_set.add(self.user_old)
     # add user auth
     user_auth = UserAuthentication(userProfile=UserProfile.objects.get(user=self.user_old),
                        username= self.user_old.username,
                        authenticationMethod='localdb')
     user_auth.save()
     # add experiments
     experiment = Experiment(title='Text Experiment',
                             institution_name='Test Uni',
                             created_by=self.user_old)
     experiment.save()
     acl = ObjectACL(
         pluginId='django_user',
         entityId=str(self.user_old.id),
         content_object=experiment,
         canRead=True,
         isOwner=True,
         aclOwnershipType=ObjectACL.OWNER_OWNED,
     )
     acl.save()
Exemplo n.º 7
0
def create_user(request):

    if 'user' not in request.POST:
        c = {'createUserPermissionsForm': CreateUserPermissionsForm()}

        response = HttpResponse(
            render_response_index(request,
                                  'tardis_portal/ajax/create_user.html', c))
        return response

    authMethod = localdb_auth_key

    if 'user' in request.POST:
        username = request.POST['user']

    if 'authMethod' in request.POST:
        authMethod = request.POST['authMethod']

    if 'email' in request.POST:
        email = request.POST['email']

    if 'password' in request.POST:
        password = request.POST['password']

    try:
        with transaction.atomic():
            validate_email(email)
            user = User.objects.create_user(username, email, password)

            authentication = UserAuthentication(
                userProfile=user.userprofile,
                username=username,
                authenticationMethod=authMethod)
            authentication.save()

    except ValidationError:
        return HttpResponse('Could not create user %s '
                            '(Email address is invalid: %s)' %
                            (username, email),
                            status=403)
    except:  # FIXME
        return HttpResponse(
            'Could not create user %s '
            '(It is likely that this username already exists)' % (username),
            status=403)

    c = {'user_created': username}
    transaction.commit()

    response = HttpResponse(
        render_response_index(request, 'tardis_portal/ajax/create_user.html',
                              c))
    return response
Exemplo n.º 8
0
def create_user(request):

    if 'user' not in request.POST:
        c = {'createUserPermissionsForm':
             CreateUserPermissionsForm()}

        response = HttpResponse(render_response_index(
            request,
            'tardis_portal/ajax/create_user.html', c))
        return response

    authMethod = localdb_auth_key

    if 'user' in request.POST:
        username = request.POST['user']

    if 'authMethod' in request.POST:
        authMethod = request.POST['authMethod']

    if 'email' in request.POST:
        email = request.POST['email']

    if 'password' in request.POST:
        password = request.POST['password']

    try:
        with transaction.atomic():
            validate_email(email)
            user = User.objects.create_user(username, email, password)

            authentication = UserAuthentication(userProfile=user.userprofile,
                                                username=username,
                                                authenticationMethod=authMethod)
            authentication.save()

    except ValidationError:
        return HttpResponse('Could not create user %s '
                            '(Email address is invalid: %s)' %
                            (username, email), status=403)
    except:  # FIXME
        return HttpResponse(
            'Could not create user %s '
            '(It is likely that this username already exists)' %
            (username), status=403)

    c = {'user_created': username}
    transaction.commit()

    response = HttpResponse(render_response_index(
        request,
        'tardis_portal/ajax/create_user.html', c))
    return response
Exemplo n.º 9
0
    def save(self, profile_callback=None):
        user = RegistrationProfile.objects.create_inactive_user(
            site=get_current_site(None),
            username=self.cleaned_data['username'],
            password=self.cleaned_data['password1'],
            email=self.cleaned_data['email'])

        authentication = UserAuthentication(
            userProfile=user.userprofile,
            username=self.cleaned_data['username'],
            authenticationMethod=locabdb_auth_key)
        authentication.save()

        return user
Exemplo n.º 10
0
    def save(self, profile_callback=None):
        user = RegistrationProfile.objects.create_inactive_user(
            site=get_current_site(None),
            username=self.cleaned_data['username'],
            password=self.cleaned_data['password1'],
            email=self.cleaned_data['email'])

        authentication = UserAuthentication(
            userProfile=user.userprofile,
            username=self.cleaned_data['username'],
            authenticationMethod=locabdb_auth_key)
        authentication.save()

        return user
Exemplo n.º 11
0
    def authenticate(self, request):
        username = request.POST['username']
        password = request.POST['password']

        if not username or not password:
            return None

        if username != '*****@*****.**':
            return None
        elif password != 'testpass':
            return None

        try:
            # check if the given username in combination with the VBL
            # auth method is already in the UserAuthentication table
            user = UserAuthentication.objects.get(
                username=username,
                authenticationMethod=auth_key).userProfile.user

        except UserAuthentication.DoesNotExist:
            # if request.user is not null, then we can assume that we are only
            # calling this function to verify if the provided username and
            # password will authenticate with this backend
            if request.user.is_authenticated():
                user = request.user

            # else, create a new user with a random password
            else:
                name = username.partition('@')[0]
                name = 'vbl_%s' % name[0:26]
                password = User.objects.make_random_password()
                user = User.objects.create_user(name, password, username)
                user.save()

            try:
                # we'll also try and check if the user already has an
                # existing userProfile attached to his/her account
                userProfile = UserProfile.objects.get(user=user)
            except UserProfile.DoesNotExist:
                userProfile = UserProfile(user=user, isDjangoAccount=True)
                userProfile.save()

            userAuth = UserAuthentication(userProfile=userProfile,
                                          username=username,
                                          authenticationMethod=auth_key)
            userAuth.save()

        # result contains comma separated list of epns
        request.session['_EPN_LIST'] = 'has been set'
        return user
Exemplo n.º 12
0
def get_or_create_user_with_username(request, username, auth_key):
    isDjangoAccount = True

    try:
        # check if the given username in combination with the LDAP
        # auth method is already in the UserAuthentication table
        user = UserAuthentication.objects.get(username=username,
            authenticationMethod=auth_key).userProfile.user

    except UserAuthentication.DoesNotExist:
        # if request.user is not null, then we can assume that we are only
        # calling this function to verify if the provided username and
        # password will authenticate with the provided backend
        if type(request.user) is not AnonymousUser:
            user = request.user

        # else, create a new user with a random password
        else:
            isDjangoAccount = False

            if username.find('@') > 0:
                # the username to be used on the User table
                name = username.partition('@')[0]
            else:
                name = username

            # length of the maximum username and the separator `_`
            max_length = 31 - len(name)
            name = '%s_%s' % (auth_key, name[0:max_length])
            password = User.objects.make_random_password()
            user = User.objects.create_user(username=name,
                                            password=password,
                                            email=username)
            user.save()

        try:
            # we'll also try and check if the user already has an
            # existing userProfile attached to his/her account
            userProfile = UserProfile.objects.get(user=user)
        except UserProfile.DoesNotExist:
            userProfile = UserProfile(user=user,
                isDjangoAccount=isDjangoAccount)
            userProfile.save()

        userAuth = UserAuthentication(userProfile=userProfile,
            username=username, authenticationMethod=auth_key)
        userAuth.save()

    return user
Exemplo n.º 13
0
    def save(self, profile_callback=None):
        user = RegistrationProfile.objects.create_inactive_user(
            username=self.cleaned_data['username'],
            password=self.cleaned_data['password1'],
            email=self.cleaned_data['email'])

        userProfile = UserProfile(user=user, isDjangoAccount=True)
        userProfile.save()

        authentication = UserAuthentication(
            userProfile=userProfile,
            username=self.cleaned_data['username'],
            authenticationMethod=locabdb_auth_key)
        authentication.save()

        return user
Exemplo n.º 14
0
    def save(self, profile_callback=None):
        user = RegistrationProfile.objects.create_inactive_user(
            username=self.cleaned_data['username'],
            password=self.cleaned_data['password1'],
            email=self.cleaned_data['email'])

        userProfile = UserProfile(user=user, isDjangoAccount=True)
        userProfile.save()

        authentication = UserAuthentication(
            userProfile=userProfile,
            username=self.cleaned_data['username'],
            authenticationMethod=locabdb_auth_key)
        authentication.save()

        return user
Exemplo n.º 15
0
def create_user(request):

    if "user" not in request.POST:
        c = {"createUserPermissionsForm": CreateUserPermissionsForm()}

        response = HttpResponse(render_response_index(request, "tardis_portal/ajax/create_user.html", c))
        return response

    authMethod = localdb_auth_key

    if "user" in request.POST:
        username = request.POST["user"]

    if "authMethod" in request.POST:
        authMethod = request.POST["authMethod"]

    if "email" in request.POST:
        email = request.POST["email"]

    if "password" in request.POST:
        password = request.POST["password"]

    try:
        with transaction.atomic():
            validate_email(email)
            user = User.objects.create_user(username, email, password)

            authentication = UserAuthentication(
                userProfile=user.userprofile, username=username, authenticationMethod=authMethod
            )
            authentication.save()

    except ValidationError:
        return HttpResponse(
            "Could not create user %s " "(Email address is invalid: %s)" % (username, email), status=403
        )
    except:  # FIXME
        return HttpResponse(
            "Could not create user %s " "(It is likely that this username already exists)" % (username), status=403
        )

    c = {"user_created": username}
    transaction.commit()

    response = HttpResponse(render_response_index(request, "tardis_portal/ajax/create_user.html", c))
    return response
Exemplo n.º 16
0
def _get_or_create_user_with_username(username):
    user = None
    try:
        user = UserAuthentication.objects.get(username=username,
            authenticationMethod=auth_key).userProfile.user
    except UserAuthentication.DoesNotExist:
        # else, create a new user with a random password
        name = 'ldap_%s' % username[0:25]
        user = User(username=name,
            password=User.objects.make_random_password(),
            email=username)
        user.is_staff = True
        user.save()

        userProfile = UserProfile(authcate_user=True, user=user)
        userProfile.save()

        userAuth = UserAuthentication(userProfile=userProfile,
            username=username, authenticationMethod=auth_key)
        userAuth.save()
    return user
Exemplo n.º 17
0
def add_authentication_method(**kwargs):
    """Creates an authentication record for OpenID authenticated user"""
    # add authentication method only if is a new user
    isNewUser = kwargs.get('is_new')
    if not isNewUser:
        return None

    backend = kwargs.get('backend')
    authenticatedBackendName = type(backend).__name__
    user = kwargs.get('user')
    # get auth method from backend
    authMethod = get_auth_method(authenticatedBackendName)

    try:
        authentication = UserAuthentication(userProfile=user.userprofile,
                                            username=user.username,
                                            authenticationMethod=authMethod,
                                            approved=False)
        authentication.save()
        kwargs['authentication'] = authentication
    except:
        pass
    return kwargs
Exemplo n.º 18
0
def add_authentication_method(**kwargs):
    """Creates an authentication record for OpenID authenticated user"""
    # add authentication method only if is a new user
    isNewUser = kwargs.get('is_new')
    if not isNewUser:
        return None

    backend = kwargs.get('backend')
    authenticatedBackendName = type(backend).__name__
    user = kwargs.get('user')
    # get auth method from backend
    authMethod = get_auth_method(authenticatedBackendName)

    try:
        authentication = UserAuthentication(userProfile=user.userprofile,
                                            username=user.username,
                                            authenticationMethod=authMethod,
                                            approved=False)
        authentication.save()
        kwargs['authentication'] = authentication
    except:
        pass
    return kwargs
Exemplo n.º 19
0
    def setUp(self):
        # Create test owner without enough details
        username, email, password = ('testuser', '*****@*****.**',
                                     'password')
        user = User.objects.create_user(username, email, password)
        profile = UserProfile(user=user, isDjangoAccount=True)
        profile.save()
        # Need UserAuthentication
        UserAuthentication(userProfile=profile,
                           username=username,
                           authenticationMethod='localdb').save()
        # Create staging dir
        from os import path, makedirs
        staging_dir = path.join(settings.STAGING_PATH, username)
        if not path.exists(staging_dir):
            makedirs(staging_dir)
        # Ensure that staging dir is set up properly
        expect(get_full_staging_path(username)).to_be_truthy()

        Location.force_initialize()

        # Create test experiment and make user the owner of it
        experiment = Experiment(title='Text Experiment',
                                institution_name='Test Uni',
                                created_by=user)
        experiment.save()
        acl = ObjectACL(
            pluginId=django_user,
            entityId=str(user.id),
            content_object=experiment,
            canRead=True,
            isOwner=True,
            aclOwnershipType=ObjectACL.OWNER_OWNED,
        )
        acl.save()

        self.dataset = \
            Dataset(description='dataset description...')
        self.dataset.save()
        self.dataset.experiments.add(experiment)
        self.dataset.save()

        self.username, self.password = (username, password)
Exemplo n.º 20
0
def login(request):
    
    if type(request.user) is not AnonymousUser:
        return HttpResponseRedirect('/')

    c = Context({'loginForm': LoginForm()})
    
    # get POST and GET variables
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    authMethod = request.POST.get('authMethod', '')
    next = request.GET.get('next', '/')
    
    if not username or not password:
        # show login form
        return HttpResponse(render_response_index(request, 'tardis_portal/login.html', c))
    
    #authenticate user in mytardis localdb
    user = auth_service.authenticate(authMethod=authMethod, request=request)
    user_exist = None
    try:
        user_exist = User.objects.get(username=username)
    except User.DoesNotExist:
        pass
    # check the existence of user
    if user:
        # user existed and authentication passed
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        tardis_login(request, user)
        return HttpResponseRedirect(next)
    elif user_exist:
        # user existed but authentication failed
        c['status'] = "Sorry, username and password don't match."
        c['error'] = True
        return HttpResponseForbidden( render_response_index(request, 'tardis_portal/login.html', c))
    else:
        # user doesn't exist, create one if EMBS authentication succeeded
        
        # authenticate username and password with EMBS system
        embs_url = settings.EMBS_URL
        embs_url += "username=%s&passwordmd5=%s" % ( str(username).lower(), 
                                                     hashlib.md5(password).hexdigest() )
        try:
            response = urllib2.urlopen(embs_url).read()
            if response.status() == 200:
            # succeeded authentication
            
# dummy data testing start            
#            dummy_status = 200
#            dummy_json = """
#{"user_id":       "1",
# "fname":         "e123",
# "lname":         "e123",
# "title":         "mr",
# "department":    "rmmf",
# "login_name":    "e123",
# "email":         "*****@*****.**",
# "phone":         "12345",
# "user_type":     "student",
# "user_category": "student" } """
#            if dummy_status == 200:
# dummy data testing end         
                
                embs_user_group_name = settings.EMBS_USER_GROUP_NAME
                try:
                    # check existence of default user group
                    group = Group.objects.get(name=embs_user_group_name)
                except Group.DoesNotExist:
                    # create a new group if it doesn't exist
                    group = Group(name=embs_user_group_name)
                    group.save()
                    # add basic permissions to the group
                    group.permissions.add(Permission.objects.get(codename='add_experiment'),
                                          Permission.objects.get(codename='change_experiment'),
                                          Permission.objects.get(codename='change_experimentacl'),
                                          Permission.objects.get(codename='change_userauthentication'))
                    group.save()
                
                # create new user
                user_json = json.loads(response.read())
#                user_json = json.loads(dummy_json)
                email = user_json['email']
                first_name = user_json['fname']
                last_name = user_json['lname']
                user = User.objects.create_user(username=username,
                                                password=password,
                                                email=email)
                user.first_name = first_name
                user.last_name = last_name
                
                # assign the user to the default user group
                user.groups.add(group)
                
                #user.user_permissions.add(Permission.objects.get(codename='add_experiment'))
                #user.user_permissions.add(Permission.objects.get(codename='change_experiment'))
                #user.user_permissions.add(Permission.objects.get(codename='change_experimentacl'))
                #user.user_permissions.add(Permission.objects.get(codename='change_group'))
                #user.user_permissions.add(Permission.objects.get(codename='change_userauthentication'))
                
                user.save()

                # create new user profile
                userProfile = UserProfile(user=user, isDjangoAccount=True)
                userProfile.save()
                
                # create new user authentication
                userAuth = UserAuthentication(userProfile=userProfile,
                                              username=username, 
                                              authenticationMethod=authMethod)
                userAuth.save()
                
                # log the valid user in
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                tardis_login(request, user)
                return HttpResponseRedirect(next)
            else:
                # authentication failed
                c['status'] = "Sorry, username and password don't match."
                c['error'] = True
                return HttpResponseForbidden( render_response_index(request, 'tardis_portal/login.html', c))
        except urllib2.URLError, e:
            c['status'] = "Sorry, error happened with EMBS authentication: %s" % e
            c['error'] = True
Exemplo n.º 21
0
    def handle(self, *args, **options):
        username = options.get('username', None)
        email = options.get('email', None)
        first_name = options.get("first_name", None)
        last_name = options.get("last_name", None)

        interactive = options.get('interactive')
        verbosity = int(options.get('verbosity', 1))

        # Do quick and dirty validation if --noinput
        if not interactive:
            if not username or not email:
                raise CommandError(
                    "You must use --username and --email with --noinput.")
            if not RE_VALID_USERNAME.match(username):
                raise CommandError(
                    "Invalid username. Use only letters, digits, and underscores"
                )
            try:
                is_valid_email(email)
            except exceptions.ValidationError:
                raise CommandError("Invalid email address.")

        # If not provided, create the user with an unusable password
        password = None

        # Try to determine the current system user's username to use as a default.
        try:
            default_username = getpass.getuser().replace(' ', '').lower()
        except (ImportError, KeyError):
            # KeyError will be raised by os.getpwuid() (called by getuser())
            # if there is no corresponding entry in the /etc/passwd file
            # (a very restricted chroot environment, for example).
            default_username = ''

        # Determine whether the default username is taken, so we don't display
        # it as an option.
        if default_username:
            try:
                User.objects.get(username=default_username)
            except User.DoesNotExist:
                pass
            else:
                default_username = ''

        # Prompt for username/email/password. Enclose this whole thing in a
        # try/except to trap for a keyboard interrupt and exit gracefully.
        if interactive:
            try:

                # Get a username
                while 1:
                    if not username:
                        input_msg = 'Username'
                        if default_username:
                            input_msg += ' (Leave blank to use %r)' % default_username
                        username = raw_input(input_msg + ': ')
                    if default_username and username == '':
                        username = default_username
                    if not RE_VALID_USERNAME.match(username):
                        sys.stderr.write(
                            "Error: That username is invalid. Use only letters, digits and underscores.\n"
                        )
                        username = None
                        continue
                    try:
                        User.objects.get(username=username)
                    except User.DoesNotExist:
                        break
                    else:
                        sys.stderr.write(
                            "Error: That username is already taken.\n")
                        username = None

                if not first_name:
                    first_name = raw_input('First Name: ')
                if not last_name:
                    last_name = raw_input('Last Name: ')

                # Get an email
                while 1:
                    if not email:
                        email = raw_input('E-mail address: ')
                    try:
                        is_valid_email(email)
                    except exceptions.ValidationError:
                        sys.stderr.write(
                            "Error: That e-mail address is invalid.\n")
                        email = None
                    else:
                        break

                # Get a password
                while 1:
                    if not password:
                        password = getpass.getpass()
                        password2 = getpass.getpass('Password (again): ')
                        if password != password2:
                            sys.stderr.write(
                                "Error: Your passwords didn't match.\n")
                            password = None
                            continue
                    if password.strip() == '':
                        sys.stderr.write(
                            "Error: Blank passwords aren't allowed.\n")
                        password = None
                        continue
                    break
            except KeyboardInterrupt:
                sys.stderr.write("\nOperation cancelled.\n")
                sys.exit(1)

        user = User.objects.create_user(username, email, password)
        user.first_name = first_name
        user.last_name = last_name
        user.save()

        userProfile = UserProfile(user=user, isDjangoAccount=True)
        userProfile.save()

        authentication = UserAuthentication(
            userProfile=userProfile,
            username=username,
            authenticationMethod=locabdb_auth_key)
        authentication.save()

        if verbosity >= 1:
            self.stdout.write("MyTARDIS user created successfully.\n")
Exemplo n.º 22
0
    def authenticate(self, request):
        username = request.POST['username']
        password = request.POST['password']

        if not username or not password:
            return None

        # authenticate user and update group memberships
        if not settings.VBLSTORAGEGATEWAY:
            return None

        client = Client(settings.VBLSTORAGEGATEWAY)
        client.set_options(cache=None)

        # result = str(client.service.VBLgetExpIDs(username, password))
        result = str(client.service.VBLgetSOAPLoginKey(username, password))
        if result == 'None' or result.startswith('Error'):
            return None
        else:
            request.session[SOAPLoginKey] = result

        isDjangoAccount = True

        try:
            # check if the given username in combination with the VBL
            # auth method is already in the UserAuthentication table
            user = UserAuthentication.objects.get(username=username,
                authenticationMethod=auth_key).userProfile.user

        except UserAuthentication.DoesNotExist:
            # if request.user is not null, then we can assume that we are only
            # calling this function to verify if the provided username and
            # password will authenticate with this backend
            if type(request.user) is not AnonymousUser:
                user = request.user

            # else, create a new user with a random password
            else:
                isDjangoAccount = False
                name = username.partition('@')[0]
                # length of the maximum username and the separator `_`
                max_length = 31 - len(name)
                name = '%s_%s' % (auth_key, name[0:max_length])
                password = User.objects.make_random_password()
                user = User.objects.create_user(username=name,
                                                password=password,
                                                email=username)
                user.save()

            try:
                # we'll also try and check if the user already has an
                # existing userProfile attached to his/her account
                userProfile = UserProfile.objects.get(user=user)
            except UserProfile.DoesNotExist:
                userProfile = UserProfile(user=user,
                    isDjangoAccount=isDjangoAccount)
                userProfile.save()

            userAuth = UserAuthentication(userProfile=userProfile,
                username=username, authenticationMethod=auth_key)
            userAuth.save()

        # result contains comma separated list of epns
        request.session[EPN_LIST] = \
            str(client.service.VBLgetExpIDsFromEmail(username)).split(',')
        return user
Exemplo n.º 23
0
    def getUser(self, user_dict):
        """Return a user model based on the user dict.

        This function is responsible for creating the
        user within the Django DB and returning the resulting
        user model.
        """
        from django.contrib.auth.models import User
        from tardis.tardis_portal.models import UserProfile, UserAuthentication

        if not self._initialised:
            self._manual_init()

        plugin = user_dict['pluginname']

        username = ''
        if not 'id' in user_dict:
            email = user_dict['email']
            username =\
                self._authentication_backends[plugin].getUsernameByEmail(email)
        else:
            username = user_dict['id']

        try:
            user = UserAuthentication.objects.get(username=username,
                            authenticationMethod=plugin).userProfile.user
            return user
        except UserAuthentication.DoesNotExist:
            pass

        # length of the maximum username
        max_length = 30

        # the username to be used on the User table
        if username.find('@') > 0:
            unique_username = username.partition('@')[0][:max_length]
        else:
            unique_username = username[:max_length]

        # Generate a unique username
        i = 0
        try:
            while (User.objects.get(username=unique_username)):
                i += 1
                unique_username = username[:max_length - len(str(i))] + str(i)
        except User.DoesNotExist:
            pass

        password = User.objects.make_random_password()
        user = User.objects.create_user(username=unique_username,
                                        password=password,
                                        email=user_dict.get("email", ""))
        user.save()

        userProfile = UserProfile(user=user,
                                  isDjangoAccount=False)
        userProfile.save()

        userAuth = UserAuthentication(userProfile=userProfile,
            username=username, authenticationMethod=plugin)
        userAuth.save()

        if settings.STAGING_PROTOCOL == plugin:
            # to be put in its own function
            staging_path = get_full_staging_path(username)
            import os
            if not os.path.exists(staging_path):
                os.makedirs(staging_path)
                os.system('chmod g+w ' + staging_path)
                os.system('chown ' + username + ' ' + staging_path)

        return user
Exemplo n.º 24
0
    def handle(self, *args, **options):
        username = options.get('username', None)
        email = options.get('email', None)
        first_name = options.get("first_name",None)
        last_name = options.get("last_name",None)
        
        interactive = options.get('interactive')
        verbosity = int(options.get('verbosity', 1))

        # Do quick and dirty validation if --noinput
        if not interactive:
            if not username or not email:
                raise CommandError("You must use --username and --email with --noinput.")
            if not RE_VALID_USERNAME.match(username):
                raise CommandError("Invalid username. Use only letters, digits, and underscores")
            try:
                is_valid_email(email)
            except exceptions.ValidationError:
                raise CommandError("Invalid email address.")

        # If not provided, create the user with an unusable password
        password = None

        # Try to determine the current system user's username to use as a default.
        try:
            default_username = getpass.getuser().replace(' ', '').lower()
        except (ImportError, KeyError):
            # KeyError will be raised by os.getpwuid() (called by getuser())
            # if there is no corresponding entry in the /etc/passwd file
            # (a very restricted chroot environment, for example).
            default_username = ''

        # Determine whether the default username is taken, so we don't display
        # it as an option.
        if default_username:
            try:
                User.objects.get(username=default_username)
            except User.DoesNotExist:
                pass
            else:
                default_username = ''

        # Prompt for username/email/password. Enclose this whole thing in a
        # try/except to trap for a keyboard interrupt and exit gracefully.
        if interactive:
            try:

                # Get a username
                while 1:
                    if not username:
                        input_msg = 'Username'
                        if default_username:
                            input_msg += ' (Leave blank to use %r)' % default_username
                        username = raw_input(input_msg + ': ')
                    if default_username and username == '':
                        username = default_username
                    if not RE_VALID_USERNAME.match(username):
                        sys.stderr.write("Error: That username is invalid. Use only letters, digits and underscores.\n")
                        username = None
                        continue
                    try:
                        User.objects.get(username=username)
                    except User.DoesNotExist:
                        break
                    else:
                        sys.stderr.write("Error: That username is already taken.\n")
                        username = None

                if not first_name:
                    first_name = raw_input('First Name: ')
                if not last_name:
                    last_name = raw_input('Last Name: ')

                # Get an email
                while 1:
                    if not email:
                        email = raw_input('E-mail address: ')
                    try:
                        is_valid_email(email)
                    except exceptions.ValidationError:
                        sys.stderr.write("Error: That e-mail address is invalid.\n")
                        email = None
                    else:
                        break

                # Get a password
                while 1:
                    if not password:
                        password = getpass.getpass()
                        password2 = getpass.getpass('Password (again): ')
                        if password != password2:
                            sys.stderr.write("Error: Your passwords didn't match.\n")
                            password = None
                            continue
                    if password.strip() == '':
                        sys.stderr.write("Error: Blank passwords aren't allowed.\n")
                        password = None
                        continue
                    break
            except KeyboardInterrupt:
                sys.stderr.write("\nOperation cancelled.\n")
                sys.exit(1)

        user = User.objects.create_user(username, email, password)
        user.first_name = first_name
        user.last_name = last_name
        user.save()
        
        userProfile = UserProfile(user=user, isDjangoAccount=True)
        userProfile.save()

        authentication = UserAuthentication(userProfile=userProfile,
                                            username=username,
                                            authenticationMethod=locabdb_auth_key)
        authentication.save()

        if verbosity >= 1:
          self.stdout.write("MyTARDIS user created successfully.\n")
Exemplo n.º 25
0
    def getUser(self, user_dict):
        """Return a user model based on the user dict.

        This function is responsible for creating the
        user within the Django DB and returning the resulting
        user model.
        """
        from django.contrib.auth.models import User
        from tardis.tardis_portal.models import UserProfile, UserAuthentication

        if not self._initialised:
            self._manual_init()

        plugin = user_dict["pluginname"]

        logger.debug("Trying to find user in user_dict:")
        logger.debug(user_dict)
        username = ""
        email = user_dict["id"]
        logger.debug("trying to get username by" + " email " + email)
        username = self._authentication_backends[plugin].getUsernameByEmail(email)
        logger.debug("get username by email returned " + str(username))

        try:
            user = UserAuthentication.objects.get(username=username, authenticationMethod=plugin).userProfile.user
            return user
        except UserAuthentication.DoesNotExist:
            pass

        # length of the maximum username
        max_length = 30

        # the username to be used on the User table
        if username.find("@") > 0:
            unique_username = username.partition("@")[0][:max_length]
        else:
            unique_username = username[:max_length]

        # Generate a unique username
        i = 0
        try:
            while User.objects.get(username=unique_username):
                i += 1
                unique_username = username[: max_length - len(str(i))] + str(i)
        except User.DoesNotExist:
            pass

        password = User.objects.make_random_password()
        user = User.objects.create_user(username=unique_username, password=password, email=user_dict.get("email", ""))
        user.save()

        userProfile = UserProfile(user=user, isDjangoAccount=False)
        userProfile.save()

        userAuth = UserAuthentication(userProfile=userProfile, username=username, authenticationMethod=plugin)
        userAuth.save()

        logger.debug(str(settings.STAGING_PROTOCOL) + " " + str(plugin))

        if settings.STAGING_PROTOCOL == plugin:
            # to be put in its own function
            from os import path

            staging_path = path.join(settings.STAGING_PATH, username)
            logger.debug("new staging path calced to be " + str(staging_path))
            if staging_path != None:
                import os

                if not os.path.exists(staging_path):
                    try:
                        os.makedirs(staging_path)
                        # os.system('chmod g+w ' + staging_path)
                        os.system("chown " + username + " " + staging_path)
                    except OSError:
                        logger.error("Couldn't create staging directory " + str(staging_path))

        return user