 					clientConfig:
 						provider: RocketChat.settings.get("#{service.key}_provider")
 
-				Accounts.saml.settings.generateUsername = RocketChat.settings.get("#{service.key}_generate_username")
+				Accounts.saml.settings.generateUsername = RocketChat.settings.get("#{service._id}_generate_username")
+				privateKeyFilePath = RocketChat.settings.get("#{service._id}_private_key_file_path")
+				publicCertFilePath = RocketChat.settings.get("#{service._id}_public_cert_file_path")
+
+				try
+					privateKey = fs.readFileSync(privateKeyFilePath).toString()
+					privateCert = fs.readFileSync(publicCertFilePath).toString()
+				catch err
+					console.warn "Can't configure key or cert for SAML, signing and encryption will not work"
+					console.warn "Error was: #{err.message}"
+					privateKey = false
+					privateCert = false
 
 				Accounts.saml.settings.providers.push
 					provider: data.clientConfig.provider
 					entryPoint: RocketChat.settings.get("#{service.key}_entry_point")
 					issuer: RocketChat.settings.get("#{service.key}_issuer")
 					cert: RocketChat.settings.get("#{service.key}_cert")
+					privateCert: privateCert
+					privateKey: privateKey
 
 				ServiceConfiguration.configurations.upsert {service: serviceName.toLowerCase()}, $set: data
 			else

	updateServices()

Meteor.startup ->
	if RocketChat.settings.get(/^(SAML_Custom)_[a-z]+$/i)?.length is 0
		Meteor.call 'addSamlService', 'Default'

fs = Npm.require('fs')

logger = new Logger 'steffo:meteor-accounts-saml',
	methods:
		updated:
