示例#1
0
 def post(self):
     status = self.get_argument("statustext", None)
     if not status: raise tornado.web.HTTPError(405)
     pubdate = time.strftime('%y-%m-%d %H:%M', time.localtime())
     redpubdate = pubdate[4:] if pubdate[3] == '0' else pubdate[3:]
     user_id = self.current_user.id
     status_id = self.db.execute(
         "insert into fd_Status (user_id, "
         " status, pubdate) values (%s,%s,%s)", user_id, status, pubdate)
     #redis
     if status_id:
         actdict = {'time': redpubdate, 'status': status}
         addresult = add_activity(self.rd, user_id, status_id, 1, actdict)
         if addresult:
             self.write(''.join([
                 encode(str(status_id)), ',',
                 self.avatar('m', self.current_user.id,
                             self.current_user.uuid_), ',',
                 self.br(
                     self.at(
                         linkify(
                             status,
                             extra_params="target='_blank' rel='nofollow'"))
                 )
             ]))
         else:
             self.write("Something wrong...")
示例#2
0
def register(request):
    '''
  Handle a Post request with the following information:
  login, password, email
  '''
    #parameter retrieval
    login = request.POST['registerLogin']
    password = request.POST['registerPassword']
    email = request.POST['registerEmail']

    #parameter validation
    loginIsValid = re.match('[\w0-9]*',
                            login) and len(login) >= 3 and len(login) < 16
    passwordIsValid = len(password) >= 6
    #TODO check with number
    emailIsValid = re.match('[\w.]*@\w*\.[\w.]*', email)

    #encrypt the password with the sha1 function
    password = encode(password)
    logger.info(login + ' ' + password + ' ' + email)

    if loginIsValid and passwordIsValid and emailIsValid:
        return processFormInformation(login, password, email, request)
    else:
        #todo, separate error message on login pass
        message = 'incorect information on the register form login:'******' password:'******' email: ' + str(
            bool(emailIsValid))
        return render_to_response('index.html', {'message': message},
                                  context_instance=RequestContext(request))
def register(request) :
  '''
  Handle a Post request with the following information:
  login, password, email
  '''
  #parameter retrieval
  login=request.POST['registerLogin']
  password=request.POST['registerPassword']
  email=request.POST['registerEmail']
  
  
  #parameter validation
  loginIsValid= re.match('[\w0-9]*',login) and len(login) > 3 and len(login) < 16
  passwordIsValid=len(password) >= 6 
  #TODO check with number
  emailIsValid=re.match('[\w.]*@\w*\.[\w.]*',email)
  
  #encrypt the password with the sha1 function
  password=encode(password)
  logger.info(login+' '+password+' '+email)
  
  if loginIsValid and passwordIsValid and emailIsValid :
     return processFormInformation(login,password,email,request)     
  else :
  #todo, separate error message on login pass
    message='incorect information on the register form login:'******' password:'******' email: '+ str(bool(emailIsValid))
    return render_to_response('index.html', {'message': message},context_instance=RequestContext(request))  
def sendActivationMail(login,email) :   
  shaSource= login + email
  code=encode(shaSource)
  subject='Activation mail for WhatNow!'
  message= 'Please follow this link to activate your account'
  message+= '\n'+settings.ACTIVATION_LINK_BASE_URL+code
  sendMail(subject,message,email)
  return code
示例#5
0
def sendActivationMail(login, email):
    shaSource = login + email
    code = encode(shaSource)
    subject = 'Activation mail for Kuestions!'
    message = 'Please follow this link to activate your account'
    message += '\n' + settings.ACTIVATION_LINK_BASE_URL + code
    sendMail(subject, message, email)
    return code
示例#6
0
def createUser(userName):
  u = User(login=userName,email='*****@*****.**',password=encode('123123'))
  u = u.create()
  u.isActivated=True
  
  #allocate ramdom profile image
  number=random.randrange(1, 30)
  u.picture='profile/'+str(number)+'.jpg'
  u.update()
def openSession(request, user):
    t = loader.get_template('index.html')
    if not user.sessionId or user.sessionId.startswith('XXX'):
        print 'trying to open session for ', user.login
        user.sessionId = encode(user.login + user.email + str(uuid.uuid1()))
        user.update()
    else:
        print 'returning the existing opened session'
    response = HttpResponseRedirect("/")
    response.set_cookie(userauth.COOKIE_KEY, user.sessionId)
    return response
def openSession(request,user) :
  t = loader.get_template('index.html')
  if not user.sessionId or user.sessionId.startswith('XXX'):
    print 'trying to open session for ',user.login
    user.sessionId= encode(user.login+user.email+str(uuid.uuid1()))
    user.update()
  else :
    print 'returning the existing opened session'
  response= HttpResponseRedirect("/");
  response.set_cookie(userauth.COOKIE_KEY, user.sessionId)
  return response
示例#9
0
 def post(self):
     statusid = self.get_argument("statusid",None)
     statuscontent = self.get_argument("status",None)
     user_id = self.current_user.id
     if statusid and statuscontent and statuscontent != "":
         statusid = decode(statusid)
         status_user = self.db.get("select user_id from fd_Status where id = %s", statusid)
         if not status_user or status_user.user_id != user_id:
             raise tornado.web.HTTPError(404)
         self.db.execute("update fd_Status set status = %s "
                 "where id = %s", statuscontent, statusid)
         status_key = "status:%s:%s" % (user_id, statusid)
         actdict = {'status':statuscontent}
         if self.rd.hmset(status_key, actdict):
             self.redirect("/status/%s" % encode(statusid))
示例#10
0
def openSession(request,user) :
  print 'trying to open session for ',user.login
  t = loader.get_template('index.html')
  sessionExpire = getTomorowDatetime()
  #print sessionExpire
  field=DateTimeField()
  #field._to_
  #user.sessionExpire=sessionExpire
  user.sessionId= encode(user.login+user.email+str(sessionExpire)+str(uuid.uuid1()))
  user.update()

  #Todo add an expiration date!
  response= HttpResponseRedirect("/");
  response.set_cookie(userauth.COOKIE_KEY, user.sessionId)
  return response
示例#11
0
def createInitialUserList():
  username = ''
  profileImgCount = 1
  f = open('/Users/macuser/Kuestions/kuestionsWS/userlist')
  for line in f:
    username = line.replace('\n', '')
    u = User(login=username,email='*****@*****.**',password=encode('123123'))
    u = u.create()
    u.isActivated=True
    
    #allocate ramdom profile image
    u.picture='profile/'+str(profileImgCount)+'.jpg'
    profileImgCount = profileImgCount + 1
    u.update()
  
  f.close()
示例#12
0
 def post(self):
     noteid = self.get_argument("id",None)
     notetype = self.get_argument("notetype",None)
     notetitle = self.get_argument("notetitle",None)
     notecontent = self.get_argument("notecontent",None)
     #status_:{0:public,1:private,2:delted
     rednotecontent = notecontent
     if len(notecontent) > 150:
         rednotecontent = notecontent[:140] + " ..."
     status_ = int(notetype)
     user_id = self.current_user.id
     rev_user = get_namedomainuuid_by_id(self.db,self.rd,str(user_id))
     pubdate = time.strftime('%y-%m-%d %H:%M', time.localtime())
     if noteid:
         noteid = decode(noteid)
         note_user = self.db.get("select user_id from fd_Note where id = %s", noteid)
         if not note_user or note_user.user_id != user_id:
             raise tornado.web.HTTPError(404)
         self.db.execute("update fd_Note set title = %s, note = %s,"
                 "status_ = %s where id = %s", notetitle, notecontent, status_, noteid)
         rev_num = int(self.db.get("select max(rev_num) as rev_num from fd_NoteHistory where note_id = %s", noteid).rev_num)
         self.db.execute("insert into fd_NoteHistory(note_id,title,note,rev_num,rev_user_id,"
                 "rev_user_name,rev_user_domain,revdate) values (%s,%s,%s,%s,%s,%s,%s,%s)", noteid, notetitle,
                 notecontent, rev_num+1, user_id, rev_user[0], rev_user[1], pubdate)
         note_key = "note:%s:%s" % (user_id, noteid)
         actdict = {'title':notetitle, 'content':rednotecontent, 'status':status_}
         if self.rd.hmset(note_key, actdict):
             self.write("right")
         else:
             self.write("wrong")
     else:
         redpubdate = pubdate[4:] if pubdate[3] == '0' else pubdate[3:]
         note_id = self.db.execute("insert into fd_Note (user_id, title, "
                 "note, pubdate, status_) values (%s,%s,%s,%s,%s)", user_id,
                 notetitle, notecontent, pubdate, status_)
         if note_id:
             self.db.execute("insert into fd_NoteHistory(note_id,title,note,rev_num,rev_user_id,"
                     "rev_user_name,rev_user_domain,revdate) values (%s,%s,%s,%s,%s,%s,%s,%s)", note_id, notetitle,
                     notecontent, 1, user_id, rev_user[0], rev_user[1], pubdate)
             actdict = {'time':redpubdate, 'title':notetitle, 
                     'content':rednotecontent, 'status':status_}
             addresult = add_activity(self.rd, user_id, note_id, 2, actdict)
             if addresult:
                 self.write(encode(str(note_id)))
                 #self.write("right")
             else:
                 self.write("wrong")
示例#13
0
 def post(self):
     status = self.get_argument("statustext",None)
     if not status: raise tornado.web.HTTPError(405)
     pubdate = time.strftime('%y-%m-%d %H:%M', time.localtime())
     redpubdate = pubdate[4:] if pubdate[3] == '0' else pubdate[3:]
     user_id = self.current_user.id
     status_id = self.db.execute("insert into fd_Status (user_id, "
                 " status, pubdate) values (%s,%s,%s)", user_id, 
                 status, pubdate)
     #redis
     if status_id:
         actdict = {'time':redpubdate, 'status':status}
         addresult = add_activity(self.rd, user_id, status_id, 1, actdict)
         if addresult:
             self.write(''.join([encode(str(status_id)), ',', self.avatar('m',self.current_user.id,self.current_user.uuid_),',', self.br(self.at(linkify(status, extra_params="target='_blank' rel='nofollow'")))]))
         else:
             self.write("Something wrong...")
示例#14
0
 def post(self):
     statusid = self.get_argument("statusid", None)
     statuscontent = self.get_argument("status", None)
     user_id = self.current_user.id
     if statusid and statuscontent and statuscontent != "":
         statusid = decode(statusid)
         status_user = self.db.get(
             "select user_id from fd_Status where id = %s", statusid)
         if not status_user or status_user.user_id != user_id:
             raise tornado.web.HTTPError(404)
         self.db.execute(
             "update fd_Status set status = %s "
             "where id = %s", statuscontent, statusid)
         status_key = "status:%s:%s" % (user_id, statusid)
         actdict = {'status': statuscontent}
         if self.rd.hmset(status_key, actdict):
             self.redirect("/status/%s" % encode(statusid))
示例#15
0
def signin(request) :
  login=request.POST['login']
  password=request.POST['password']
  user=User(login=login)
  user=user.findByLogin()
  password=encode(password)
  if login=='' or password=='' :
    message='Please enter a login and a password'
  elif not user :
    message = 'This account does not exist'
  elif not user.isActivated :
    message= 'This account has not been activated yet'
  elif not user.password == password :
    message= 'wrong login/password combination'
  else : #every thing went fine, the session can be open
    return openSession(request,user)
  #return a response in case an error occurred
  return render_to_response('index.html', {'message': message},context_instance=RequestContext(request))
示例#16
0
def signin(request) :
  login=request.POST['login']
  password=request.POST['password']
  user=User(login=login)
  user=user.findByLogin()
  password=encode(password)
  if login=='' or password=='' :
    message='Please enter a login and a password'
  elif not user :
    message = 'This account does not exist'
  elif not user.isActivated :
    message= 'This account has not been activated yet'
  elif not user.password == password :
    message= 'wrong login/password combination'
  else : #every thing went fine, the session can be open
    return openSession(request,user)
  #return a response in case an error occurred
  return render_to_response('index.html', {'message': message},context_instance=RequestContext(request))
示例#17
0
文件: doc.py 项目: alexzhan/dormforge
    def post(self):
        template_values = {}
        title = self.get_argument("title", None)
        summary = self.get_argument("summary", None)
        tag = self.get_argument("tag", None)
        secret = self.get_argument("secret", None)
        endocid = self.get_argument("docid", None)
        oldtag = self.get_argument("oldtag", None)
        errors = 0
        title_error = 0
        title_error_messages = ['',
                u'请输入标题',
                ]
        if not endocid:
            name = self.get_argument("doc.name", None)
            content_type = self.get_argument("doc.content_type", None)
            path = self.get_argument("doc.path", None)
            md5 = self.get_argument("doc.md5", None)
            size = self.get_argument("doc.size", None)
        if not title or len(title) == 0:
            errors = errors + 1
            title_error = 1
            template_values['title_error'] = title_error
            template_values['title_error_message'] = title_error_messages[title_error]
        else:
            doc_error = 0
            doc_error_messages = ['',
                    u'请选择文档',
                    u'暂时不支持该文档格式',
                    u'文档不能大于20M',
                    u"该文档已被上传过",
                    ]
            if not endocid:
                if not (name and path and md5 and size):
                    errors = errors + 1
                    doc_error = 1
                else:
                    if name.split(".").pop().lower() not in ["doc", "docx", "ppt", "pptx", "pdf", "xls"]:
                        os.remove(path)
                        errors = errors + 1
                        doc_error = 2
                    else:
                        if int(size) > 1024*1024*20:
                            os.remove(path)
                            errors = errors + 1
                            doc_error = 3
                        else:
                            predoc = self.db.get("select * from fd_Doc where md5 = %s and status_ = 0", md5)
                            if predoc:
                                os.remove(path)
                                errors = errors + 1
                                doc_error = 4
                            else:
                                usrpath = u"/data/static/usrdoc/%s/" % self.current_user.id
                                staticpath = u"/work/Dormforge/static/usrdoc/%s/" % self.current_user.id
                                if not os.path.exists(usrpath):
                                    os.makedirs(usrpath)
                                if not os.path.exists(staticpath):
                                    os.makedirs(staticpath)
                                docid = "".join([path.split("/").pop(), str(time.time()).split(".")[0]])
                                doctype = name.split(".").pop().lower()
                                usrdoc = ''.join([usrpath, docid, '.', doctype])
                                shutil.move(path, usrdoc)
                                if name.split(".").pop().lower() != 'pdf':
                                    usrpdf = ''.join([usrpath, docid, ".pdf"])
                                    usrjpg = ''.join([staticpath, docid, ".jpg"])
                                    usrswf = ''.join([staticpath, docid, ".swf"])
                                    if os.path.exists("/opt/libreoffice3.5/program/python"):
                                        os.system("/opt/libreoffice3.5/program/python /work/Dormforge/util/DocumentConverter.py %s %s" % (usrdoc, usrpdf))
                                    else:
                                        os.system("python /work/Dormforge/util/DocumentConverter.py %s %s" % (usrdoc, usrpdf))
                                    os.system("convert -sample 150x150 %s[0] %s" % (usrpdf, usrjpg))
                                    os.system("pdf2swf %s -o %s -f -T 9 -t -s storeallcharacters" % (usrpdf, usrswf))
                                    os.remove(usrpdf)
                                else:
                                    usrjpg = ''.join([staticpath, docid, ".jpg"])
                                    usrswf = ''.join([staticpath, docid, ".swf"])
                                    os.system("convert -sample 150x150 %s[0] %s" % (usrdoc, usrjpg))
                                    os.system("pdf2swf %s -o %s -f -T 9 -t -s storeallcharacters" % (usrdoc, usrswf))

            if doc_error != 0:
                template_values['doc_error'] = doc_error
                template_values['doc_error_message'] = doc_error_messages[doc_error]
            else:
                if endocid:
                    doc_sql = ["update fd_Doc set "]
                else:
                    if os.path.exists(usrjpg) and os.path.exists(usrswf):
                        doc_sql = ["insert into fd_Doc set doc_id = '%s',name = '%s',content_type = '%s',md5 = '%s', docsize = %s," % (docid,name.replace("'", "''").replace("%", "%%"),content_type,md5,int(size))]
                doc_sql.append("title = '%s'," % title.replace("'", "''").replace("%", "%%"))
                if summary:
                    doc_sql.append("summary = '%s'," % summary.replace("'", "''").replace("%", "%%"))
                if tag:
                    tag = tag.strip().replace(' ',',')
                    tag = tag.strip().replace(',',',')
                    tags = tag.split(",")
                    taglists = []
                    for t in tags:
                        if t in taglists:
                            continue
                        taglists.append(t)
                    newtag = " ".join(taglists)
                    if not (endocid and newtag == oldtag):
                        doc_sql.append("tags = '%s'," % newtag.replace("'", "''").replace("%", "%%"))
                pubdate = time.strftime('%y-%m-%d %H:%M', time.localtime())
                redpubdate = pubdate[4:] if pubdate[3] == '0' else pubdate[3:]
                doctype = 0
                if secret and secret == "on":
                    doctype = 1
                if endocid:
                    doc_sql.append("status_ = %s where id = %s" % (doctype, decode(endocid)))
                else:
                    doc_sql.append("user_id = %s,pubdate = '%s',status_ = %s" % (self.current_user.id,pubdate,doctype))
                doc_id = self.db.execute("".join(doc_sql))
                if tag:
                    if (not endocid) or (endocid and newtag != oldtag):
                        for t in taglists:
                            tag_id = self.db.get("select id from fd_Doctag where tag = %s", t)
                            if tag_id:
                                tag_id = tag_id.id
                            else:
                                tag_id = self.db.execute("insert into fd_Doctag (tag) values (%s)", t)
                            if endocid:
                                with_doc_id = decode(endocid)
                            elif doc_id:
                                with_doc_id = doc_id
                            dtag_id = self.db.execute("insert into fd_Dtag (doc_id,tag_id) values (%s,%s)", with_doc_id, tag_id)
                if endocid:
                    doc_key = "doc:%s:%s" % (self.current_user.id, decode(endocid))
                    actdict = {'status':doctype}
                elif doc_id:
                    actdict = {'time':redpubdate, 'docid':docid, 'status':doctype}#docid not doc_id
                if title:
                    actdict['title'] = title
                if summary:
                    actdict['summary'] = summary
                if endocid:
                    if self.rd.hmset(doc_key, actdict):
                        self.redirect("/doc/" + endocid)
                elif doc_id:
                    addresult = add_activity(self.rd, self.current_user.id, doc_id, 4, actdict)
                    if addresult:
                        self.redirect("/doc/" + encode(str(doc_id)))

        if errors != 0:
            if title:
                template_values['title'] = title
            if summary:
                template_values['summary'] = summary
            if tag:
                template_values['tag'] = tag
            self.render("editdoc.html", template_values=template_values)
示例#18
0
 def __encode_data(self):
     """
     私有方法加密密码
     :return: 密码密文
     """
     return encode(self.id) + '%%%' + encode(self.psw)