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" }
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"}
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()
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 }
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" }
def decode(self, session_data): encoded_data = base64.decodestring(session_data) pickled, tamper_check = encoded_data[:-32], encoded_data[-32:] if md5_constructor(pickled + acconfig.SECRET_KEY).hexdigest() != tamper_check: raise SuspiciousOperation("User tampered with session cookie.") try: return pickle.loads(pickled) # Unpickling can cause a variety of exceptions. If something happens, # just return an empty dictionary (an empty session). except: return {}
def generateID(self, secret=acconfig.SECRET_KEY): "Returns session key that isn't being used." # The random module is seeded when this Apache child is created. # Use settings.SECRET_KEY as added salt. try: pid = os.getpid() except AttributeError: # No getpid() in Jython, for example pid = 1 while 1: session_key = md5_constructor("%s%s%s%s" % (randrange(0, MAX_SESSION_KEY), pid, time.time(), secret)).hexdigest() if not self.exists(session_key): break return session_key
def encode(self, session_dict): "Returns the given session dictionary pickled and encoded as a string." pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) pickled_md5 = md5_constructor(pickled + acconfig.SECRET_KEY).hexdigest() return base64.encodestring(pickled + pickled_md5)
def generateID(secret=None): if secret is None: secret=acconfig.SECRET_KEY key=md5_constructor("%s%s%s%s" % (randrange(0, 184467440737096L), 144, time.time(), secret)).hexdigest() return key