def test_generate_sha(self): s1 = six.u('\xc5se') s2 = six.u('\xd8ystein') s3 = six.u('\xc6gir') h1 = generate_sha1(s1) h2 = generate_sha1(s2) h3 = generate_sha1(s3) # Check valid SHA1 activation key self.failUnless(re.match('^[a-f0-9]{40}$', h1[1])) self.failUnless(re.match('^[a-f0-9]{40}$', h2[1])) self.failUnless(re.match('^[a-f0-9]{40}$', h3[1]))
def test_generate_sha(self): s1 = six.u("\xc5se") s2 = six.u("\xd8ystein") s3 = six.u("\xc6gir") h1 = generate_sha1(s1) h2 = generate_sha1(s2) h3 = generate_sha1(s3) # Check valid SHA1 activation key self.assertTrue(re.match("^[a-f0-9]{40}$", h1[1])) self.assertTrue(re.match("^[a-f0-9]{40}$", h2[1])) self.assertTrue(re.match("^[a-f0-9]{40}$", h3[1]))
def change_email(self, email): """ Changes the email address for a user. A user needs to verify this new email address before it becomes active. By storing the new email address in a temporary field -- ``temporary_email`` -- we are able to set this email address after the user has verified it by clicking on the verfication URI in the email. This email get's send out by ``send_verification_email``. **Arguments** ``email`` The new email address that the user wants to use. """ self.email_unconfirmed = email salt, hash = generate_sha1(self.user.username) self.email_confirmation_key = hash self.email_confirmation_key_created = datetime.datetime.now() self.save() # Send email for activation self.send_confirmation_email()
def create_userena_profile(self, user): """ Creates an userena profile """ if isinstance(user.username, unicode): user.username = user.username.encode('utf-8') salt, activation_key = generate_sha1(user.username) return self.create(user=user, activation_key=activation_key)
def upload_to_cover(instance, filename): salt, hash = generate_sha1(instance.id) extension = filename.split('.')[-1].lower() return '%(path)s%(hash)s.%(extension)s' % { 'path': 'cover/', 'hash': hash[:10], 'extension': extension }
def create_baby_tile(request, template_name="kinger/revision/create_baby_tile.html"): print request.FILES form = TileBabyForm(request.POST,request.FILES) print form.errors,'errors------------------------------' if form.is_valid(): ty = request.POST.get("ty",'') desc = request.POST.get("description",'') try: description = urllib.unquote(desc) except: description = desc tile = form.save(commit=False) tile.creator = request.user tile.user = request.user tile.new_category_id = 1200 tile.is_tips = 0 print ty,'ty--------------------------------------' if ty == "flash": # pid = request.POST.get("tile_pid") file_path = request.POST.get("file_path") extension = request.POST.get("extension") file_id = request.POST.get("fid") print file_path,extension,'ppppppppppppppppppppppppppppppppppp' tile.save() date = str(datetime.datetime.strftime(datetime.datetime.now(),"%Y%m%d")) salt, hash = generate_sha1(tile.id) file_name = 'tile/' + date + '/' + hash[:22] + '.' + extension # tile_img = TinymceImage.objects.get(id=pid) tile.img = file_name print tile.id,'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy' try: URL('http://' + SITE_INFO.domain + reverse('cron_make_large_img')).post_async(filename=file_name,file_path=file_path,tileid=tile.id) except Exception, e: print e,'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' try: fr = open(file_path,"rb") content = fr.read() fr.close() if os.path.isfile(file_path): os.remove(file_path) AliyunStorage(). _put_file(file_name, content) except: pass try: temp = TemporaryFiles.objects.get(fileid=file_id) os.remove(temp.path) temp.delete() except: pass else: tile.description = urllib.unquote(str(tile.description)) tile.save() if ty == "word_type": messages.success(request, _("发布成功")) return redirect('kinger_rev_time_axis') data = json.dumps({'status':1,'desc':"ok"}) return HttpResponse(data)
def post(self, request): user = request.user new_email = request.data.get('email', None) try: if not new_email: raise AccountException(constants.INVALID_PARAMETERS) if new_email.lower() == user.email: raise AccountException(constants.EMAIL_NOT_CHANGED) if User.objects.filter(email__iexact=new_email): raise AccountException(constants.EMAIL_IN_USE) # the following is a rewritten version of user.userena_signup.change_email(new_email) user.userena_signup.email_unconfirmed = new_email salt, hash = generate_sha1(user.username) user.userena_signup.email_confirmation_key = hash user.userena_signup.email_confirmation_key_created = get_datetime_now() user.userena_signup.save() # the purpose is rewriting the following part where the emails are sent out email_change_url = settings.USER_BASE_URL +\ settings.MAIL_EMAIL_CHANGE_CONFIRM_URL.format(user.userena_signup.email_confirmation_key) context = { 'user': user, 'email_change_url': email_change_url } # mail to new email account mails.send_mail( subject_template_name=settings.MAIL_CHANGE_EMAIL_NEW_SUBJECT, email_template_name=settings.MAIL_CHANGE_EMAIL_NEW_TEXT, html_email_template_name=settings.MAIL_CHANGE_EMAIL_NEW_HTML, to_email=user.userena_signup.email_unconfirmed, from_email=settings.BEAM_MAIL_ADDRESS, context=context ) context['support'] = settings.BEAM_SUPPORT_MAIL_ADDRESS context['new_email'] = user.userena_signup.email_unconfirmed # mail to old email account mails.send_mail( subject_template_name=settings.MAIL_CHANGE_EMAIL_OLD_SUBJECT, email_template_name=settings.MAIL_CHANGE_EMAIL_OLD_TEXT, html_email_template_name=settings.MAIL_CHANGE_EMAIL_OLD_HTML, to_email=user.email, from_email=settings.BEAM_MAIL_ADDRESS, context=context ) return Response() except AccountException as e: return Response({'detail': e.args[0]}, status=status.HTTP_400_BAD_REQUEST)
def generate_key_personal_email(self, user): if isinstance(user.profile.first_name, text_type): user.profile.first_name = smart_text(user.profile.first_name) salt, activation_key = generate_sha1(user.profile.first_name) try: profile = self.filter(user=user) profile.update(personal_email_confirmation_key=activation_key) except self.model.DoesNotExist: raise Exception("Profile doesnt exist")
def upload_to_mugshot(instance, filename): """ Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ extension = filename.split('.')[-1].lower() salt, hash = generate_sha1(instance.id) return '%(path)s%(hash)s.%(extension)s' % {'path': userena_settings.USERENA_MUGSHOT_PATH, 'hash': hash[:10], 'extension': extension}
def create_userena_profile(self, user): """ Creates an :class:`UserenaSignup` instance for this user. :param user: Django :class:`User` instance. :return: The newly created :class:`UserenaSignup` instance. """ if isinstance(user.username, text_type): user.username = smart_text(user.username) salt, activation_key = generate_sha1(user.username) salt, invitation_key = generate_sha1(user.username) try: profile = self.get(user=user) except self.model.DoesNotExist: profile = self.create(user=user, activation_key=activation_key, invitation_key=invitation_key) return profile
def create_userena_profile(self, user): """ Creates an :class:`UserenaSignup` instance for this user. :param user: Django :class:`User` instance. :return: The newly created :class:`UserenaSignup` instance. """ if isinstance(user.username, unicode): user.username = user.username.encode("utf-8") salt, activation_key = generate_sha1(user.username) return self.create(user=user, activation_key=activation_key)
def create_userena_profile(self, user): """ Creates an :class:`UserenaSignup` instance for this user. :param user: Django :class:`User` instance. :return: The newly created :class:`UserenaSignup` instance. """ if isinstance(user.username, unicode): user.username = user.username.encode('utf-8') salt, activation_key = generate_sha1(user.username) return self.create(user=user, activation_key=activation_key)
def leeren_anlegen(cls): username = cls.erzeuge_username() nutzer = UserenaSignup.objects.create_user(username, email='*****@*****.**', password='******', active=False, send_email=False) signup = nutzer.userena_signup salt, hash = generate_sha1(nutzer.username) signup.activation_key = hash signup.save() return nutzer
def upload_to_mugshot(instance, filename): """ Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ extension = filename.split('.')[-1].lower() salt, hash = generate_sha1(instance.pk) path = userena_settings.USERENA_MUGSHOT_PATH % {'username': instance.user.username, 'id': instance.user.id, 'date': instance.user.date_joined, 'date_now': get_datetime_now().date()} return '%(path)s%(hash)s.%(extension)s' % {'path': path, 'hash': hash[:10], 'extension': extension}
def upload_to_mugshot(instance, filename): """ Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ extension = filename.split(".")[-1].lower() salt, hash = generate_sha1(instance.id) path = userena_settings.USERENA_MUGSHOT_PATH % { "username": instance.user.username, "id": instance.user.id, "date": instance.user.date_joined, "date_now": get_datetime_now().date(), } return "%(path)s%(hash)s.%(extension)s" % {"path": path, "hash": hash[:10], "extension": extension}
def create_userena_profile(self, user): """ Creates an :class:`UserenaSignup` instance for this user. :param user: Django :class:`User` instance. :return: The newly created :class:`UserenaSignup` instance. """ # FIXME probably it's a bug: we don't need to # make user.username bytes instead of str if isinstance(user.username, str): user.username = user.username.encode('utf-8') salt, activation_key = generate_sha1(user.username) return self.create(user=user, activation_key=activation_key)
def upload_to_thumbnail(instance, filename): """ 103,143 Uploads a thumbnail for a user to the ``EBOOK_THUMBNAIL_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ #extension = filename.split('.')[-1].lower() extension = 'jpg_103' salt, hash = generate_sha1(instance.id) path = ebook_settings.EBOOK_THUMBNAIL_PATH % {'username': instance.created_by.username, 'id': instance.created_by.id, 'date': instance.created_by.date_joined, 'date_now': get_datetime_now().date()} return 'thumbnail/products/%(path)s_%(hash)s.%(extension)s' % {'path': path, 'hash': hash[:10], 'extension': extension}
def upload_to_mugshot(instance, filename): """ Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ instance_name = instance.__class__.__name__.lower() extension = filename.split('.')[-1].lower() salt, hash = generate_sha1(instance.id) if instance_name == 'tile': date = str(datetime.datetime.strftime(datetime.datetime.now(),"%Y%m%d")) return instance_name + '/' + date + '/' + hash[:22] + '.' + extension return '%(path)s/%(hash)s.%(extension)s' % { 'path': instance.__class__.__name__.lower(), 'hash': hash[:22], 'extension': extension }
def create_userena_profile(self, user): """ Creates an :class:`UserenaSignup` instance for this user. :param user: Django :class:`User` instance. :return: The newly created :class:`UserenaSignup` instance. """ if isinstance(user.username, text_type): user.username = user.username.encode("utf-8") salt, activation_key = generate_sha1(user.username) try: profile = self.get(user=user) except self.model.DoesNotExist: profile = self.create(user=user, activation_key=activation_key) return profile
def reissue_activation(activation_key): ''' Rewritten version of UserenaSignup.objects.reissue_activation() to customize the sent email ''' try: userena = UserenaSignup.objects.get(activation_key=activation_key) except UserenaSignup.objects.model.DoesNotExist: return None try: salt, new_activation_key = generate_sha1(userena.user.username) userena.activation_key = new_activation_key userena.save(using=UserenaSignup.objects._db) userena.user.date_joined = get_datetime_now() userena.user.save(using=UserenaSignup.objects._db) return new_activation_key except Exception: return None
def change_email(self, email): """ Changes the email address for a user. A user needs to verify this new email address before it becomes active. By storing the new email address in a temporary field -- ``temporary_email`` -- we are able to set this email address after the user has verified it by clicking on the verification URI in the email. This email gets send out by ``send_verification_email``. :param email: The new email address that the user wants to use. """ self.email_unconfirmed = email salt, hash = generate_sha1(self.user.username) self.email_confirmation_key = hash self.email_confirmation_key_created = get_datetime_now() self.save()
def reissue_activation(self, activation_key): """ Creates a new ``activation_key`` resetting activation timeframe when users let the previous key expire. :param activation_key: String containing the secret SHA1 activation key. """ try: userena = self.get(activation_key=activation_key) except self.model.DoesNotExist: return False try: salt, new_activation_key = generate_sha1(userena.user.username) userena.activation_key = new_activation_key userena.save(using=self._db) userena.user.date_joined = get_datetime_now() userena.user.save(using=self._db) userena.send_activation_email() return True except Exception: return False
def create_inactive_user(self, username, email, password): """ A simple wrapper that creates a new ``User``. """ now = datetime.datetime.now() new_user = self.model(username=username, email=email, is_staff=False, is_active=False, is_superuser=False, last_login=now, date_joined=now) new_user.set_password(password) # Create activation key if isinstance(username, unicode): username = username.encode('utf-8') salt, activation_key = generate_sha1(username) new_user.activation_key = activation_key new_user.activation_key_created = datetime.datetime.now() new_user.save(using=self._db) # All users have an empty profile profile_model = get_profile_model() new_profile = profile_model(user=new_user) new_profile.save(using=self._db) # Give permissions to view and change profile permissions = ['view_profile', 'change_profile'] for perm in permissions: assign(perm, new_user.user, new_profile) new_user.send_activation_email() return new_user
def post(self, request): """ 发布一条内容, 针对个人或者班级. ``POST`` `tiles/create/ <http://192.168.1.222:8080/v1/tiles/types>`_ :param type_id: 瓦片类型 :param uid: 发布者,默认为匿名用户(uid: -1) :param class_id: 瓦片所属班级,是否属于班级的内容 :param content: 内容描述 :param img: 二进制图片信息. """ params = request.POST type_id = params.get("type_id") uid = params.get("uid", -1) class_id = params.get("class_id") content = params.get("content", "") category_id = params.get("category_id",type_id) img = request.FILES.get('img') video = params.get("video", "") title = params.get("title", "") tag = params.get("tag", "") group = None category_id = int(category_id) if category_id in (1,2,3): category_id = 17 from oa.helpers import user_access_list user = request.user code_list = [c.code for c in user_access_list(user)] school_level = True if "manage_school_tile" in code_list else False try: tile_type = TileType.objects.get(pk=type_id) if not title: title = tile_type.name except TileType.DoesNotExist: pass #return rc.NOT_HERE try: tile_category = TileCategory.objects.all_with_deleted().get(pk=category_id) if not title: title = tile_category.name except TileCategory.DoesNotExist: return rc.not_here("tile_category object is not exist") #return rc.NOT_HERE group_id = 0 if school_level: user = None try: group = Group.objects.get(pk=uid) if uid else None group_id = group.id except Group.DoesNotExist: group = None else: try: user = User.objects.get(pk=uid) except User.DoesNotExist: return rc.not_here("user object is not exist") #return rc.NOT_HERE if class_id and group_id == 0: try: group = Group.objects.get(pk=class_id) if class_id else None except Group.DoesNotExist: group = None tile = Tile(creator=request.user, user=user, group=group) tile.title = title tile.type_id = type_id if category_id == 9: #if not group: #return rc.not_here("group object is not exist for Activity") try: desc = json.loads(content) act = desc['events'] except: return rc.not_here("Activity description object must be json include key events") if not act: desc = '' else: i = 0 for d in act: if not d['content']: i += 1 if i == len(act): desc = '' if not desc: return rc.not_here("Activity description object can not be null") active = Activity() active.user = user active.creator = request.user active.group = group active.description = json.dumps({"events":desc['events']}) active.save() tile.description = content # tile.img = img tile.video = video # try: # assert category_id != None # tc = TileCategory.objects.get(pk=category_id) # assert not tc.is_parent # except Exception, e: # print e # return rc.BAD_REQUEST tile.category_id = category_id try: is_exist = Tile.objects.get(creator=request.user, user=user, group=group,\ title = title,description = content,img = img,video = video,category_id = category_id) return None except: tile.save() if tag and tile.id: tile_tag = TileCreateTag() tile_tag.tag = tag tile_tag.tile = tile tile_tag.save() if tile.id and img: try: date = str(datetime.datetime.strftime(datetime.datetime.now(),"%Y%m%d")) salt, hash = generate_sha1(tile.id) extension = str(img).split('.')[-1].lower() file_name = 'tile/' + date + '/' + hash[:22] + '.' + extension AliyunStorage(). _put_file(file_name, img.read()) tile.img = file_name tile.save() except: pass return tile if tile.id else None
def upload_to_cover(instance, filename): salt, hash = generate_sha1(instance.id) extension = filename.split('.')[-1].lower() return '%(path)s%(hash)s.%(extension)s' % {'path': 'cover/', 'hash': hash[:10], 'extension': extension}