Beispiel #1
0
    def _authorize(self, username, password):
        errors = {'SUCCESS': '', 'ERROR': ''}  # status return

        username = str(username).strip()
        password = str(password).strip()

        # Is username SJSUID or email ???
        isSJSUID = username.replace(' ', '').isdigit()

        try:
            # Check if the user is present
            if isSJSUID:

                Validate({'SJSUID': username})

                self.session.execute(
                    """
					SELECT * FROM Student WHERE Student.`SJSUID` = %s;
					""", username)

                exist = self.session.fetchone()
                if exist and 'Email' in exist:
                    username = exist['Email']

            else:  # username is an email
                Validate({'Email': username})

                self.session.execute(
                    """
					SELECT * FROM Student WHERE Student.`Email` = %s;
					""", username)

                exist = self.session.fetchone()  # user is in database

            # Confirm stormpath account
            if exist:
                try:
                    # Stormpath raises error on failure
                    a = stormApp.authenticate_account(username,
                                                      password).account
                    if a.email:
                        errors['SUCCESS'] = '1'

                        return errors

                except Exception as e:
                    raise TypeError('Invalid username or password')

        except (TypeError, ValidatorException) as e:
            self._printWarning("%s", e)

            errors['SUCCESS'] = '0'
            errors['ERROR'] = str(e)

            return dict(errors)

        except Exception as e:
            self._printError("%s", e)
            return False
Beispiel #2
0
	def removeInterest(self, studentID, *interests):
		try:
			# Validate method arguments
			Validate({
				'SJSUID': studentID
			})

			uidStudent = self._getStudentUID(studentID)

			values = []
			# Build list of (studentID, InterestID)
			for interest in interests:
				#  Get interest unique id
				self.session.execute("""
					SELECT i.`InterestID`
						FROM Interest as i WHERE i.`Title` = %s;
					""", interest)

				interestID = self.session.fetchone()

				if not interestID:	# No interestID found == Unknown interestName
					raise TypeError("Unknown interest")
				else:
					interestID = interestID['InterestID']

				values.append((uidStudent, interestID))

				# Return false if no values to enter into DB
				if values:
					# Delete rows with (studentID, interestID)
					# NOTE: DELETE will have no action if not found
					self.session.executemany("""
						DELETE FROM StudentInterest 
							WHERE StudentInterest.`Student_fk` = %s
							AND StudentInterest.`Interest_fk` = %s;
						""", values)

					self.conn.commit()
					return True

				return False

		except (TypeError, ValidatorException) as e:
			self.conn.rollback()
			# Unknown interest name. No InterestID returned
			self._printWarning("%s", e)
 
			#
			# TODO:
			#	return message to frontend of unknown interestName not foun
			#	return to frontend high priority validation errors
			# 
			return e

		except (ValidatorException, Exception) as e:
			self.conn.rollback()
			self._printError("%s", e)
Beispiel #3
0
    def addAdvisor(self,
                   FirstName,
                   LastName,
                   Email,
                   Department,
                   MiddleName=None):
        try:
            # Validate arguments
            Validate({
                'FirstName': FirstName,
                'LastName': LastName,
                'Department': Department,
                'MiddleName': MiddleName,
                'Email': Email
            })

            # Check if this advisor (professor) already exists in DB
            self.session.execute(
                """
				SELECT * FROM Advisor as ad
					WHERE ad.`FirstName` = %s AND ad.`LastName` = %s
					AND ad.`Email` = %s AND ad.`Department` = %s;
				""", (FirstName, LastName, Email, Department))

            exist = self.session.fetchone()
            if not exist:
                # Insert advisor if not exists
                self.session.execute(
                    """
					INSERT INTO `Advisor` (`FirstName`, `MiddleName`,
						`LastName`, `Email`, `Department`) VALUES (%s, %s, %s, %s, %s);
					""", (FirstName, MiddleName, LastName, Email, Department))

                self.conn.commit()
                return True

            else:  # Advisor entity already exists
                raise TypeError("Advisor already registered")

        except (TypeError, ValidatorException) as e:
            self.conn.rollback()
            # Unknown studentID or organizationName was encountered
            self._printWarning("%s", e)

            #
            # TODO:
            #	return message to frontend of error
            #	return to frontend high priority validation errors
            #
            return e

        except Exception as e:
            self.conn.rollback()

            # A non-existing organization was specified!!!
            self._printError("%s", e)
Beispiel #4
0
    def authorArticle(self, studentID, organizationName, articleTitle,
                      articleContent):
        try:
            # Validate method arguments
            Validate({
                'SJSUID': studentID,
                'ArticleTitle': articleTitle,
                'ArticleContent': articleContent
            })

            # Get organization unique id
            uidOrganization = super(Officer,
                                    self)._getOrganizationUID(organizationName)

            # Get student unique id
            uidStudent = super(Officer, self)._getStudentUID(studentID)

            # Check active status of this officer
            active = self._isOfficerActive(uidStudent, uidOrganization)
            if not active:
                raise TypeError(
                    "Given studentID not allowed to author articles")

            else:  # Insert newsfeed article into DB
                self.session.execute(
                    """
					INSERT INTO NewsfeedArticle (`ArticleTitle`, `OrganizationID`, `ArticleContent`)
						VALUES (%s, %s, %s);
					""", (articleTitle.strip(), uidOrganization, articleContent.strip()))

                self.conn.commit()
                return True

            return False

        except (TypeError, ValidatorException) as e:
            self.conn.rollback()
            # Unknown studentID or organizationName was encountered
            self._printWarning("%s", e)

            #
            # TODO:
            #	return message to frontend of error
            #	return to frontend high priority validation errors
            #
            return e

        except Exception as e:
            self.conn.rollback()

            # A non-existing organization was specified!!!
            self._printError("%s", e)
Beispiel #5
0
	def commentArticle(self, studentID, studentComment, articleID):
		try:
			# Validate method arguments
			Validate({
				'SJSUID': studentID,
				'StudentComment': studentComment,
			})

			uidStudent = self._getStudentUID(studentID)

			# Get organization unique id indirectly from article
			self.session.execute("""
				SELECT nfa.`OrganizationID`
					FROM NewsfeedArticle as nfa WHERE nfa.`ArticleID` = %s;
				""", articleID)

			orgID = self.session.fetchone()
			if not orgID:
				raise TypeError("Unknown articleID")
			else:
				orgID = orgID['OrganizationID']

			# Verify that student is active member
			active = self._isStudentActiveMember(uidStudent, orgID)

			if active:	# Only active members can comment
				self.session.execute("""
					INSERT INTO Comment (`Article_fk`, `Author_fk`, `Content`)
						VALUES (%s, %s, %s);
					""", (articleID, uidStudent, studentComment))

				self.conn.commit()
				return True

			return False

		except (TypeError, ValidatorException) as e:
			self.conn.rollback()
			# Unknown studentID or articleID returned
			self._printWarning("%s", e)
 
			#
			# TODO:
			#	return message to frontend of unknown studentID and articleID
			#	return to frontend high priority validation errors
			# 
			return e

		except (ValidatorException, Exception) as e:
			self.conn.rollback()
			self._printError("%s", e)
Beispiel #6
0
	def quitOrganization(self, studentID, organizationName):
		try:
			# Validate method arguments
			Validate({
				'SJSUID': studentID,
				'OrganizationName': organizationName
			})

			uidStudent = self._getStudentUID(studentID)

			# Get organization unique ID
			uidOrganization = self._getOrganizationUID(organizationName)

			self.conn.commit()	# Being new transaction

			# Check if student active(1) member of organization
			activeMember = self._isStudentActiveMember(uidStudent, uidOrganization)			
		
			if activeMember: # Set organization member to inactive
				self.session.execute("""
					UPDATE MemberOf
						SET MemberOf.`Active` = '0' 
						WHERE MemberOf.`Student_fk` = %s AND MemberOf.`Organization_fk` = %s;
					""", (uidStudent, uidOrganization))
								
				self.conn.commit()
				return True

			else:	# Empty SQL return means either non-member or inactive
				self._printWarning("%s either inactive or not part of %s", studentID, organizationName)
				return True

			return False 	# 99.99% chance you will not hit this !!!

		except (TypeError, ValidatorException) as e:
			self.conn.rollback()
			# Unknown interest name. No InterestID returned
			self._printWarning("%s", e)
 
			#
			# TODO:
			#	return message to frontend of unknown interestName not foun
			#	return to frontend high priority validation errors
			# 
			return e

		except Exception as e:
			self.conn.rollback()
			
			# A non-existing organization was specified!!!
			self._printError("%s", e)
Beispiel #7
0
    def leaveOffice(self, studentID, organizationName):
        # Leaving officer position does not mean quitting organization
        try:
            # Validate method arguments
            Validate({
                'SJSUID': studentID,
                'OrganizationName': organizationName
            })

            # Get student unique id
            uidStudent = super(Officer, self)._getStudentUID(studentID)

            # Get organization unique id
            uidOrganization = super(Officer,
                                    self)._getOrganizationUID(organizationName)

            self.conn.commit()  # Being new transaction

            # Change officer status to inactive(0)
            self.session.execute(
                """
				UPDATE OfficerOf
					SET `Active` = '0'
					WHERE OfficerOf.`Student_fk` = %s AND OfficerOf.`Organization_fk` = %s;
				""", (uidStudent, uidOrganization))

            self.conn.commit()
            return True

        except (TypeError, ValidatorException) as e:
            self.conn.rollback()
            # Unknown studentID or organizationName was encountered
            self._printWarning("%s", e)

            #
            # TODO:
            #	return message to frontend of error
            #	return to frontend high priority validation errors
            #
            return e

        except Exception as e:
            self.conn.rollback()

            # A non-existing organization was specified!!!
            self._printError("%s", e)
Beispiel #8
0
	def editStudentInfo(self, studentID, **kwargs):
		try:
			# Validate arguments
			Validate({
				'SJSUID': studentID	
			})

			# Loop kwargs and do queries
			for key, value in kwargs.iteritems():
				if key == 'Email':
					self.__updateStudentEmail(studentID, value)

				# 
				# INSERT HERE IF ADDITIONAL STUDENT ATTRIBUTE EDIT FUNC
				# 

				else:	# Unknown key was passed to method
					raise TypeError("Student attribute not found")

			self.conn.commit()	# Commit transaction only after all changes applied
			return True

		except (TypeError, ValidatorException) as e:
			self.conn.rollback()
			# Unknown studentID or organizationName was encountered
			self._printWarning("%s", e)
 
			#
			# TODO:
			#	return message to frontend of error
			#	return to frontend high priority validation errors
			# 
			return e

		except Exception as e:
			self.conn.rollback()
			
			# A non-existing organization was specified!!!
			self._printError("%s", e)
Beispiel #9
0
    def _addStudent(self,
                    studentID,
                    studentEmail,
                    FirstName,
                    LastName,
                    Password,
                    MiddleName=None):
        errors = {'SUCCESS': '', 'ERROR': ''}  # status return

        try:
            # Validate method arguments
            Validate({
                'SJSUID': studentID,
                'FirstName': FirstName,
                'LastName': LastName,
                'MiddleName': MiddleName,
                'Email': studentEmail
            })

            # Check stormpath for existance of account
            stormAccount = stormApp.accounts.search({'email': studentEmail})

            if len(stormAccount) >= 1:  # Account exists
                raise TypeError('Please verify inputs')

            exist = self.__existingUser(studentEmail)  # Check if existing user

            if not exist:
                # Insert student entity
                self.session.execute(
                    """
					INSERT INTO `Student` (`SJSUID`, `Email`, `FirstName`, `LastName`,
						`MiddleName`) VALUES (%s, %s, %s, %s, %s);
					""", (studentID, studentEmail, FirstName, LastName, MiddleName))

                try:
                    # Create a new Stormpath Account.
                    account = stormApp.accounts.create({
                        'given_name': FirstName,
                        'middle_name': MiddleName,
                        'surname': LastName,
                        'email': studentEmail,
                        'password': Password
                    })

                    self.conn.commit()

                    # Everything is OK
                    errors['SUCCESS'] = '1'
                    return errors

                except Exception as e:
                    # Stormpath.accounts.create raises error on failure
                    self.conn.rollback()
                    raise TypeError(str(e))

            else:
                # Student entity already exists
                raise TypeError('Please verify inputs')

        except (TypeError, ValidatorException) as e:
            self.conn.rollback()

            self._printWarning("%s", e)

            errors['SUCCESS'] = '0'
            errors['ERROR'] = str(e)

            return dict(errors)

        except Exception as e:
            self.conn.rollback()

            self._printError("%s", e)
            return False
Beispiel #10
0
	def addInterest(self, studentID, *interests):
		try:
			# Validate method arguments
			Validate({
				'SJSUID': studentID
			})

			uidStudent = self._getStudentUID(studentID)

			values = []
			# Build list of (studentID, InterestID)
			for interest in interests:
				#  Get interest unique id
				self.session.execute("""
					SELECT i.`InterestID`
						FROM Interest as i WHERE i.`Title` = %s;
					""", interest)

				interestID = self.session.fetchone()

				if not interestID:	# No interestID found == Unknown interestName
					raise TypeError("Unknown interest")
				else:
					interestID = interestID['InterestID']

				# If duplicate entry exists, do not insert again else SQL IntegrityError
				self.session.execute("""
					SELECT * FROM StudentInterest as si
						WHERE si.`Student_fk` = %s AND si.`Interest_fk` = %s;
					""", (uidStudent, interestID))

				duplicate = self.session.fetchall()
				if not duplicate:
					values.append((uidStudent, interestID))
				
				else:	# Go on to next loop iteration
					continue

			self.conn.commit()	# Start a new transaction

			# Return false if no values to insert into DB
			if values:
				# Add all student's interest at once
				self.session.executemany("""
					INSERT INTO StudentInterest (`Student_fk`, `Interest_fk`)
						VALUES (%s, %s)
					""", values)

				self.conn.commit()
				return True

			return False

		except (TypeError, ValidatorException) as e:
			self.conn.rollback()
			# Unknown interest name. No InterestID returned
			self._printWarning("%s", e)
 
			#
			# TODO:
			#	return message to frontend of unknown interestName not foun
			#	return to frontend high priority validation errors
			# 
			return e

		except (ValidatorException, Exception) as e:
			self.conn.rollback()
			self._printError("%s", e)
Beispiel #11
0
	def joinOrganization(self, studentID, organizationName):
		try:
			# Validate method arguments
			Validate({
				'SJSUID': studentID,
				'OrganizationName': organizationName
			})

			# Get student unique ID
			uidStudent = self._getStudentUID(studentID)

			# Get organization unique ID
			uidOrganization = self._getOrganizationUID(organizationName)

			self.conn.commit()	# Being new transaction

			# Check if student already organization member
			self.session.execute("""
				SELECT * FROM MemberOf as mem
					WHERE mem.`Student_fk` = %s AND mem.`Organization_fk` = %s;
				""", (uidStudent, uidOrganization))

			data = self.session.fetchone()
			self.conn.commit()	# Being new transaction

			if not data:	# Add student to organization 
				self.session.execute("""
					INSERT INTO MemberOf (`Student_fk`, `Organization_fk`)
						VALUES (%s, %s);
					""", (uidStudent, uidOrganization))

				self.conn.commit()
				return True

			else:	# Check if student active(1) member of organization	
				activeMember = self._isStudentActiveMember(uidStudent, uidOrganization)

				if not activeMember : # Update organization member active status to active(1)

					# Inactive status may be a result of being blacklisted
					blacklisted = self._isStudentBlacklisted(uidStudent, uidOrganization)	
					if blacklisted:
						return False

					self.session.execute("""
						UPDATE MemberOf
							SET MemberOf.`Active` = '1' 
							WHERE MemberOf.`Student_fk` = %s AND MemberOf.`Organization_fk` = %s;
						""", (uidStudent, uidOrganization))
									
					self.conn.commit()
					return True

				else:	# Organization member already active	
					self._printWarning("%s in %s already active", studentID, organizationName)
					return True

			return False 	# 99.99% chance you will not hit this !!!

		except (TypeError, ValidatorException) as e:
			self.conn.rollback()
			# Unknown studentID or organizationName was encountered
			self._printWarning("%s", e)
 
			#
			# TODO:
			#	return message to frontend of error
			#	return to frontend high priority validation errors
			# 
			return e

		except Exception as e:
			self.conn.rollback()
			
			# A non-existing organization was specified!!!
			self._printError("%s", e)