Exemple #1
0
	def register(self,acenv,conf):
		usersColl=acenv.app.storage.users
		email=replaceVars(acenv,conf["email"]).lower()
		if not (len(email)>5 and self.EMAIL_RE.match(email)):
			return {
				"@status":"error",
				"@error":"NotValidEmailAddress",
				"@message":"Suplied value is not a valid e-mail address"
			}
		if list(usersColl.find({"email":email})):
			return {
				"@status":"error",
				"@error":"EmailAdressAllreadySubscribed",
				"@message":"User already exists in the system"
			}
		key=generateID()
		d={
			"email":email,
			"password":md5_constructor(replaceVars(acenv,conf["password"])).hexdigest(),
			"role":replaceVars(acenv,conf.get("role",self.ROLE)),
			"approvalKey":key,
			"privileges":[]
		}
		if conf.has_key("data"):
			d.update(conf["data"].execute(acenv))
		id=usersColl.save(d,safe=True)
		return {
			"@status":"ok",
			"@id":id,
			"@approvalKey":key
		}
Exemple #2
0
	def register(self,acenv,conf):
		email=replaceVars(acenv,conf["email"])
		password=replaceVars(acenv,conf["password"])
		role=replaceVars(acenv,conf.get("role",self.ROLE))
		sql="select exists(select * from %s.emails where email='%s')"%(acconfig.dbschema,email)
		passwd=md5_constructor(password).hexdigest()
		key=generateID()
		#returns False if email is not registered yet
		if acenv.app.getDBConn().query(sql)["rows"][0][0]:
			return {
				"error":"EmailAdressAllreadySubscribed"
			}
		#XXX implement psycopg escaping!!!
		id="SELECT currval('%s.users_id_seq')"%(acconfig.dbschema)
		sql="""INSERT into %s.users
			(password,role)
		VALUES
			('%s', '%s');
		INSERT into %s.emails
			(email,_user,approval_key,approved,main)
		VALUES
			('%s', (%s), '%s', %s, %s)"""%(
			acconfig.dbschema,
			passwd,
			role,
			acconfig.dbschema,
			email,
			id,
			key,
			conf.get("approved",self.APPROVED),
			conf.get("approved",self.MAIN)
		)
		result=acenv.app.getDBConn().query(sql)
		acenv.requestStorage["approval_key"]=key
		return {"status":"ok"}
Exemple #3
0
	def setcookie(self,env,config):
		#if config[1]["action"].lower()=="set":
		d={"name":replaceVars(env,config["name"],fn=str), "value":replaceVars(env,config["value"])}
		if config.has_key("path"):
			d["path"]=replaceVars(env,config["path"])
		HTTP.setCookie(env,d)
		return {}
Exemple #4
0
	def login(self,acenv,conf):
		D=acenv.doDebug
		email=replaceVars(acenv,conf["email"])
		password=replaceVars(acenv,conf["password"])
		sql="select password,id,role from %s.users where id=(select _user from %s.emails where email='%s')"%(acconfig.dbschema,acconfig.dbschema,email)
		try:
			result=acenv.app.getDBConn().query(sql)
			result=dict(zip(result["fields"], result["rows"][0]))
		except IndexError:
			if D: acenv.error("Account not found")
			return {
				"@status":"error",
				"@error":"AccountNotFound"
			}
		if result['password']==md5_constructor(password).hexdigest():
			if D: acenv.info("Password is correct")
			if not acenv.sessionStorage:
				acenv.sessionStorage=MongoSession(acenv)
			if D: acenv.info("Setting ID=%s, email=%s and role=%s to session",result['id'],email,result['role'])
			acenv.sessionStorage["ID"]=result['id']
			acenv.sessionStorage["email"]=email
			acenv.sessionStorage["role"]=result['role']
			#is it necessary?
			acenv.sessionStorage["loggedIn"]=True
			#acenv.session["fake"]=False
			return {"@status":"ok"}
		else:
			if D: acenv.error("Password is not correct")
			return {
				"@status":"error",
				"@error":"WrongPassword"
			}
Exemple #5
0
	def copy(self,acenv,conf):
		#D=acenv.doDebug
		copyFrom=os.path.join(self.abspath,*replaceVars(acenv,conf["from"]).split("/"))
		copyTo=os.path.join(self.abspath,*replaceVars(acenv,conf["to"]).split("/"))
		if os.path.isfile(copyFrom) and not os.path.isfile(copyTo):
			shutil.copyfile(copyFrom, copyTo)
		return {"@status":"ok"}
Exemple #6
0
	def login(self,acenv,conf):
		D=acenv.doDebug
		email=replaceVars(acenv,conf["email"]).lower()
		usersColl=acenv.app.storage.users
		try:
			user=list(usersColl.find({
				"email":email,
				'$or': [
					{'suspended': {'$exists': False}},
					{'suspended': False}
				]
			}))[0]
		except IndexError:
			if D: acenv.error("Account not found")
			return {
				"@status":"error",
				"@error":"AccountNotFound"
			}
		password=replaceVars(acenv,conf["password"])
		if user['password']==md5_constructor(password).hexdigest():
			if D: acenv.info("Password is correct")
			if not acenv.sessionStorage:
				acenv.sessionStorage=MongoSession(acenv)
			if D: acenv.info("Setting session as:\n	%s",user)
			user["ID"]=str(user.pop("_id"))
			user["loggedIn"]=True
			acenv.sessionStorage.data=user
			#print "login sess data ",acenv.sessionStorage.data
			return {"@status":"ok"}
		else:
			if D: acenv.error("Password is not correct")
			return {
				"@status":"error",
				"@error":"WrongPassword"
			}
Exemple #7
0
	def colaslist(self,env,conf):
		query=replaceVars(env,conf["query"],self.none2null)
		result=self.CONNECTIONS[conf.get("server","default")].query(query)
		ret=[]
		for i in result["rows"]:
			ret.append(i[0])
		return ret
Exemple #8
0
	def generate(self,env,conf):
		#D=env.doDebug
		command=conf["command"]
		if command=="md5":
			value=replaceVars(env,conf["params"]["value"])
			return md5_constructor(value).hexdigest()
		return generateID()
Exemple #9
0
	def delete(self,acenv,conf):
		D=acenv.doDebug
		path=self.abspath+replaceVars(acenv,conf["path"])
		if (os.path.exists(path)):
			if (os.path.isfile(path)):
				os.remove(path)
			else:
				shutil.rmtree(path)
		return {"@status":"ok"}
Exemple #10
0
 def generate(self, env, config):
     if config.get("command"):
         return self.execute(env, config)
     D = env.doDebug
     if D:
         env.debug("START default:generation with %s", config)
     ret = replaceVars(env, config["string"], str)
     if D:
         env.debug("END default component generation with: '%s...'", ret)
     return ret
Exemple #11
0
	def generate(self,acenv,conf):
		command=conf["params"]["exec"]
		content=replaceVars(acenv,content)
		try:
			p=subprocess.Popen(command.split(), bufsize=2024, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
		except OSError:
			raise Error("SubProcessError","%s failed with error code %s"%(command,res))
		p.stdin.write(conf["content"])
		p.stdin.close()
		return start.stdout.read()
Exemple #12
0
	def generate(self,acenv,conf):
		D=acenv.doDebug
		if D:acenv.debug("START Email.send with: %s",conf)
		content=conf["content"]
		headers={}
		params=conf["params"]
		for h in params:
			headers[h]=replaceVars(acenv,params[h])
			if type(headers[h]) is list:
				headers[h]=", ".join(headers[h])
		if D:acenv.debug("Computed headers: %s",headers)
		content=replaceVars(acenv,content)
		try:
			mail.send(headers,content)
		except Exception,e:
			return {
				"@status":"error",
				"@error":type(e),
				"@message":str(e)
			}
Exemple #13
0
	def generate(self, acenv, config):
		D=acenv.doDebug
		if D:
			acenv.info("Component: 'FS'")
			acenv.info("Executing command: '%s'", config["command"])
		c=config["params"]
		conf={}
		for i in c:
			conf[i]=replaceVars(acenv, c[i], lambda x: type(x) is generator and x or str(x))
		if D:
			if not conf.get("path"):
				acenv.error("path not suplied")
			elif conf["path"][0]!='/':
				acenv.error("missning '/' character at the begginig of 'path' attribute")
		try:
			if type(conf["content"]) is not generator:
				conf["content"]=replaceVars(acenv,config["content"])
		except:
			pass
		conf["fullPath"]=os.path.join(self.abspath,*conf["path"].split("/"))
		return self.__getattribute__(config["command"])(acenv,conf)
Exemple #14
0
	def query(self,env,conf):
		D=env.doDebug
		P=env.doProfiling
		if D: env.debug("START DB:query with: conf='%s'",conf)
		query=replaceVars(env,conf["query"],self.none2null)
		if type(query) is list:
			query="".join(map(str,query))
		if D: env.debug("replaceVars returned '%s'",query)
		if P:
			t=time.time()
		result=self.CONNECTIONS[conf.get("server","default")].query(query)
		if P:
			env.profiler["dbtimer"]+=time.time()-t
			env.profiler["dbcounter"]+=1
		if D: env.debug("database returned %s",result)
		if result and len(result["rows"]):
			if D: env.debug("Creating list of ordered dicts.")
			#TODO get relations keys and return them as attributes
			first=True #for debugging purposes
			ret=[]
			fields=result["fields"]
			cdata=conf["cdata"]
			for row in result["rows"]:
				r={}
				#TODO optimize returning row and value
				for i in xrange(len(row)):
					if type(row[i]) is str and fields[i] in cdata:
						s="<![CDATA["+row[i].replace("]]>","]]>]]&gt;<![CDATA[")+"]]>"
					else:
						s=row[i]
					r[fields[i]]=s
					#nodes.append((fields[i],s))
				first=False
				ret.append(r)
			if not conf["return"]=="list" and len(ret) is 1:
				#row
				if D:env.debug("END DB:query with one row: %s",ret[0])
				return ret[0]
				#if len(ret[2]) is 1:
					#value
				#	return Object(ret[2][0][2][0])
			else:
				if D:env.debug("END DB:query with multiple rows: %s",ret)
				return ret
		else:
			if D:env.debug("END DB:query with no rows.")
			return {}
		return ret
Exemple #15
0
	def redirect(self,env,config):
		if env.doDebug: env.info("Requested redirect to <a href=\"#\">%s</a>"%(replaceVars(env,config["location"])))
		env.doRedirect=True
		env.outputHeaders.append(("Location",replaceVars(env,config["location"],fn=str)))
		return {}
Exemple #16
0
	def find(self,acenv,config,count=False,one=False):
		D=acenv.doDebug
		P=acenv.doProfiling
		params=config["params"]
		coll=acenv.app.storage[params.get("coll",self.DEFAULT_COLL)]
		p={
			"spec":params.get("where", config["content"]).execute(acenv)
		}
		if D:acenv.debug("Finding objects matching:\n%s",p["spec"])
		for i in params:
			#FIXME lame exception
			if type(params[i]) is list and i!='sort':
				params[i]=replaceVars(acenv,params[i])
		try:
			p["fields"]=params["fields"]
		except: pass
		if not one:
			try:
				p["skip"]=int(params["skip"])
			except: pass
			try:
				p["limit"]=int(params["limit"])
			except: pass
			try:
				p["sort"]=params["sort"]
			except:
				pass
		if P: t=time.time()
		if count:
			ret=coll.find(**p).count()
			if D:acenv.debug("Objects matching count is: %s",ret)
		elif one:
			ret=list(coll.find(**p).limit(-1))
			ret=ret and ret[0] or None
		else:
			ret=list(coll.find(**p))
			if ret and params.has_key("sort") and len(params["sort"]) is 1:
				sortBy=params['sort'][0][0]
				if ret[0].has_key(sortBy)\
				and type(ret[0][sortBy]) in STR_TYPES\
				or ret[-1].has_key(sortBy)\
				and type(ret[-1][sortBy]) in STR_TYPES:
					if D:acenv.debug("Doing additional Python sort")
					def sortedKey(k):
						try:
							return k[sortBy].lower()
						except:
							return ''
					pars={"key":sortedKey}
					if params['sort'][0][1] is pymongo.DESCENDING:
						pars["reverse"]=True
					ret=sorted(ret, **pars)
		if P:
			acenv.profiler["dbtimer"]+=time.time()-t
			acenv.profiler["dbcounter"]+=1
		if ret:
			#if len(ret) is 1:
			#	if D:acenv.debug("END Mongo.find with %s",ret[0])
			#	return ret[0]
			if D:acenv.debug("END Mongo.find with %s",ret)
			return ret
		else:
			if count:
				if D:acenv.debug("END Mongo.count with 0")
				return ret
			if D:acenv.debug("END Mongo.find with no object")
			return []
Exemple #17
0
	def num2words(self,env,config):
		return n2w.liczba_slownie(replaceVars(env,config["number"]))
Exemple #18
0
	def list(self,acenv,conf):
		return List(replaceVars(acenv, conf["content"]))