Beispiel #1
0
    def d2l_authorization(self):
        uc = self.get_user_context()
        if not isinstance(uc, d2lauth.D2LUserContext):
            return uc # if no user_context is setup, return uc to d2l to get authorized.
        
        try:
            whoami = d2lservice.get_whoami(uc)
            id = str(whoami.UniqueName) + self.settings('d2l_append_email_address','')
            fullname = whoami.FirstName + u' ' + whoami.LastName
            
            # if doesn't exist create it and update login info
            category = self.request.params.get('category','0')
            user = Users.by({'email':id}).first()
            if not user:
                Users.registerNonLocalUser(email=id, fullname=fullname)
                user = Users.by({'email':id}).first() #retrieve new user
            
            # auto group incoming users
            if Validate.bool(self.request.params.get('group','false')):
                user = Users.add_groups(user, Groups.groups_auto_assigned_by_category(category))
            
            user = Users.login_updates(user)
            
            # set session and send them to alias controller
            return HTTPFound(location=route_url('alias', self.request, _query={'category':category} ), 
                             headers=remember(self.request, user.id))

        except Exception as e:
            print "ERROR 0: " + str(e) # log later?
        return HTTPForbidden() 
Beispiel #2
0
 def feedback(self):
     self.response['sent_status'] = 0
     if 'feedback.message' in self.request.params:
         msg = Validate.sanatize_textsafe(self.request.params.get('feedback.message',''))
         msg = msg + "\n\n ---------- \n"
         msg = msg + "Player: " + self.request.params.get('feedback.player','error') + "\n"
         msg = msg + "Category: " + self.request.params.get('feedback.category','error') + "\n"
         msg = msg + "From: " + self.request.params.get('feedback.from','error') + "\n"
         
         try:
             # Send to 
             emails = Properties.get('MAILER_FEEDBACK_ADDRESS').replace(' ','').split(',')
             message = Message(subject="Feedback - " + datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S"),
                               sender=self.request.user.email,
                               recipients=emails,
                               body=msg
                               )
             mailer = get_mailer(self.request)
             mailer.send(message)
             
             # Receipt
             message_receipt = Message(subject="Feedback - Receipt",
                               sender=Properties.get('MAILER_GLOBAL_FROM_ADDRESS'),
                               recipients=[self.request.user.email],
                               body="Thank you for submitting feedback. \n\n ---- \n" + Validate.sanatize_textsafe(self.request.params.get('feedback.message',''))
                               )
             mailer.send(message_receipt)
             
             self.response['sent_status'] = 2
         except Exception as e:
             self.response['sent_status'] = 1
     return self.response
Beispiel #3
0
    def email(self):
        id = self.request.matchdict['id']
        test = Tests.by({'id':id,'alias':self.request.user.alias}).first()
        if not test:
            raise HTTPForbidden()
        file = self._generate_pdf(id)
        self.response['id'] = id
        self.response['emails'] = self.request.params.get('email.addresses',None)
        
        if 'form.submitted' in self.request.params:
            if self.request.params['email.ok'] == '1':
                emails = self.request.params['email.addresses'].replace(' ','').split(',')
                for email in emails:
                    if not Validate.email(email):
                        self.notify('Invalid email address',warn=True)
                        return self.template('email.pt')
                        
                try:
                    message = Message(subject=self._email_fmt(id, str(Properties.get('MAILER_TO_SUBJECT','Submission'))),
                                      sender=str(Properties.get('MAILER_GLOBAL_FROM_ADDRESS','System')),
                                      recipients=emails,
                                      body=self._email_fmt(id, str(Properties.get('MAILER_BODY','Submission'))))
                    attachment = Attachment('submission_' + str(id) + '.pdf', 'application/pdf', file)
                    message.attach(attachment)
                    mailer = get_mailer(self.request)
                    mailer.send(message)
                    self.notify('Email sent!')
                except Exception as e:
                    print "ERROR: " + str(e)
                    self.notify('Unable to send email!',warn=True)
            else:
                self.notify('Unable to send example email!',warn=True)

        return self.template('email.pt')
Beispiel #4
0
 def login(self):
     self.response['allow_registration'] = Validate.bool(self.settings('allow_local_registration','false'))
     if self.request.user:
         return HTTPFound(location=route_url('alias', self.request, _query={'category':self.request.params.get('category',0)}))
         
     for fn in self.login_layers:
         layer = fn(self)
         if layer:
             return layer
    def login(self):
        self.response["allow_registration"] = Validate.bool(self.settings("allow_local_registration", "false"))
        if self.request.user:
            return HTTPFound(
                location=route_url("alias", self.request, _query={"category": self.request.params.get("category", 0)})
            )

        for fn in self.login_layers:
            layer = fn(self)
            if layer:
                return layer
Beispiel #6
0
 def __init__(self, request, response):
     self.response = response
     self.request = request
     self.response['category'] = self.request.params.get('category','Unknown Category')
     s = request.params.get('start','').strip(' ')
     if s == '': s = '1/1/2000'
     e = request.params.get('end','').strip(' ')
     if e == '': e = '1/1/2030'
     self.start = datetime.datetime.strptime(s, '%m/%d/%Y')
     self.end = datetime.datetime.strptime(e, '%m/%d/%Y')
     self.include_incompleted = Validate.bool(self.request.params.get('incompleted', False))
    def register(self):
        if not Validate.bool(self.settings("allow_local_registration", "false")):
            return HTTPFound(location=route_url("menu", self.request))

        self.response["email"] = ""

        if "form.submitted" in self.request.params:
            self.response["email"] = Validate.sanatize(self.request.params["email"])
            password = Validate.sanatize(self.request.params["password"])
            repassword = Validate.sanatize(self.request.params["re.password"])

            if Users.by({"email": self.response["email"]}).first():
                self.notify("Email already in use!", warn=True)
                return self.template("register.pt")
            if not Validate.email(self.response["email"]):
                self.notify("Not a valid email address!", warn=True)
                return self.template("register.pt")
            if not Validate.password(password):
                self.notify("Improper password!", warn=True)
                return self.template("register.pt")
            if repassword != password:
                self.notify("Passwords do not match!", warn=True)
                return self.template("register.pt")

            # Below is good
            Users.registerLocalUser(self.response["email"], password)
            return HTTPFound(location=route_url("login", self.request))

        return self.template("register.pt")
Beispiel #8
0
 def register(self):
     if not Validate.bool(self.settings('allow_local_registration','false')):
         return HTTPFound(location=route_url('menu', self.request))
 
     self.response['email'] = ''
 
     if 'form.submitted' in self.request.params:
         self.response['email'] = Validate.sanatize(self.request.params['email'])
         password = Validate.sanatize(self.request.params['password'])
         repassword = Validate.sanatize(self.request.params['re.password'])
         
         if Users.by({'email':self.response['email']}).first():
             self.response['message'] = "Email already in use"
             return self.template('register.pt')
         if not Validate.email(self.response['email']):
             self.response['message'] = "Not a valid email address"
             return self.template('register.pt')
         if not Validate.password(password):
             self.response['message'] = "Improper password."
             return self.template('register.pt')
         if repassword != password:
             self.response['message'] = "Passwords do not match."
             return self.template('register.pt')
             
         # Below is good
         Users.registerLocalUser(self.response['email'], password)
         return HTTPFound(location=route_url('login', self.request))
         
     return self.template('register.pt')
    def change_password(self):
        user = Users.by(self.request.user.id).first()
        if not user.is_local:
            return HTTPForbidden()

        if "form.submitted" in self.request.params:
            old = Validate.sanatize(self.request.params["old_password"])
            new = Validate.sanatize(self.request.params["new_password"])
            recheck = Validate.sanatize(self.request.params["new_recheck_password"])

            if not Validate.password(new):
                self.notify("Improper new password!", warn=True)
                return self.template("change_password.pt")
            if recheck != new:
                self.notify("New passwords do not match!", warn=True)
                return self.template("change_password.pt")

            if user.validate_password(old):
                user._set_password(new)
                transaction.commit()

        return self.template("change_password.pt")
Beispiel #10
0
    def change_password(self):
        user = Users.by(self.request.user.id).first()
        if not user.is_local:
            return HTTPForbidden()

        if 'form.submitted' in self.request.params:
            old = Validate.sanatize(self.request.params['old_password'])
            new = Validate.sanatize(self.request.params['new_password'])
            recheck = Validate.sanatize(self.request.params['new_recheck_password'])
            
            if not Validate.password(new):
                self.response['message'] = "Improper new password."
                return self.template('change_password.pt')
            if recheck != new:
                self.response['message'] = "New passwords do not match."
                return self.template('change_password.pt')
            
            if user.validate_password(old):
                user._set_password(new)
                transaction.commit()
    
        return self.template('change_password.pt')
Beispiel #11
0
    def alias(self):
        if self.request.user.alias:
            return self.reroute()

        self.response['alias'] =  ''
        self.response['accessibility'] = False
        if 'form.submitted' in self.request.params:
            self.response['alias'] = Validate.sanatize(self.request.params['alias'])
            self.response['accessibility'] = Validate.bool(self.request.params.get('accessibility', False))

            user = Users.by({'alias':self.response['alias']}).first()
            if user:
                self.response['message'] = 'Alias is already taken'
            elif not Validate.alias(self.response['alias']):
                self.response['message'] = 'Improper Alias'
            else:
                user = Users.by(self.request.user.id).first()
                user.alias = self.response['alias']
                user.needs_accessibility = self.response['accessibility']
                transaction.commit()
                return self.reroute()
                
        return self.template('alias.pt')
Beispiel #12
0
    def alias(self):
        if self.request.user.alias:
            return self.reroute()

        self.response['alias'] =  ''
        self.response['category'] = self.request.params.get('category','0')
        self.response['accessibility'] = False
        if 'form.submitted' in self.request.params:
            self.response['alias'] = Validate.sanatize(self.request.params['alias'])
            self.response['accessibility'] = Validate.bool(self.request.params.get('accessibility', False))

            user = Users.by({'alias':self.response['alias']}).first()
            if user:
                self.notify('Alias already in use!',warn=True)
            elif not Validate.alias(self.response['alias']):
                self.notify('Improper alias!',warn=True)
            else:
                user = Users.by(self.request.user.id).first()
                user.alias = self.response['alias']
                user.needs_accessibility = self.response['accessibility']
                transaction.commit()
                return self.reroute()
                
        return self.template('alias.pt')
Beispiel #13
0
    def _transaction(self, question_set, fields):
         
        for key,v in fields.iteritems():
            if Validate.sanatize(v) != '':
               
                parts = key.split('_')
            
                if parts[0] == 'answerhelp':
                    question_set.answer_help = v

                if parts[0] == 'correctanswer' and not key.endswith('_index'):
                    if parts[1] == 'old':
                        a = Answers.by(parts[2]).first()
                        a.answer = v
                        a.position=fields[key + '_index']
                    else:
                        a = Answers(question_sets_id=question_set.id, answer=v, is_correct=True, position=fields[key + '_index'])
                        DBSession.add(a)
                
                if parts[0] == 'wronganswer' and not key.endswith('_index'):
                    if parts[1] == 'old':
                        a = Answers.by(parts[2]).first()
                        a.answer = v
                        a.position = fields[key + '_index']
                    else:
                        a = Answers(question_sets_id=question_set.id, answer=v, is_correct=False, position=fields[key + '_index'])
                        DBSession.add(a)
                        
                if parts[0] == 'question':
                    if parts[1] == 'old':
                        a = Questions.by(parts[2]).first()
                        a.question = v
                    else:
                        a = Questions(question=v, question_sets_id=question_set.id)
                        DBSession.add(a)
        
            DBSession.flush()
        transaction.commit()
        
        
        
        
        
        
        
        
        
        
Beispiel #14
0
    def edit_category(self):
        category_id = self.request.matchdict['category']
        self.response['category_id'] = category_id
        self.response['version'] = Addons.get_version('QuizSmith Core')
        self.response['d2l_on'] = Validate.bool(self.settings('d2l_on'))
        
        if 'form.submit' in self.request.params or 'form.submit.questions' in self.request.params:
            active = None
            if category_id == 'add':
                active = Categories(name='New Category')
                editors = []
                for group in self.request.user.get_groups():
                    editors.append(str(group.id))
                reviewers = []
                for group in self.request.user.get_groups():
                    reviewers.append(str(group.id))
                active.set_groups([], editors, reviewers)
                DBSession.add(active)
                DBSession.flush()
                category_id = str(active.id)
            else:
                active = Categories.by(category_id, sort='position asc', user=self.request.user, permission=ACL.EDIT).first()
            
            active.name = self.request.params.get('category.name','')
            active.category_intro = self.request.params.get('category.intro','')
            active.playable_questions = self.request.params.get('category.playable_questions',10)
            active.wrong_answer_time_penalty = self.request.params.get('category.wrong_answer_time_penalty',5)
            active.max_wrong_answer_allowed = self.request.params.get('category.max_wrong_answer_allowed',2)
            active.question_time_allowed = self.request.params.get('category.question_time_allowed',30)
            active.transition_in = self.request.params.get('category.transition_in','Random')
            active.transition_out = self.request.params.get('category.transition_out','Random')
            active.d2l_folder = self.request.params.get('category.d2l_folder','')
            
            assesment_data = []
            for key,v in self.request.params.iteritems():
                if key.startswith('assessment'):
                    field_data = key.split('.')
                    row = {}
                    if not any(a['id'] == field_data[-1] for a in assesment_data):
                        assesment_data.append(row)
                    else:
                        row = filter(lambda x: x['id'] == field_data[-1], assesment_data)[0]
                    row['id'] = field_data[-1]
                    if v.isdigit():
                        row[field_data[1]] = int(v)
                    else:  
                        row[field_data[1]] = str(v)
            active.set_assessments(assesment_data)
            
            editors = []
            if  self.request.params.getall('category.editable'):
                editors = self.request.params.getall('category.editable')
            else:
                for g in active.groups:
                    if g.edit:
                        editors.append(str(g.groups_id))
                        
            reviewers = []
            if  self.request.params.getall('category.reviewable'):
                reviewers = self.request.params.getall('category.reviewable')
            else:
                for g in active.groups:
                    if g.edit:
                        editors.append(str(g.groups_id))
            
            active.set_groups(self.request.params.getall('category.playable'), editors, reviewers)
            DBSession.flush()
            transaction.commit()
            self.notify('Changes saved!')
            if 'form.submit.questions' in self.request.params:
                return HTTPFound(location=self.request.application_url + '/edit/category/' + category_id + '/questions')
            return HTTPFound(location=self.request.application_url + '/edit/category/' + category_id)
        elif category_id == 'add':
            self.response['active_category'] = Categories(name='New Category')
        else:
            self.response['active_category'] = Categories.by(category_id, sort='position asc', user=self.request.user, permission=ACL.EDIT, strict=True).first()

        self.response['transitions_in'] = self.response['active_category'].transition_in
        self.response['transitions_out'] = self.response['active_category'].transition_out
        self.response['transitions'] = Transitions.all()
        
        
        self.response['questions'] = QuestionSets.by({'category_id':category_id}).count()
        self.response['all_edit_groups'] = Groups.by({'edit':True}).all()
        self.response['all_play_groups'] = Groups.by({'play':True}).all()
        self.response['all_review_groups'] = Groups.by({'review':True}).all()
        self.response['play_groups'] =  []
        self.response['edit_groups'] =  []
        self.response['review_groups'] =  []
        
        if self.response['active_category'].groups:
            for categorygroup in self.response['active_category'].groups:
                group = Groups.by(categorygroup.groups_id).first()
                if categorygroup.edit:
                    self.response['edit_groups'].append(group.name) 
                if categorygroup.play:
                    self.response['play_groups'].append(group.name) 
                if categorygroup.review:
                    self.response['review_groups'].append(group.name) 
            
        return self.template('/edit-category.pt', theme='AdminPanel')

        
        
        
        
        
        
        
        
        
        
        
        
Beispiel #15
0
def d2l_login_layer(self):
    if Validate.bool(self.settings('d2l_on','false')) and not Validate.bool(self.request.params.get('local','0')):
        self.response['category'] = self.request.params.get('category','')
        return self.template('login.pt', theme='D2L')
    return None
Beispiel #16
0
    def edit_groups(self):
        self.response['email'] = self.request.params.get('edit.find.user','')
        self.response['user'] = Users.by({'email':self.response['email']}).first()
        self.response['editing_group'] = None

        # add/remove users from groups
        if 'edit.user.group.add.submit' in self.request.params:
            id = self.request.params.get('edit.user.group.add','')
            group = Groups.by(id).first()
            self.response['user'].groups.append(Groups.by(id).first())
            transaction.commit()
            self.response['message'] = "Added user to group"
            self.response['message_class'] = "info"
            self.response['editing_group'] = Groups.by(id).first()
            self.response['user'] = Users.by({'email':self.response['email']}).first()
            
        if 'edit.user.group.remove.submit' in self.request.params:
            id = self.request.params.get('edit.user.group.remove','')
            self.response['user'].groups.remove(Groups.by(id).first())
            transaction.commit()
            self.response['message'] = "Removed user from group"
            self.response['message_class'] = "info"
            self.response['user'] = Users.by({'email':self.response['email']}).first()
            
        if 'edit.group.find.submit' in self.request.params:
            id = self.request.params.get('edit.group.find','')
            self.response['editing_group'] = Groups.by(id).first()
            
        if 'edit.group.edit.submit' in self.request.params:
            id = self.request.params.get('edit.group.edit.id','')
            group = Groups.by(id).first()
            group.name = self.request.params.get('edit.group.edit.name','No name')
            group.description = self.request.params.get('edit.group.edit.description','No Description')
            group.play = Validate.bool(self.request.params.get('edit.group.edit.play', False))
            group.edit = Validate.bool(self.request.params.get('edit.group.edit.edit', False))
            group.review = Validate.bool(self.request.params.get('edit.group.edit.review', False))
            cats = []
            for cid in self.request.params.getall('edit.group.edit.categories'):
                cats.append(Categories.by(int(cid)).first())
            group.categories = cats
            
            transaction.commit()
            self.response['editing_group'] = Groups.by(id).first()
            self.response['message'] = "Edit successful"
            self.response['message_class'] = "info"
            
        if 'edit.group.new.submit' in self.request.params:
            i = Groups.newest().id + 1
            DBSession.add(Groups(name='New Group' + str(i)))
            transaction.commit()
            self.response['editing_group'] = Groups.newest()
            self.response['message'] = "Added new group"
            self.response['message_class'] = "info"
            
        if 'edit.group.delete.submit' in self.request.params:
            id = int(self.request.params.get('edit.group.find','0'))
            if id not in [1,2,3]:
                try:
                    group = Groups.by(id).first()
                    DBSession.delete(group)
                    transaction.commit()
                    self.response['message'] = "Deleted group"
                    self.response['message_class'] = "info"
                except exc.SQLAlchemyError:
                    self.response['message'] = "You can't delete this group.  It has user and category dependencies."
            else:
                self.response['message'] = "You can't delete this permanent group"
            
        self.response['groups'] = Groups.all()
        self.response['categories'] = Categories.all()
        
        return self.template('/edit-groups.pt', theme='AdminPanel')
Beispiel #17
0
    def edit_groups(self):
        lookup = self.request.params.get('edit.user.find','')
        self.response['email'] = self.request.params.get('edit.user.find.email','')
        self.response['user'] = Users.by({'email':self.response['email']}).first()
        if self.response['user'] and lookup:
            self.notify('User found')
        if self.response['email'] and not self.response['user'] and lookup:
            self.notify('No user found',warn=True)
        self.response['editing_group'] = None

        # add/remove users from groups
        if 'edit.user.group.add.submit' in self.request.params:
            id = self.request.params.get('edit.user.group.add','')
            group = Groups.by(id).first()
            self.response['user'].groups.append(Groups.by(id).first())
            transaction.commit()
            self.notify('Added user to group')
            self.response['editing_group'] = Groups.by(id).first()
            self.response['user'] = Users.by({'email':self.response['email']}).first()
            
        if 'edit.user.group.remove.submit' in self.request.params:
            id = self.request.params.get('edit.user.group.remove','')
            self.response['user'].groups.remove(Groups.by(id).first())
            transaction.commit()
            self.notify('Removed user from group')
            self.response['user'] = Users.by({'email':self.response['email']}).first()
            
        if 'edit.group.find.submit' in self.request.params:
            id = self.request.params.get('edit.group.find','')
            self.response['editing_group'] = Groups.by(id).first()
            
        if 'edit.group.edit.submit' in self.request.params:
            id = self.request.params.get('edit.group.edit.id','')
            group = Groups.by(id).first()
            group.name = self.request.params.get('edit.group.edit.name','No name')
            group.description = self.request.params.get('edit.group.edit.description','No Description')
            group.play = Validate.bool(self.request.params.get('edit.group.edit.play', False))
            group.edit = Validate.bool(self.request.params.get('edit.group.edit.edit', False))
            group.review = Validate.bool(self.request.params.get('edit.group.edit.review', False))
            cats = []
            for cid in self.request.params.getall('edit.group.edit.categories'):
                cats.append(Categories.by(int(cid)).first())
            group.categories = cats
            
            transaction.commit()
            self.response['editing_group'] = Groups.by(id).first()
            self.notify('Changes saved!')
            
        if 'edit.group.new.submit' in self.request.params:
            i = Groups.newest().id + 1
            DBSession.add(Groups(name='New Group' + str(i)))
            transaction.commit()
            self.response['editing_group'] = Groups.newest()
            self.notify('Added group!')
            
        if 'edit.group.delete.submit' in self.request.params:
            id = int(self.request.params.get('edit.group.find','0'))
            if id not in [1,2,3]:
                try:
                    group = Groups.by(id).first()
                    DBSession.delete(group)
                    transaction.commit()
                    self.notify('Removed group!')
                except exc.SQLAlchemyError:
                    self.notify("You can't delete this group.  It has user and category dependencies.",warn=True)
            else:
                self.notify("Can't remove permanent group!",warn=True)
            
        self.response['groups'] = Groups.all()
        self.response['categories'] = Categories.all()
        
        return self.template('/edit-groups.pt', theme='AdminPanel')