예제 #1
0
파일: auth.py 프로젝트: StochSS/stochss
    def get(self):
        """ Corresponds to /login """
        # Make sure user isn't logged in already
        if self.logged_in():
            return self.redirect("/")
        # Need to log in

        try:
            secret_key = self.request.GET['secret_key']
        except KeyError:
            secret_key = None
        
        if secret_key is not None:
            secret_key_attempt = SecretKey(key_string=secret_key)
            if secret_key_attempt.isEqualToAdminKey() and not User.admin_exists():
                return self.redirect('/register?secret_key={0}'.format(secret_key))
            elif secret_key_attempt.isEqualToAdminKey() and  User.admin_exists() and SingleMultiUserMode.is_single_user_mode():
                # Single user mode, login user and forward to / page
                user_subobj = self.auth.store.user_model.get_by_auth_id(User.get_admin_user_id())
                user = self.auth.store.user_to_dict(user_subobj)
                self.auth.set_session(user)
                return self.redirect('/')

        # Normal user login
        if SingleMultiUserMode.is_single_user_mode() or not User.admin_exists():
            self.render_response('login_disabled.html')
        else:
            self.render_response('login.html')
예제 #2
0
파일: auth.py 프로젝트: jesusrv1103/stochss
    def get(self):
        """ Corresponds to /login """
        # Make sure user isn't logged in already
        if self.logged_in():
            return self.redirect("/")
        # Need to log in

        try:
            secret_key = self.request.GET['secret_key']
        except KeyError:
            secret_key = None

        if secret_key is not None:
            secret_key_attempt = SecretKey(key_string=secret_key)
            if secret_key_attempt.isEqualToAdminKey(
            ) and not User.admin_exists():
                return self.redirect(
                    '/register?secret_key={0}'.format(secret_key))
            elif secret_key_attempt.isEqualToAdminKey() and User.admin_exists(
            ) and SingleMultiUserMode.is_single_user_mode():
                # Single user mode, login user and forward to / page
                user_subobj = self.auth.store.user_model.get_by_auth_id(
                    User.get_admin_user_id())
                user = self.auth.store.user_to_dict(user_subobj)
                self.auth.set_session(user)
                return self.redirect('/')

        # Normal user login
        if SingleMultiUserMode.is_single_user_mode(
        ) or not User.admin_exists():
            self.render_response('login_disabled.html')
        else:
            self.render_response('login.html')
예제 #3
0
    def extractStochKitJob(self, path, userId = None, handler = None, rename = None):
        jobj = json.loads(self.zipfb.read(path))
        path = os.path.abspath(os.path.dirname(__file__))
        
        zipPath = jobj["output_location"]

        if jobj["user_id"] not in [x.user_id() for x in User.query().fetch()]:
            jobj["user_id"] = handler.user.user_id()

        if userId:
            jobj["user_id"] = userId

        outPath = tempfile.mkdtemp(dir = "{0}/../output/".format(path))

        for name in self.zipfb.namelist():
            if re.search('^{0}/.*$'.format(zipPath), name):
                relname = os.path.relpath(name, zipPath)

                if not os.path.exists(os.path.dirname("{0}/{1}".format(outPath, relname))):
                    os.makedirs(os.path.dirname("{0}/{1}".format(outPath, relname)))

                fhandle = open("{0}/{1}".format(outPath, relname), 'w')
                fhandle.write(self.zipfb.read(name))
                fhandle.close()

        jobj["output_location"] = outPath
        jobj["stdout"] = "{0}/stdout".format(outPath)
        jobj["stderr"] = "{0}/stderr".format(outPath)
    
        return simulation.JobManager.createJob(handler, jobj, rename = rename)
예제 #4
0
    def get(self):
        """ Corresponds to /admin """
        users = User.query().fetch()
        if len(users) == 0:
            users = None
        pending_users_list = PendingUsersList.shared_list()

        # This is complicated. We need to get the Users that don't exist as User objects, but exist as approved users. These are the pre-approved users. The admin user must be specifically excluded
        active_users = set(
            filter(None, [
                str(u.email_address) if not u.is_admin_user() else None
                for u in users
            ]))
        approved_users = set(
            [str(u) for u in pending_users_list.approved_users])
        preapproved_users = approved_users - active_users

        context = {
            'admin_approval_required':
            pending_users_list.admin_approval_required,
            'email_verification_required':
            pending_users_list.email_verification_required,
            'email_setup': EmailConfig.is_enabled(),
            'active_users': users,
            'preapproved_users': preapproved_users,
            'users_waiting_approval': pending_users_list.users_waiting_approval
        }
        self.render_response('admin.html', **context)
예제 #5
0
파일: auth.py 프로젝트: bbbales2/stochss
 def check_if_user_exists(self, user_dict):
     """
     Check to see if the user has already logged in with another provider
     Currently only comparing email address.
     Returns the user object if it exists, otherwise None.
     """
     users = User.query(ndb.GenericProperty('email_address') == user_dict['email_address']).fetch()
     user = users[0] if users else None
     return user
예제 #6
0
    def extractStochOptimJob(self, path, userId = None, handler = None, rename = None):
        jsonJob = json.loads(self.zipfb.read(path))
        path = os.path.abspath(os.path.dirname(__file__))
        
        zipPath = jsonJob["outData"]


        job = stochoptim.StochOptimJobWrapper()

        jobNames = [x.jobName for x in db.Query(stochoptim.StochOptimJobWrapper).filter('userId =', handler.user.user_id()).run()]

        #print jobNames

        if jsonJob["jobName"] in jobNames:
            if rename:

                i = 1
                tryName = '{0}_{1}'.format(jsonJob["jobName"], i)

                while tryName in jobNames:
                    i = i + 1
                    tryName = '{0}_{1}'.format(jsonJob["jobName"], i)
                    
                jsonJob["jobName"] = tryName

        if jsonJob["userId"] not in [x.user_id() for x in User.query().fetch()]:
            jsonJob["userId"] = handler.user.user_id()

        if userId:
            jsonJob["userId"] = userId

        outPath = tempfile.mkdtemp(dir = "{0}/../output/".format(path))

        for name in self.zipfb.namelist():
            if re.search('^{0}/.*$'.format(zipPath), name):
                relname = os.path.relpath(name, zipPath)

                if not os.path.exists(os.path.dirname("{0}/{1}".format(outPath, relname))):
                    os.makedirs(os.path.dirname("{0}/{1}".format(outPath, relname)))

                fhandle = open("{0}/{1}".format(outPath, relname), 'w')
                fhandle.write(self.zipfb.read(name))
                fhandle.close()

        job.userId = jsonJob["userId"]
        job.jobName = jsonJob["jobName"]
        job.startTime = jsonJob["startTime"]
        job.modelName = jsonJob["modelName"] if "modelName" in jsonJob else None
        job.indata = json.dumps(jsonJob["indata"])
        job.nameToIndex = json.dumps(jsonJob["nameToIndex"])
        job.outData = outPath
        job.status = jsonJob["status"]

        job.put()

        return job.key().id()
예제 #7
0
파일: auth.py 프로젝트: bbbales2/stochss
 def should_create_admin(self):
     """
     Right now, just check to see if this is the first user being created.
     i.e. the first user to log in is the admin.
     """
     users = User.query().fetch(1)
     if users:
         return False
     else:
         return True
예제 #8
0
    def extractStochKitModel(self, path, userId = None, handler = None, rename = None):
        modelj = json.loads(self.zipfb.read(path))
        modelj["model"] = self.zipfb.read(modelj["model"])

        if modelj["user_id"] not in [x.user_id() for x in User.query().fetch()]:
            modelj["user_id"] = handler.user.user_id()

        if userId:
            modelj["user_id"] = userId
            
        return modeleditor.ModelManager.createModel(handler, modelj, rename = rename)
예제 #9
0
파일: auth.py 프로젝트: StochSS/stochss
    def post(self):
        '''
        Login attempt or request for account
        '''
        email_address = self.request.POST['email']
        try:
            request_account = self.request.POST['request_account']
        except KeyError:
            request_account = False
            
        # Login attempt, need to grab password too
        password = self.request.POST['password']
        try:
            user = self.auth.get_user_by_password(email_address, password, remember=True)
            # Success, put user in the session and redirect to home page

            # Has this user been approved? Or is the user the admin? Login either way
            pending_users_list = PendingUsersList.shared_list()

            userdb = User.get_by_id(user["user_id"])

            if hasattr(userdb, 'is_admin'):
                isAdmin = userdb.is_admin
            else:
                isAdmin = False

            if not isAdmin and pending_users_list.email_verification_required and not userdb.is_verified():
                context = {
                    'error_alert': True,
                    'alert_message': 'You need to verify your account before you can login.'
                    }
                return self.render_response('login.html', **context)

            if not isAdmin and pending_users_list.admin_approval_required and not pending_users_list.is_user_approved(email_address):
                # Not approved, add to approval waitlist
                pending_users_list.add_user_to_approval_waitlist(email_address)
                context = {
                    'error_alert': True,
                    'alert_message': 'You need to be approved by the admin before you can login.'
                    }
                return self.render_response('login.html', **context)

            # All Clear
            self.auth.set_session(user)
            return self.redirect('/')

        except (InvalidAuthIdError, InvalidPasswordError) as e:
            logging.info('Login failed for user: {0} with exception: {1}'.format(email_address, e))
            context = {
                'error_alert': True,
                'alert_message': 'The email or password you entered is incorrect.'
                }
            return self.render_response('login.html', **context)
예제 #10
0
파일: admin.py 프로젝트: bbbales2/stochss
    def get(self):
        """ Corresponds to /admin """
        users = User.query().fetch(projection=[ndb.GenericProperty('name'), ndb.GenericProperty('email_address')])
        if len(users) == 0:
            users = None
        pending_users_list = PendingUsersList.shared_list()

        context = {
            'active_users': users,
            'approved_users': pending_users_list.approved_users,
            'users_waiting_approval': pending_users_list.users_waiting_approval
        }
        self.render_response('admin.html', **context)
예제 #11
0
    def post(self):
        '''
        Login attempt or request for account
        '''
        email_address = self.request.POST['email']
        try:
            request_account = self.request.POST['request_account']
        except KeyError:
            request_account = False

        # Login attempt, need to grab password too
        password = self.request.POST['password']
        try:
            user = self.auth.get_user_by_password(email_address,
                                                  password,
                                                  remember=True)
            # Success, put user in the session and redirect to home page

            # Has this user been approved? Or is the user the admin? Login either way
            pending_users_list = PendingUsersList.shared_list()

            userdb = User.get_by_id(user["user_id"])

            if hasattr(userdb, 'is_admin'):
                isAdmin = userdb.is_admin
            else:
                isAdmin = False

            if pending_users_list.is_user_approved(email_address) or isAdmin:
                self.auth.set_session(user)
                return self.redirect('/')
            else:
                # Not approved, add to approval waitlist
                pending_users_list.add_user_to_approval_waitlist(email_address)
                context = {
                    'error_alert':
                    True,
                    'alert_message':
                    'You need to be approved by the admin before you can login.'
                }
                return self.render_response('login.html', **context)
        except (InvalidAuthIdError, InvalidPasswordError) as e:
            logging.info(
                'Login failed for user: {0} with exception: {1}'.format(
                    email_address, e))
            context = {
                'error_alert': True,
                'alert_message':
                'The email or password you entered is incorrect.'
            }
            return self.render_response('login.html', **context)
예제 #12
0
    def _delete_user(self, email):
        """ Delete existing user """
        user = User.get_by_auth_id(email)
        if user:
            if user.is_admin_user():
                return False
            # Delete from db
            user.key.delete()
            
            pending_users_list = PendingUsersList.shared_list()
            if(pending_users_list.is_user_approved(email)):
                pending_users_list.remove_user_from_approved_list(email)

            # Need to delete the auth_id from the 'unique' model store
            # see https://code.google.com/p/webapp-improved/source/browse/webapp2_extras/appengine/auth/models.py
            unique_auth_id = "User.auth_id:{0}".format(email)
            User.unique_model.delete_multi([unique_auth_id])
        return True
예제 #13
0
 def _reset_user_password(self, email):
     '''
     Reset the password of the user with the given email address to a
      random password that they will be sure to change immediately.
     Returns a tuple (success, password), where success is a boolean
      indicating whether or not the operation completed and password is 
      the new password of the user if success is True.
     '''
     user = User.get_by_auth_id(email)
     # First we have 5 letters (upper/lowercase) or digits
     random_password = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(5))
     # Then 2 punctuation chars
     random_password += ''.join(random.choice(string.punctuation) for x in range(2))
     # Then 5 more letters or digits
     random_password += ''.join(random.choice(string.ascii_letters + string.digits) for x in range(5))
     user.set_password(random_password)
     user.put()
     return (True, random_password)
예제 #14
0
파일: admin.py 프로젝트: dnath/stochss
    def get(self):
        """ Corresponds to /admin """
        users = User.query().fetch()
        if len(users) == 0:
            users = None
        pending_users_list = PendingUsersList.shared_list()

        # This is complicated. We need to get the Users that don't exist as User objects, but exist as approved users. These are the pre-approved users. The admin user must be specifically excluded
        active_users = set(filter(None, [str(u.email_address) if not u.is_admin_user() else None for u in users]))
        approved_users = set([str(u) for u in pending_users_list.approved_users])
        preapproved_users = approved_users - active_users

        context = {
            'active_users': users,
            'preapproved_users': preapproved_users,
            'users_waiting_approval': pending_users_list.users_waiting_approval
        }
        self.render_response('admin.html', **context)
예제 #15
0
    def extractStochKitModel(self, path, userId = None, handler = None, rename = None):
        modelj = json.loads(self.zipfb.read(path))
        modelj["model"] = self.zipfb.read(modelj["model"])

        #print "IMPORTING JOB USER ID IS: ", userId, jobj["user_id"], [x.user_id() for x in User.query().fetch()], jobj["user_id"] in [x.user_id() for x in User.query().fetch()]

        #print "importing ", modelj["model_name"], modelj["user_id"]

        if modelj["user_id"] not in [x.user_id() for x in User.query().fetch()]:
            modelj["user_id"] = handler.user.user_id()

        if userId:
            modelj["user_id"] = userId
            
        res = modeleditor.ModelManager.createModel(handler, modelj, rename = rename)

        #print "create model result ", res

        return res
예제 #16
0
파일: auth.py 프로젝트: ahellander/stochss
 def get(self):
     """ Corresponds to /login """
     # Make sure user isn't logged in already
     if self.logged_in():
         return self.redirect("/")
     # Need to log in
     try:
         secret_key = self.request.GET['secret_key']
     except KeyError:
         secret_key = None
     
     if secret_key is not None:
         secret_key_attempt = SecretKey(key_string=secret_key)
         if secret_key_attempt.isEqualToAdminKey() and not User.admin_exists():
             return self.redirect('/register?secret_key={0}'.format(secret_key))
         else:
             # Unauthorized secret key query string param, just ignore it completely...
             pass
     
     self.render_response('login.html')
예제 #17
0
파일: auth.py 프로젝트: aviral26/stochss
 def get(self):
     """ Corresponds to /login """
     # Make sure user isn't logged in already
     if self.logged_in():
         return self.redirect("/")
     # Need to log in
     try:
         secret_key = self.request.GET['secret_key']
     except KeyError:
         secret_key = None
     
     if secret_key is not None:
         secret_key_attempt = SecretKey(key_string=secret_key)
         if secret_key_attempt.isEqualToAdminKey() and not User.admin_exists():
             return self.redirect('/register?secret_key={0}'.format(secret_key))
         else:
             # Unauthorized secret key query string param, just ignore it completely...
             pass
     
     self.render_response('login.html')
예제 #18
0
파일: admin.py 프로젝트: bbbales2/stochss
 def _delete_user(self, email):
     """ Delete existing user """
     users = User.query(ndb.GenericProperty('email_address') == user_dict['email_address']).fetch()
     if users:
         users[0].delete()
     return True
예제 #19
0
파일: auth.py 프로젝트: jesusrv1103/stochss
    def post(self):
        '''
        This is where user registration takes place, both for regular users as well as admins.
        An admin registers by presenting a secret token in the query string, which will be sent with the
        POST data.
        A user can register only if they have been approved by the admin, i.e. they are in the approved_users
        list (see admin.py).
        '''

        try:
            secret_key = self.request.POST['secret_key']
        except KeyError:
            secret_key = None

        if secret_key is None:
            # Normal user registration
            logging.info('Registering a normal user...')
            user_email = self.request.POST['email']

            # Just an email address here, we should first make sure they have not been approved
            pending_users_list = PendingUsersList.shared_list()

            # If the user does not exist, we create it.
            if not bool(User.get_by_auth_id(user_email)):
                _attrs = {
                    'email_address': user_email,
                    'name': self.request.POST['name'],
                    'password_raw': self.request.POST['password'],
                    'verified': False
                }
                success, user = self.auth.store.user_model.create_user(
                    user_email, **_attrs)

                if success:
                    # check if user is preapproved
                    if pending_users_list.is_user_approved(user_email):
                        success = True
                        approved = True
                        # Has the user been preapproved? If so, we just verify it.
                        user.verified = True
                        user.put()
                    else:
                        success = pending_users_list.add_user_to_approval_waitlist(
                            user_email)
                        approved = False

                if success:
                    if approved or (
                            not pending_users_list.email_verification_required
                            and
                            not pending_users_list.admin_approval_required):
                        context = {
                            'success_alert':
                            True,
                            'alert_message':
                            'Account creation successful! Your account is approved and you can log in immediately.'
                        }
                    elif pending_users_list.email_verification_required:
                        # Create a signup token for the user and send a verification email
                        token = str(uuid.uuid4())
                        user.signup_token = token
                        user.signup_token_time_created = None
                        user.put()
                        EmailConfig.send_verification_email(user_email, token)
                        context = {
                            'success_alert':
                            True,
                            'alert_message':
                            'Account creation successful! You will recieve a verification email, please follow the instructions to activate your account.'
                        }
                    elif pending_users_list.admin_approval_required:
                        context = {
                            'success_alert':
                            True,
                            'alert_message':
                            'Account creation successful! Once an admin has approved your account, you can login.'
                        }

                    return self.render_response('login.html', **context)

                logging.info(
                    "Account registration failed for: {0}".format(user))
                context = {
                    'email_address': self.request.POST['email'],
                    'name': self.request.POST['name'],
                    'user_registration_failed': True
                }
                return self.render_response('user_registration.html',
                                            **context)
            else:
                context = {
                    'error_alert': True,
                    'alert_message': 'You have already requested an account.'
                }
                return self.render_response('login.html', **context)
        else:
            # Attempt to create an admin user
            logging.info('Registering an admin user...')
            # Check the secret key again
            secret_key_attempt = SecretKey(key_string=secret_key)
            if secret_key_attempt.isEqualToAdminKey():
                # Then we can attempt to create an admin
                if User.admin_exists():
                    logging.info("Admin already exists...")
                    # Redirect to login, only one admin allowed
                    return self.redirect(
                        '/login?secret_key={0}'.format(secret_key))
                else:
                    # CREATE THE ADMIN ALREADY
                    _attrs = {
                        'email_address': self.request.POST['email'],
                        'name': self.request.POST['name'],
                        'password_raw': self.request.POST['password'],
                        'is_admin': 'YES',
                        'verified': True
                    }
                    success, user = self.auth.store.user_model.create_user(
                        _attrs['email_address'], **_attrs)

                    if success:
                        # Invalidate the token
                        SecretKey.clear_stored_key()
                        if 'user_mode' in self.request.POST:
                            if self.request.POST['user_mode'] == 'single':
                                logging.info(
                                    "UserRegistrationPage: user_mode set to single"
                                )
                                SingleMultiUserMode.set_single_user_mode()
                            elif self.request.POST['user_mode'] == 'multi':
                                logging.info(
                                    "UserRegistrationPage: user_mode set to multi"
                                )
                                SingleMultiUserMode.set_multi_user_mode()
                            else:
                                logging.info(
                                    "UserRegistrationPage: unknown user_mode {0}"
                                    .format(self.request.POST['user_mode']))
                        else:
                            logging.info(
                                "UserRegistrationPage: user_mode not set")
                        return self.redirect(
                            '/login?secret_key={0}'.format(secret_key))
                    else:
                        context = {
                            'email_address': self.request.POST['email'],
                            'name': self.request.POST['name'],
                            'user_registration_failed': True
                        }
                        return self.render_response('user_registration.html',
                                                    **context)

            else:
                # Unauthorized secret key
                context = {
                    'error_alert': True,
                    'alert_message': 'Invalid secret token.'
                }
                return self.render_response('login.html', **context)
예제 #20
0
파일: auth.py 프로젝트: StochSS/stochss
    def post(self):
        '''
        This is where user registration takes place, both for regular users as well as admins.
        An admin registers by presenting a secret token in the query string, which will be sent with the
        POST data.
        A user can register only if they have been approved by the admin, i.e. they are in the approved_users
        list (see admin.py).
        '''

        try:
            secret_key = self.request.POST['secret_key']
        except KeyError:
            secret_key = None
        
        if secret_key is None:
            # Normal user registration
            logging.info('Registering a normal user...')
            user_email = self.request.POST['email']

            # Just an email address here, we should first make sure they have not been approved
            pending_users_list = PendingUsersList.shared_list()

            # If the user does not exist, we create it.
            if not bool(User.get_by_auth_id(user_email)):
                _attrs = {
                    'email_address': user_email,
                    'name': self.request.POST['name'],
                    'password_raw': self.request.POST['password'],
                    'verified': False
                }
                success, user = self.auth.store.user_model.create_user(user_email, **_attrs)

                if success:
                    # check if user is preapproved
                    if pending_users_list.is_user_approved(user_email):
                        success = True
                        approved = True
                        # Has the user been preapproved? If so, we just verify it.
                        user.verified = True
                        user.put()
                    else:
                        success = pending_users_list.add_user_to_approval_waitlist(user_email)
                        approved = False
                
                if success:
                    if approved or (not pending_users_list.email_verification_required and not pending_users_list.admin_approval_required):
                        context = {
                            'success_alert': True,
                            'alert_message': 'Account creation successful! Your account is approved and you can log in immediately.'
                        }
                    elif pending_users_list.email_verification_required:
                        # Create a signup token for the user and send a verification email
                        token = str(uuid.uuid4())
                        user.signup_token = token
                        user.signup_token_time_created=None
                        user.put()
                        EmailConfig.send_verification_email(user_email, token)
                        context = {
                            'success_alert': True,
                            'alert_message': 'Account creation successful! You will recieve a verification email, please follow the instructions to activate your account.'
                        }
                    elif pending_users_list.admin_approval_required:
                        context = {
                            'success_alert': True,
                            'alert_message': 'Account creation successful! Once an admin has approved your account, you can login.'
                        }

                    return self.render_response('login.html', **context)

                logging.info("Account registration failed for: {0}".format(user))
                context = {
                    'email_address': self.request.POST['email'],
                    'name': self.request.POST['name'],
                    'user_registration_failed': True
                }
                return self.render_response('user_registration.html', **context)
            else:
                context = {
                    'error_alert': True,
                    'alert_message': 'You have already requested an account.'
                }
                return self.render_response('login.html', **context)
        else:
            # Attempt to create an admin user
            logging.info('Registering an admin user...')
            # Check the secret key again
            secret_key_attempt = SecretKey(key_string=secret_key)
            if secret_key_attempt.isEqualToAdminKey():
                # Then we can attempt to create an admin
                if User.admin_exists():
                    logging.info("Admin already exists...")
                    # Redirect to login, only one admin allowed
                    return self.redirect('/login?secret_key={0}'.format(secret_key))
                else:
                    # CREATE THE ADMIN ALREADY
                    _attrs = {
                        'email_address': self.request.POST['email'],
                        'name': self.request.POST['name'],
                        'password_raw': self.request.POST['password'],
                        'is_admin': 'YES',
                        'verified': True
                    }
                    success, user = self.auth.store.user_model.create_user(_attrs['email_address'], **_attrs)
                    
                    if success:
                        # Invalidate the token
                        SecretKey.clear_stored_key()
                        if 'user_mode' in self.request.POST:
                            if self.request.POST['user_mode'] == 'single':
                                logging.info("UserRegistrationPage: user_mode set to single")
                                SingleMultiUserMode.set_single_user_mode()
                            elif self.request.POST['user_mode'] == 'multi':
                                logging.info("UserRegistrationPage: user_mode set to multi")
                                SingleMultiUserMode.set_multi_user_mode()
                            else:
                                logging.info("UserRegistrationPage: unknown user_mode {0}".format(self.request.POST['user_mode']))
                        else:
                            logging.info("UserRegistrationPage: user_mode not set")
                        return self.redirect('/login?secret_key={0}'.format(secret_key))
                    else:
                        context = {
                            'email_address': self.request.POST['email'],
                            'name': self.request.POST['name'],
                            'user_registration_failed': True
                        }
                        return self.render_response('user_registration.html', **context)
            
            else:
                # Unauthorized secret key
                context = {
                    'error_alert': True,
                    'alert_message': 'Invalid secret token.'
                }
                return self.render_response('login.html', **context)
예제 #21
0
    def post(self):
        if 'files[]' in self.request.POST:
            files = []
            for name, fieldStorage in self.request.POST.items():
                if type(fieldStorage) is unicode:
                    continue

                job = ImportJobWrapper()

                filename, suffix = os.path.splitext(fieldStorage.filename)
                filename = os.path.basename(filename)
                
                path = os.path.abspath(os.path.dirname(__file__))
                [tid, tmpfile] = tempfile.mkstemp(dir = os.path.abspath(os.path.dirname(__file__)) + '/../static/tmp/', prefix = filename + "_", suffix = suffix)
                job.userId = self.user.user_id()
                job.status = "Writing file on server"
                job.zipFile = tmpfile

                job.put()

                fhandle = os.fdopen(tid, 'w')
                fhandle.write(fieldStorage.value)
                fhandle.close()

                job.status = "Analyzing file"
                job.put()

                zipFile = zipfile.ZipFile(fieldStorage.file, 'r')

                headers = { "models" : {}, "stochkitJobs" : {}, "stochOptimJobs" : {}, "sensitivityJobs" : {} }
                for name in zipFile.namelist():
                    if re.search('models/[a-zA-Z0-9\-_]*\.json$'.format(filename), name):
                        headers['models'][name] = json.loads(zipFile.read(name))
                    elif re.search('stochkitJobs/[a-zA-Z0-9\-_]*\.json$'.format(filename), name):
                        headers['stochkitJobs'][name] = json.loads(zipFile.read(name))
                    elif re.search('sensitivityJobs/[a-zA-Z0-9\-_]*\.json$'.format(filename), name):
                        headers['sensitivityJobs'][name] = json.loads(zipFile.read(name))
                    elif re.search('stochOptimJobs/[a-zA-Z0-9\-_]*\.json$'.format(filename), name):
                        headers['stochOptimJobs'][name] = json.loads(zipFile.read(name))

                #print headers['stochOptimJobs']

                zipFile.close();

                job.status = "Finished"
                [tid, tmpfile] = tempfile.mkstemp(dir = os.path.abspath(os.path.dirname(__file__)) + '/../static/tmp/')

                fhandle = os.fdopen(tid, 'w')
                fhandle.write(json.dumps(headers))
                fhandle.close()

                job.headerFile = tmpfile
                job.put()

                files.append( fieldStorage.filename )
            
            self.response.headers['Content-Type'] = 'application/json'
            self.response.write(json.dumps(files))
        else:
            reqType = self.request.get('reqType')

            if reqType == 'importInfo':
                # Print [ { id: importJobid,
                #           zipFile : zipFilename,
                #           listOfModelJsons,
                #           listOfJobJsons } ]

                jobs = []

                for job in db.GqlQuery("SELECT * FROM ImportJobWrapper WHERE userId = :1", self.user.user_id()).run():
                    #Using os open here cause normal Python open is failing
                    try:
                        fdescript = os.open(job.headerFile, os.O_RDONLY)
                    except:
                        job.delete()
                        return

                    contents = ""
                    while 1:
                        part = os.read(fdescript, 5000)
                        if part == '':
                            break

                        contents += part;

                    headers = json.loads(contents)
                    os.close(fdescript)

                    try:
                      fversion = open(os.path.abspath(os.path.dirname(__file__)) + '/../VERSION', 'r')
                      version = fversion.read().strip()
                      fversion.close()
                    except:
                      version = "1.1.0"

                    jobs.append({ "id" : job.key().id(),
                                  "zipFile" : os.path.basename(job.zipFile),
                                  "headers" : headers,
                                  "version" : version })
                    
                self.response.headers['Content-Type'] = 'application/json'
                self.response.write(json.dumps(jobs))
                return
            elif reqType == 'doImport':
                state = json.loads(self.request.get('state'))
                overwriteType = self.request.get('overwriteType')

                job = ImportJobWrapper.get_by_id(state["id"])
                fdescript = os.open(job.headerFile, os.O_RDONLY)
                
                contents = ""
                while 1:
                    part = os.read(fdescript, 5000)
                    if part == '':
                        break

                    contents += part;

                headers = json.loads(contents)
                os.close(fdescript)

                globalOp = self.request.get('globalOp')

                globalOp = True if globalOp == 'true' else False

                job = ImportJobWrapper.get_by_id(state["id"])

                if globalOp and not self.user.is_admin_user():
                    self.response.headers['Content-Type'] = 'application/json'
                    self.response.write( json.dumps({ "status" : False,
                                                      "msg" : "Non-admin users cannot export all data" }) )
                    return

                szip = SuperZip(zipFileName = job.zipFile)

                if not globalOp:
                    userId = self.user.user_id()
                else:
                    userId = None

                validUsers = [x.user_id() for x in User.query().fetch()]

                for name in state['selections']['mc']:
                    if not state['selections']['mc'][name]:
                        continue

                    if userId == None:
                        userID = headers['models'][name]["user_id"]

                        if userID not in validUsers:
                            userID = userId
                    else:
                        userID = userId

                    rename = False
                    dbName = headers['models'][name]["name"]
                    jobs = list(db.GqlQuery("SELECT * FROM StochKitModelWrapper WHERE user_id = :1 AND model_name = :2", userID, dbName).run())

                    if len(jobs) > 0:
                        otherJob = jobs[0]

                        if overwriteType == 'keepOld':
                            continue
                        elif overwriteType == 'overwriteOld':
                            #print 'deleting', dbName, 'hehe'
                            otherJob.delete()
                        #elif overwriteType == 'renameOld':
                        #    i = 1
                        #    tryName = name + '_' + str(i)

                        #    while len(list(db.GqlQuery("SELECT * FROM StochKitJobWrapper WHERE user_id = :1 AND name", self.user.user_id(), tryName).run())) > 0:
                        #        i += 1
                        #        tryName = name + '_' + str(i)

                        #    otherJob.name = tryName
                        #    otherJob.put()
                        elif overwriteType == 'renameNew':
                            rename = True
                            
                    #print "importing ", name
                    szip.extractStochKitModel(name, userId, self, rename = rename)

                #print "globalOp", userId

                for name in state['selections']['sjc']:
                    if not state['selections']['sjc'][name]:
                        continue

                    if userId == None:
                        userID = headers['stochkitJobs'][name]["user_id"]

                        if userID not in validUsers:
                            userID = userId
                    else:
                        userID = userId

                    dbName = headers['stochkitJobs'][name]["name"]
                    jobs = list(db.GqlQuery("SELECT * FROM StochKitJobWrapper WHERE user_id = :1 AND name = :2", userID, dbName).run())

                    rename = False

                    if len(jobs) > 0:
                        otherJob = jobs[0]

                        #print otherJob.name

                        if overwriteType == 'keepOld':
                            continue
                        elif overwriteType == 'overwriteOld':
                            otherJob.delete(self)
                        elif overwriteType == 'renameNew':
                            rename = True

                    szip.extractStochKitJob(name, userId, self, rename = rename)

                for name in state['selections']['snc']:
                    if not state['selections']['snc'][name]:
                        continue

                    if userId == None:
                        userID = headers['sensitivityJobs'][name]["userId"]

                        if userID not in validUsers:
                            userID = userId
                    else:
                        userID = userId

                    dbName = headers['sensitivityJobs'][name]["jobName"]
                    jobs = list(db.GqlQuery("SELECT * FROM SensitivityJobWrapper WHERE userId = :1 AND jobName = :2", userID, dbName).run())

                    rename = False

                    if len(jobs) > 0:
                        otherJob = jobs[0]

                        if overwriteType == 'keepOld':
                            continue
                        elif overwriteType == 'overwriteOld':
                            otherJob.delete()
                        elif overwriteType == 'renameNew':
                            rename = True

                    szip.extractSensitivityJob(name, userId, self, rename = rename)

                for name in state['selections']['soc']:
                    if not state['selections']['soc'][name]:
                        continue

                    if userId == None:
                        userID = headers['stochOptimJobs'][name]["userId"]

                        if userID not in validUsers:
                            userID = userId
                    else:
                        userID = userId

                    dbName = headers['stochOptimJobs'][name]["jobName"]
                    jobs = list(db.GqlQuery("SELECT * FROM StochOptimJobWrapper WHERE userId = :1 AND jobName = :2", userID, dbName).run())

                    rename = False

                    if len(jobs) > 0:
                        otherJob = jobs[0]

                        if overwriteType == 'keepOld':
                            continue
                        elif overwriteType == 'overwriteOld':
                            otherJob.delete()
                        elif overwriteType == 'renameNew':
                            rename = True

                    szip.extractStochOptimJob(name, userId, self, rename = rename)

                szip.close()

                # Expect an importJobId
                # along with a list of model jsons to import
                # and a list of job jsons to import
                self.response.headers['Content-Type'] = 'application/json'
                self.response.write(json.dumps( { "status" : True,
                                                  "msg" : "Archive imported" }))
                
                return
            elif reqType == 'delJob':
                job = ImportJobWrapper.get_by_id(int(self.request.get('id')))
                job.delete()
                
                self.response.headers['Content-Type'] = 'application/json'
                self.response.write(json.dumps( { "status" : True, "msg" : "Export job deleted" } ))
                return
예제 #22
0
 def user_exists(self, user_email):
     return bool(User.get_by_auth_id(user_email))
예제 #23
0
    def post(self):
        '''
        This is where user registration takes place, both for regular users as well as admins.
        An admin registers by presenting a secret token in the query string, which will be sent with the
        POST data.
        A user can register only if they have been approved by the admin, i.e. they are in the approved_users
        list (see admin.py).
        '''

        try:
            secret_key = self.request.POST['secret_key']
        except KeyError:
            secret_key = None

        if secret_key is None:
            # Normal user registration
            logging.info('Registering a normal user...')
            user_email = self.request.POST['email']

            # Just an email address here, we should first make sure they havent been approved
            pending_users_list = PendingUsersList.shared_list()

            # Now add to approval waitlist
            if pending_users_list.is_user_approved(user_email):
                success = True
                approved = True
            elif pending_users_list.user_exists(user_email):
                success = True
                approved = False
            else:
                success = pending_users_list.add_user_to_approval_waitlist(
                    user_email)
                approved = False

            if success:
                # Then create the user
                _attrs = {
                    'email_address': user_email,
                    'name': self.request.POST['name'],
                    'password_raw': self.request.POST['password']
                }
                success, user = self.auth.store.user_model.create_user(
                    user_email, **_attrs)

                if success:
                    if approved:
                        context = {
                            'success_alert':
                            True,
                            'alert_message':
                            'Account creation successful! Your account is approved and you can log in immediately.'
                        }
                    else:
                        context = {
                            'success_alert':
                            True,
                            'alert_message':
                            'Account creation successful! Once an admin has approved your account, you can login.'
                        }

                    return self.render_response('login.html', **context)
                else:
                    logging.info(
                        "Acount registration failed for: {0}".format(user))
                    context = {
                        'email_address': self.request.POST['email'],
                        'name': self.request.POST['name'],
                        'user_registration_failed': True
                    }
                    return self.render_response('user_registration.html',
                                                **context)
            else:
                context = {
                    'error_alert': True,
                    'alert_message': 'You have already requested an account.'
                }
                return self.render_response('login.html', **context)
        else:
            # Attempt to create an admin user
            logging.info('Registering an admin user...')
            # Check the secret key again
            secret_key_attempt = SecretKey(key_string=secret_key)
            if secret_key_attempt.isEqualToAdminKey():
                # Then we can attempt to create an admin
                if User.admin_exists():
                    logging.info("Admin already exists...")
                    # Delete the token from the DB and redirect to login, only one admin allowed
                    SecretKey.clear_stored_key()
                    return self.redirect('/login')
                else:
                    # CREATE THE ADMIN ALREADY
                    _attrs = {
                        'email_address': self.request.POST['email'],
                        'name': self.request.POST['name'],
                        'password_raw': self.request.POST['password'],
                        'is_admin': 'YES'
                    }
                    success, user = self.auth.store.user_model.create_user(
                        _attrs['email_address'], **_attrs)

                    if success:
                        # Invalidate the token
                        SecretKey.clear_stored_key()
                        context = {
                            'success_alert':
                            True,
                            'alert_message':
                            'Account creation successful! You may now log in with your new account.'
                        }
                        return self.render_response('login.html', **context)
                    else:
                        context = {
                            'email_address': self.request.POST['email'],
                            'name': self.request.POST['name'],
                            'user_registration_failed': True
                        }
                        return self.render_response('user_registration.html',
                                                    **context)

            else:
                # Unauthorized secret key
                context = {
                    'error_alert': True,
                    'alert_message': 'Invalid secret token.'
                }
                return self.render_response('login.html', **context)
예제 #24
0
파일: auth.py 프로젝트: aviral26/stochss
    def post(self):
        '''
        This is where user registration takes place, both for regular users as well as admins.
        An admin registers by presenting a secret token in the query string, which will be sent with the
        POST data.
        A user can register only if they have been approved by the admin, i.e. they are in the approved_users
        list (see admin.py).
        '''
        logging.info(self.request.POST)

        try:
            secret_key = self.request.POST['secret_key']
        except KeyError:
            secret_key = None
        
        if secret_key is None:
            # Normal user registration
            logging.info('Registering a normal user...')
            user_email = self.request.POST['email']

            # Just an email address here, we should first make sure they havent been approved
            pending_users_list = PendingUsersList.shared_list()

            # Now add to approval waitlist
            if pending_users_list.is_user_approved(user_email):
                success = True
                approved = True
            elif pending_users_list.user_exists(user_email):
                success = True
                approved = False
            else:
                success = pending_users_list.add_user_to_approval_waitlist(user_email)
                approved = False

            if success:
                # Then create the user
                _attrs = {
                    'email_address': user_email,
                    'name': self.request.POST['name'],
                    'password_raw': self.request.POST['password']
                }
                success, user = self.auth.store.user_model.create_user(user_email, **_attrs)
                
                if success:
                    if approved:
                        context = {
                            'success_alert': True,
                            'alert_message': 'Account creation successful! Your account is approved and you can log in immediately.'
                        }
                    else:
                        context = {
                            'success_alert': True,
                            'alert_message': 'Account creation successful! Once an admin has approved your account, you can login.'
                        }

                    return self.render_response('login.html', **context)
                else:
                    logging.info("Acount registration failed for: {0}".format(user))
                    context = {
                        'email_address': self.request.POST['email'],
                        'name': self.request.POST['name'],
                        'user_registration_failed': True
                    }
                    return self.render_response('user_registration.html', **context)
            else:
                context = {
                    'error_alert': True,
                    'alert_message': 'You have already requested an account.'
                }
                return self.render_response('login.html', **context)
        else:
            # Attempt to create an admin user
            logging.info('Registering an admin user...')
            # Check the secret key again
            secret_key_attempt = SecretKey(key_string=secret_key)
            if secret_key_attempt.isEqualToAdminKey():
                # Then we can attempt to create an admin
                if User.admin_exists():
                    logging.info("Admin already exists...")
                    # Delete the token from the DB and redirect to login, only one admin allowed
                    SecretKey.clear_stored_key()
                    return self.redirect('/login')
                else:
                    # CREATE THE ADMIN ALREADY
                    _attrs = {
                        'email_address': self.request.POST['email'],
                        'name': self.request.POST['name'],
                        'password_raw': self.request.POST['password'],
                        'is_admin': 'YES'
                    }
                    success, user = self.auth.store.user_model.create_user(_attrs['email_address'], **_attrs)
                    
                    if success:
                        # Invalidate the token
                        SecretKey.clear_stored_key()
                        context = {
                            'success_alert': True,
                            'alert_message': 'Account creation successful! You may now log in with your new account.'
                        }
                        return self.render_response('login.html', **context)
                    else:
                        context = {
                            'email_address': self.request.POST['email'],
                            'name': self.request.POST['name'],
                            'user_registration_failed': True
                        }
                        return self.render_response('user_registration.html', **context)
            
            else:
                # Unauthorized secret key
                context = {
                    'error_alert': True,
                    'alert_message': 'Invalid secret token.'
                }
                return self.render_response('login.html', **context)