def create(self,request,msg_recv,msg_resp,authentication_pass): """ """ try: #process user = authenticate( username=msg_recv.username, password=msg_recv.password ) if user is None: #Login baned logger.debug("----------Failed------------%s,%s"%(msg_recv.username,msg_recv.password)) msg_resp.agentID = DEFAULT_ERROR_ID msg_resp.isSuccessful = False msg_resp.reason = "Wrong username or password" else: #Login ok logger.debug("----------Successful------------%s,%s"%(msg_recv.username,msg_recv.password)) msg_resp.agentID = user.get_profile().agentID msg_resp.isSuccessful = True msg_resp.reason = "Login Successful" return msg_resp except Exception,err: import pdb; print pdb.traceback logger.error("Login from Client Error %s "%err)
def create(self,request,msg_recv,msg_resp,authentication_pass): """ """ try: uploadFileObj = request.FILES #TODO: whether the agentID is right if authentication_pass and uploadFileObj is not None: file_obj = InputProcessing.FilesCalculate() #Process upload file fileName = receiveFile(uploadFileObj) msg_resp.isSuccessful, msg_resp.result, msg_resp.reason \ = file_obj.fileQuery( fullfilename = fileName, ) else: msg_resp.isSuccessful = False msg_resp.result = "None" msg_resp.reason = "Wrong Agent ID" return msg_resp except Exception,err: import pdb; print pdb.traceback logger.error("File Search Error %s "%err)
def parseJsonToObject(dct,message_type): """ Get dct and message_type to create the object """ obj = message_type() for item in obj.__dct__: #TODO cannot solve subclass try: obj.__setattr__(item,dct[item]) except Exception,err: logger.error(err)
def send_mail(subject, message, recipient_list, **kwargs): auth_user, auth_password = choice(settings.EMAIL_POOL) loginfo(p='Send with ' + auth_user, label='send_mail') try: flag = _send_mail( subject, message, auth_user, recipient_list, auth_user=auth_user, auth_password=auth_password, **kwargs) except Exception as e: logger.error(e) flag = False return flag
def create_inactive_user(self,request, username,password,email, send_email=True, profile_callback=None, **kwargs): """ Create a new, inactive ``User``, generates a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. TODO: we will custom the USER """ #如果存在用户的话不必进行新建只需对权限表进行操作即可,否则新建用户 if User.objects.filter(email=email).count() == 0: new_user = User.objects.create_user(username, email, password) new_user.is_active = False new_user.save() registration_profile = self.create_profile(new_user) registration_profile.save() current_site = Site.objects.get_current() site_domain=current_site.domain if send_email: from django.core.mail import send_mail subject = render_to_string('registration/activation_email_subject.txt', {'site':get_current_site(request), 'username':username, 'password':password}) subject = ''.join(subject.splitlines()) message = render_to_string('registration/activation_email.txt', {'activation_key':registration_profile.activation_key, 'expiration_days':settings.ACCOUNT_ACTIVATION_DAYS, 'site':site_domain, 'username':username, 'password':password}) logger.error(message) send_mail(subject,message,settings.DEFAULT_FROM_EMAIL,[new_user.email]) else: new_user = User.objects.get(email=email) # 创建普通用户NORMALUSER Profile new_normalprofile = NormalProfile(userid = new_user) new_normalprofile.save() # 对用户权限写入数据库 new_authority = UserIdentity.objects.get(identity=NORMAL_USER) new_authority.auth_groups.add(new_user) new_authority.save() if profile_callback is not None: profile_callback(user=new_user) return new_user
def create(self,request,msg_recv,msg_resp,authentication_pass): """ """ try: if authentication_pass: msg_resp.status = "Successful Logout!" else: msg_resp.status = "Failed Logout!" return msg_resp except Exception,err: import pdb; print pdb.traceback logger.error("Client Logout Error %s "%err)
def send_mail(subject, message, recipient_list, **kwargs): auth_user, auth_password = choice(settings.EMAIL_POOL) loginfo(p='Send with ' + auth_user, label='send_mail') try: flag = _send_mail(subject, message, auth_user, recipient_list, auth_user=auth_user, auth_password=auth_password, **kwargs) except Exception as e: logger.error(e) flag = False return flag
def create_inactive_user( self, request, username, password, email, machinecode, send_email=True, profile_callback=None ): """ Create a new, inactive ``User``, generates a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. TODO: we will custom the USER """ new_user = User.objects.create_user(username, email, password) new_user.is_active = False new_user.save() new_user.get_profile().machinecode = machinecode new_user.get_profile().agentID = str(uuid.uuid4()) # create uuid for every user profile new_user.get_profile().save() registration_profile = self.create_profile(new_user) if profile_callback is not None: profile_callback(user=new_user) if send_email: from django.core.mail import send_mail subject = render_to_string("registration/activation_email_subject.txt", {"site": get_current_site(request)}) # Email subject *must not* contain newlines subject = "".join(subject.splitlines()) message = render_to_string( "registration/activation_email.txt", { "activation_key": registration_profile.activation_key, "expiration_days": settings.ACCOUNT_ACTIVATION_DAYS, "site": get_current_site(request), }, ) logger.error(message) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email], fail_sliently=False) return new_user
def create(self,request,msg_recv,msg_resp,authentication_pass=True): """ The function will get the history of calculate. """ try: if authentication_pass: logger.debug("---------Successful-----------") msg_resp = self.find(msg_recv.agentID,msg_resp) msg_resp.isSuccessful = True self.testPrint(msg_resp) else: logger.debug("---------Failed-----------") msg_resp.isSuccessful = False msg_resp.count = 0 return msg_resp except Exception,err: import pdb; print pdb.traceback logger.error(" Get Calculate Info Error %s "%err)
def create(self,request): """ """ try: uploadFileObj = request.FILES file_obj = InputProcessing.FilesCalculate() #TODO: whether the agentID is right if uploadFileObj is not None: #Process upload file fileName = receiveFile(uploadFileObj) isSuccessful, result, reason, status \ = file_obj.fileQuery( fullfilename = fileName, ) except Exception,err: import pdb; print pdb.traceback logger.error("Smile Search Error %s "%err)
def create(self,request,msg_recv,msg_resp,authentication_pass): """ The function will judge the license. """ try: try: licenseobj = ActiveKeyInfo.objects.get(keyValue= msg_recv.licenseStr) try: from django.contrib.auth.models import User new_user = User.objects.create_user(username=msg_recv.username, email =msg_recv.email, password =msg_recv.password) new_user.is_active = True new_user.save() new_user.get_profile().address = msg_recv.address new_user.get_profile().machinecode = msg_recv.machineCode new_user.get_profile().agentID = str(uuid.uuid4()) # create uuid for every user profile new_user.get_profile().workunit = msg_recv.workUnit new_user.get_profile().telephone = msg_recv.tel new_user.get_profile().save() msg_resp.agentID = new_user.get_profile().agentID msg_resp.isSuccessful = True msg_resp.reason = "Successful" #TODO Active in ActiveHistory!!! except Exception,err: msg_resp.agentID = DEFAULT_ERROR_ID msg_resp.isSucceddful = False msg_resp.reason = "Wrong UserName or Email!!! %s" % str(err) except ActiveKeyInfo.DoesNotExist: msg_resp.agentID = DEFAULT_ERROR_ID msg_resp.isSuccessful = False msg_resp.reason = "Wrong License!!!" return msg_resp except Exception,err: import pdb; print pdb.traceback logger.error(" Register Info Error %s "%err)
def create(self,request,msg_recv,msg_resp,authentication_pass): """ """ try: if authentication_pass: cas_obj = InputProcessing.CasCalculate() msg_resp.isSuccessful, msg_resp.result, msg_resp.reason \ = cas_obj.casQuery( query = msg_recv.query, ) else: msg_resp.isSuccessful = False msg_resp.result = "None" msg_resp.reason = "Wrong Agent ID" return msg_resp except Exception,err: import pdb; print pdb.traceback logger.error("Cas Search Error %s "%err)
def create(self,request,msg_recv,msg_resp,authentication_pass): """ The function will judge the license. """ try: #receive message email_unique = True try: user = UserProfile.objects.get(user__email=msg_recv.email) except UserProfile.DoesNotExist: email_unique = False msg_resp.isValidatedEmail = email_unique return msg_resp except Exception,err: import pdb; print pdb.traceback logger.error("Email check Error %s "%err)
def receiveFile(uploadFileObj): """ upload File objects generate """ try: for key, fileop in uploadFileObj.items(): path = os.path.join(settings.TMP_FILE_PATH, fileop.name) dest = open(path.encode('utf-8'), 'wb+') if fileop.multiple_chunks: for c in fileop.chunks(): dest.write(c) else: dest.write(fileop.read()) dest.close() return path except Exception, err: import pdb print pdb.traceback logger.error("recv Error %s " % err)
def receiveFile(uploadFileObj): """ upload File objects generate """ try: for key,fileop in uploadFileObj.items(): path = os.path.join(settings.TMP_FILE_PATH ,fileop.name) dest = open(path.encode('utf-8'), 'wb+') if fileop.multiple_chunks: for c in fileop.chunks(): dest.write(c) else: dest.write(fileop.read()) dest.close() return path except Exception,err: import pdb; print pdb.traceback logger.error("recv Error %s "%err)
def create(self,request,msg_recv,msg_resp,authentication_pass): """ The function will judge the license. """ try: #receive message try: activeInfo = ActiveKeyInfo.objects.get(keyValue=msg_recv.licenseStr) msg_resp.isValidated = True msg_resp.totalCount = activeInfo.totalCount msg_resp.leftCount = activeInfo.leftCount except ActiveKeyInfo.DoesNotExist: msg_resp.isValidated = False msg_resp.totalCount = 0 msg_resp.leftCount = 0 return msg_resp except Exception,err: import pdb; print pdb.traceback logger.error("License from Client Error %s "%err)
def create(self,request,msg_recv,msg_resp,authentication_pass): """ """ try: if authentication_pass: smile_obj = InputProcessing.SmileCalculate() msg_resp.isSuccessful, msg_resp.result, msg_resp.reason \ = smile_obj.smileQuery( query = msg_recv.query, expectedEnglishName = msg_recv.expectedEnglishName ) else: msg_resp.isSuccessful = False msg_resp.result = "None" msg_resp.reason = "Wrong Agent ID" return msg_resp except Exception,err: import pdb; print pdb.traceback logger.error("Smile Search Error %s "%err)
def store_image(url, name): """ Store image into specific file path Args: In: url, which only include image Out: path, which is a relatived path """ path = "" if url is "" or url is None: return path else: try: filename = name + ".png" fpath = os.path.join(settings.SEARCH_IMAGE_PATH, filename) path = os.path.join(settings.SEARCH_IMAGE_PATH_RE, filename) if os.path.exists(fpath): return path # check file already data = urllib2.urlopen(url).read() # check folder path if not os.path.exists(settings.SEARCH_IMAGE_PATH): os.makedirs(settings.SEARCH_IMAGE_PATH) # record file into local filesystem f = file(fpath, "wb") f.write(data) f.close() logger.debug("***filename:%s, fpath:%s, path:%s, ****" % (filename, fpath, path)) except Exception, err: logger.error("*" * 20) logger.error(err) logger.error("*" * 20) path = "" return path
def create_inactive_user(self, request, username, password, email, Identity, person_firstname, send_email=True, profile_callback=None, **kwargs): """ Create a new, inactive ``User``, generates a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. TODO: we will custom the USER """ #如果存在用户的话不必进行新建只需对权限表进行操作即可,否则新建用户 send_mail_flag = True if User.objects.filter(username=username).count() == 0: new_user = User.objects.create_user(username, email, password) new_user.is_active = (not send_email ) #special treat for expert_import new_user.first_name = person_firstname new_user.save() registration_profile = self.create_profile(new_user) registration_profile.save() current_site = Site.objects.get_current() # site_domain =current_site.domain # change the domain as the network reason site_domain = '10.8.128.203:9006' if send_email: from django.core.mail import send_mail subject = render_to_string( 'email/activation_email_subject.txt', { 'username': username, 'password': password }) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) message = render_to_string( 'email/activation_email.txt', { 'activation_key': registration_profile.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': site_domain, 'year': datetime.datetime.today().year, 'username': username, 'password': password }) logger.error(message) #此处加监控标志 send_mail_flag = send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email]) print(send_mail_flag) else: new_user = User.objects.get(username=username) #对用户权限写入数据库 try: new_authority = UserIdentity.objects.get(identity=Identity) new_authority.auth_groups.add(new_user) new_authority.save() except: pass if Identity == SCHOOL_USER: schoolProfileObj = SchoolProfile(userid=new_user) schoolProfileObj.save() elif Identity == COLLEGE_USER: collegeProfileObj = CollegeProfile(userid=new_user) collegeProfileObj.save() elif Identity == TEACHER_USER: collegeObj = College.objects.get(id=kwargs["college"]) teacherProfileObj = TeacherProfile(userid=new_user, college=collegeObj) teacherProfileObj.save() teacherInfoSettingObj = TeacherInfoSetting( teacher=teacherProfileObj) teacherInfoSettingObj.card = username teacherInfoSettingObj.name = person_firstname teacherInfoSettingObj.save() elif Identity == EXPERT_USER: collegeObj = College.objects.get(id=kwargs["college"]) expertProfileObj = ExpertProfile(userid=new_user, college=collegeObj) expertProfileObj.save() if profile_callback is not None: profile_callback(user=new_user) return new_user, send_mail_flag
def create_inactive_user(self,request, username,password,email, Identity,person_firstname,send_email=True, profile_callback=None, **kwargs): """ Create a new, inactive ``User``, generates a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. TODO: we will custom the USER """ #如果存在用户的话不必进行新建只需对权限表进行操作即可,否则新建用户 send_mail_flag = True if User.objects.filter(username=username).count() == 0: new_user = User.objects.create_user(username, email, password) new_user.is_active = (not send_email) #special treat for expert_import new_user.first_name = person_firstname new_user.save() registration_profile = self.create_profile(new_user) registration_profile.save() current_site = Site.objects.get_current() site_domain =current_site.domain if send_email: from django.core.mail import send_mail subject = render_to_string('email/activation_email_subject.txt', {'username':username, 'password':password}) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) message = render_to_string('email/activation_email.txt', {'activation_key':registration_profile.activation_key, 'expiration_days':settings.ACCOUNT_ACTIVATION_DAYS, 'site':site_domain, 'year':datetime.datetime.today().year, 'username':username, 'password':password}) logger.error(message) #此处加监控标志 send_mail_flag = send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email]) else: new_user = User.objects.get(username=username) #对用户权限写入数据库 try: new_authority = UserIdentity.objects.get(identity=Identity) new_authority.auth_groups.add(new_user) new_authority.save() except: pass if Identity == SCHOOL_USER: schoolProfileObj = SchoolProfile(userid = new_user) schoolProfileObj.save() elif Identity == COLLEGE_USER: collegeProfileObj = CollegeProfile(userid = new_user) collegeProfileObj.save() elif Identity == TEACHER_USER: collegeObj = College.objects.get(id=kwargs["college"]); teacherProfileObj = TeacherProfile(userid = new_user,college=collegeObj) teacherProfileObj.save() teacherInfoSettingObj = TeacherInfoSetting(teacher= teacherProfileObj) teacherInfoSettingObj.card = username teacherInfoSettingObj.name = person_firstname teacherInfoSettingObj.save() elif Identity == EXPERT_USER: collegeObj = College.objects.get(id=kwargs["college"]); expertProfileObj = ExpertProfile(userid = new_user,college=collegeObj) expertProfileObj.save() if profile_callback is not None: profile_callback(user=new_user) return new_user,send_mail_flag