def crop(request, upload=False): if upload and (not request.user.avatar_temp or not 'upload' in settings.avatars_types): return error404(request) if not upload and request.user.avatar_type != 'upload': messages.error(request, _("Crop Avatar option is avaiable only when you use uploaded image as your avatar."), 'usercp_avatar') return redirect(reverse('usercp_avatar')) message = request.messages.get_message('usercp_avatar') if request.method == 'POST': if request.csrf.request_secure(request): try: image_path = settings.MEDIA_ROOT + 'avatars/' if upload: source = Image.open(image_path + request.user.avatar_temp) else: source = Image.open(image_path + request.user.avatar_original) width, height = source.size aspect = float(width) / float(request.POST['crop_b']) crop_x = int(aspect * float(request.POST['crop_x'])) crop_y = int(aspect * float(request.POST['crop_y'])) crop_w = int(aspect * float(request.POST['crop_w'])) crop = source.crop((crop_x, crop_y, crop_x + crop_w, crop_y + crop_w)) if upload: image_name, image_extension = path(request.user.avatar_temp).splitext() else: image_name, image_extension = path(request.user.avatar_original).splitext() image_name = '%s_%s%s' % (request.user.pk, random_string(8), image_extension) resizeimage(crop, settings.AVATAR_SIZES[0], image_path + image_name, info=source.info, format=source.format) for size in settings.AVATAR_SIZES[1:]: resizeimage(crop, size, image_path + str(size) + '_' + image_name, info=source.info, format=source.format) request.user.delete_avatar_image() if upload: request.user.delete_avatar_original() request.user.avatar_type = 'upload' request.user.avatar_original = '%s_org_%s%s' % (request.user.pk, random_string(8), image_extension) source.save(image_path + request.user.avatar_original) request.user.delete_avatar_temp() request.user.avatar_image = image_name request.user.avatar_crop = [str(float(request.POST[x])) for x in ('crop_x', 'crop_y', 'crop_w')] request.user.save(force_update=True) messages.success(request, _("Your avatar has been cropped."), 'usercp_avatar') return redirect(reverse('usercp_avatar')) except Exception: message = Message(_("Form contains errors."), messages.ERROR) else: message = Message(_("Request authorisation is invalid."), messages.ERROR) return render_to_response('usercp/avatar_crop.html', context_instance=RequestContext(request, { 'message': message, 'after_upload': upload, 'avatar_size': settings.AVATAR_SIZES[0], 'avatar_crop': request.user.avatar_crop if not upload else None, 'source': 'avatars/%s' % (request.user.avatar_temp if upload else request.user.avatar_original), 'tab': 'avatar'}));
def action_reset(self, items, checked): # First loop - check for errors for user in items: if user.pk in checked: if user.is_protected() and not self.request.user.is_god(): return Message( _('You cannot reset protected members passwords.'), 'error'), reverse('admin_users') # Second loop - reset passwords for user in items: if user.pk in checked: new_password = random_string(8) user.set_password(new_password) user.save(force_update=True) user.email_user( self.request, 'users/password/new_admin', _("Your New Password"), { 'password': new_password, }, ) return Message( _('Selected users passwords have been reset successfully.'), 'success'), reverse('admin_users')
def credentials(request): message = request.messages.get_message('usercp_credentials') if request.method == 'POST': form = CredentialsChangeForm(request.POST, request=request) if form.is_valid(): token = random_string(12) request.user.email_user( request, 'users/new_credentials', _("Activate new Sign-In Credentials"), {'token': token} ) request.session['new_credentials'] = { 'token': token, 'email_hash': request.user.email_hash, 'new_email': form.cleaned_data['new_email'], 'new_password': form.cleaned_data['new_password'], } if form.cleaned_data['new_email']: request.user.email = form.cleaned_data['new_email'] request.messages.set_flash(Message(_("We have sent e-mail message to your new e-mail address with link you have to click to confirm change of your sign-in credentials. This link will be valid only for duration of this session, do not sign out until you confirm change!")), 'success', 'usercp_credentials') else: request.messages.set_flash(Message(_("We have sent e-mail message to your e-mail address with link you have to click to confirm change of your sign-in credentials. This link will be valid only for duration of this session, do not sign out until you confirm change!")), 'success', 'usercp_credentials') return redirect(reverse('usercp_credentials')) message = Message(form.non_field_errors()[0], 'error') else: form = CredentialsChangeForm(request=request) return request.theme.render_to_response('usercp/credentials.html', context_instance=RequestContext(request, { 'message': message, 'form': FormLayout(form), 'tab': 'credentials', }));
def form(request): message = None if request.method == 'POST': form = UserResetPasswordForm(request.POST, request=request) if form.is_valid(): user = form.found_user user_ban = Ban.objects.check_ban(username=user.username, email=user.email) if user_ban: return error_banned(request, user, user_ban) elif user.activation != User.ACTIVATION_NONE: return redirect_message(request, messages.INFO, _("%(username)s, your account has to be activated in order for you to be able to request new password.") % {'username': user.username}) user.token = random_string(12) user.save(force_update=True) user.email_user( request, 'users/password/confirm', _("Confirm New Password Request") ) return redirect_message(request, messages.INFO, _("%(username)s, new password request confirmation has been sent to %(email)s.") % {'username': user.username, 'email': user.email}) else: message = Message(form.non_field_errors()[0], messages.ERROR) else: form = UserResetPasswordForm(request=request) return render_to_response('reset_password.html', { 'message': message, 'form': form, }, context_instance=RequestContext(request));
def reset(request, username="", user="******", token=""): user = int(user) try: user = User.objects.get(pk=user) user_ban = Ban.objects.check_ban(username=user.username, email=user.email) if user_ban: return error_banned(request, user, user_ban) if user.activation != User.ACTIVATION_NONE: return redirect_message(request, messages.INFO, _("%(username)s, your account has to be activated in order for you to be able to request new password.") % {'username': user.username}) if not token or not user.token or user.token != token: return redirect_message(request, messages.ERROR, _("%(username)s, request confirmation link is invalid. Please request new confirmation link.") % {'username': user.username}) new_password = random_string(6) user.token = None user.set_password(new_password) user.save(force_update=True) # Logout signed in and kill remember me tokens Session.objects.filter(user=user).update(user=None) Token.objects.filter(user=user).delete() # Set flash and mail new password user.email_user( request, 'users/password/new', _("Your New Password"), {'password': new_password} ) return redirect_message(request, messages.SUCCESS, _("%(username)s, your password has been changed with new one that was sent to %(email)s.") % {'username': user.username, 'email': user.email}) except User.DoesNotExist: return error404(request)
def create_user(self, username, email, password, timezone=False, ip='127.0.0.1', agent='', no_roles=False, activation=0, request=False): token = '' if activation > 0: token = random_string(12) timezone = timezone or settings.default_timezone # Get first rank try: from misago.models import Rank default_rank = Rank.objects.filter(special=0).order_by('-order')[0] except IndexError: default_rank = None # Store user in database new_user = User( last_sync=tz_util.now(), join_date=tz_util.now(), join_ip=ip, join_agent=agent, activation=activation, token=token, timezone=timezone, rank=default_rank, subscribe_start=settings.subscribe_start, subscribe_reply=settings.subscribe_reply, ) validate_username(username) validate_password(password) new_user.set_username(username) new_user.set_email(email) new_user.set_password(password) new_user.full_clean() new_user.default_avatar() new_user.save(force_insert=True) # Set user roles? if not no_roles: from misago.models import Role new_user.roles.add(Role.objects.get(_special='registered')) new_user.make_acl_key() new_user.save(force_update=True) # Update forum stats with UpdatingMonitor() as cm: if activation == 0: monitor.increase('users') monitor['last_user'] = new_user.pk monitor['last_user_name'] = new_user.username monitor['last_user_slug'] = new_user.username_slug else: monitor.increase('users_inactive') # Return new user return new_user
def process_request(self, request): if request.user.is_crawler(): return None if 'csrf_token' in request.session: csrf_token = request.session['csrf_token'] else: csrf_token = random_string(16) request.session['csrf_token'] = csrf_token request.csrf = CSRFProtection(csrf_token)
def process_request(self, request): if request.user.is_crawler(): return None if 'csrf_token' in request.session: csrf_token = request.session['csrf_token'] else: csrf_token = random_string(16); request.session['csrf_token'] = csrf_token request.csrf = CSRFProtection(csrf_token)
def reset(request, username="", user="******", token=""): user = int(user) try: user = User.objects.get(pk=user) user_ban = Ban.objects.check_ban(username=user.username, email=user.email) if user_ban: return error_banned(request, user, user_ban) if user.activation != User.ACTIVATION_NONE: return redirect_message( request, Message( _("%(username)s, your account has to be activated in order for you to be able to request new password." ) % {'username': user.username}), 'info') if not token or not user.token or user.token != token: return redirect_message( request, Message( _("%(username)s, request confirmation link is invalid. Please request new confirmation link." ) % {'username': user.username}), 'error') new_password = random_string(6) user.token = None user.set_password(new_password) user.save(force_update=True) # Logout signed in and kill remember me tokens Session.objects.filter(user=user).update(user=None) Token.objects.filter(user=user).delete() # Set flash and mail new password user.email_user(request, 'users/password/new', _("Your New Password"), {'password': new_password}) return redirect_message( request, Message( _("%(username)s, your password has been changed with new one that was sent to %(email)s." ) % { 'username': user.username, 'email': user.email }), 'success') except User.DoesNotExist: return error404(request)
def post_markdown(text): md = markdown.Markdown(safe_mode='escape', output_format=settings.OUTPUT_FORMAT, extensions=['nl2br', 'fenced_code']) remove_unsupported(md) md.mi_token = random_string(16) for extension in settings.MARKDOWN_EXTENSIONS: module = '.'.join(extension.split('.')[:-1]) extension = extension.split('.')[-1] module = import_module(module) attr = getattr(module, extension) ext = attr() ext.extendMarkdown(md) text = md.convert(text) md, text = tidy_markdown(md, text) return md, text
def post_markdown(request, text): md = markdown.Markdown( safe_mode='escape', output_format=settings.OUTPUT_FORMAT, extensions=['nl2br', 'fenced_code']) remove_unsupported(md) md.mi_token = random_string(16) for extension in settings.MARKDOWN_EXTENSIONS: module = '.'.join(extension.split('.')[:-1]) extension = extension.split('.')[-1] module = import_module(module) attr = getattr(module, extension) ext = attr() ext.extendMarkdown(md) text = md.convert(text) return tidy_markdown(md, text)
def form(request): message = None if request.method == 'POST': form = UserResetPasswordForm(request.POST, request=request) if form.is_valid(): user = form.found_user user_ban = Ban.objects.check_ban(username=user.username, email=user.email) if user_ban: return error_banned(request, user, user_ban) elif user.activation != User.ACTIVATION_NONE: return redirect_message( request, Message( _("%(username)s, your account has to be activated in order for you to be able to request new password." ) % {'username': user.username}), 'info') user.token = random_string(12) user.save(force_update=True) user.email_user(request, 'users/password/confirm', _("Confirm New Password Request")) return redirect_message( request, Message( _("%(username)s, new password request confirmation has been sent to %(email)s." ) % { 'username': user.username, 'email': user.email }), 'info') else: message = Message(form.non_field_errors()[0], 'error') else: form = UserResetPasswordForm(request=request) return request.theme.render_to_response( 'reset_password.html', { 'message': message, 'form': FormLayout(form), }, context_instance=RequestContext(request))
def action_deactivate(self, items, checked): # First loop - check for errors for user in items: if user.pk in checked: if user.is_protected() and not self.request.user.is_god(): return Message(_('You cannot force validation of protected members e-mails.'), messages.ERROR), reverse('admin_users') # Second loop - reset passwords for user in items: if user.pk in checked: user.activation = user.ACTIVATION_USER user.token = token = random_string(12) user.save(force_update=True) user.email_user( self.request, 'users/activation/invalidated', _("Account Activation"), ) return Message(_('Selected users accounts have been deactivated and new activation links have been sent to them.'), messages.SUCCESS), reverse('admin_users')
def credentials(request): message = request.messages.get_message("usercp_credentials") if request.method == "POST": form = CredentialsChangeForm(request.POST, request=request) if form.is_valid(): token = random_string(12) request.user.email_user( request, "users/new_credentials", _("Activate new Sign-In Credentials"), {"token": token} ) request.session["new_credentials"] = { "token": token, "email_hash": request.user.email_hash, "new_email": form.cleaned_data["new_email"], "new_password": form.cleaned_data["new_password"], } if form.cleaned_data["new_email"]: request.user.email = form.cleaned_data["new_email"] messages.success( request, _( "We have sent e-mail message to your new e-mail address with link you have to click to confirm change of your sign-in credentials. This link will be valid only for duration of this session, do not sign out until you confirm change!" ), "usercp_credentials", ) else: messages.success( request, _( "We have sent e-mail message to your e-mail address with link you have to click to confirm change of your sign-in credentials. This link will be valid only for duration of this session, do not sign out until you confirm change!" ), "usercp_credentials", ) return redirect(reverse("usercp_credentials")) message = Message(form.non_field_errors()[0], messages.ERROR) else: form = CredentialsChangeForm(request=request) return render_to_response( "usercp/credentials.html", context_instance=RequestContext(request, {"message": message, "form": form, "tab": "credentials"}), )
def credentials(request): message = request.messages.get_message('usercp_credentials') if request.method == 'POST': form = CredentialsChangeForm(request.POST, request=request) if form.is_valid(): token = random_string(12) request.user.email_user(request, 'users/new_credentials', _("Activate new Sign-In Credentials"), {'token': token}) request.session['new_credentials'] = { 'token': token, 'email_hash': request.user.email_hash, 'new_email': form.cleaned_data['new_email'], 'new_password': form.cleaned_data['new_password'], } if form.cleaned_data['new_email']: request.user.email = form.cleaned_data['new_email'] request.messages.set_flash( Message( _("We have sent e-mail message to your new e-mail address with link you have to click to confirm change of your sign-in credentials. This link will be valid only for duration of this session, do not sign out until you confirm change!" )), 'success', 'usercp_credentials') else: request.messages.set_flash( Message( _("We have sent e-mail message to your e-mail address with link you have to click to confirm change of your sign-in credentials. This link will be valid only for duration of this session, do not sign out until you confirm change!" )), 'success', 'usercp_credentials') return redirect(reverse('usercp_credentials')) message = Message(form.non_field_errors()[0], 'error') else: form = CredentialsChangeForm(request=request) return request.theme.render_to_response('usercp/credentials.html', context_instance=RequestContext( request, { 'message': message, 'form': FormLayout(form), 'tab': 'credentials', }))
def action_reset(self, items, checked): # First loop - check for errors for user in items: if user.pk in checked: if user.is_protected() and not self.request.user.is_god(): return Message(_('You cannot reset protected members passwords.'), messages.ERROR), reverse('admin_users') # Second loop - reset passwords for user in items: if user.pk in checked: new_password = random_string(8) user.set_password(new_password) user.save(force_update=True) user.email_user( self.request, 'users/password/new_admin', _("Your New Password"), { 'password': new_password, }, ) return Message(_('Selected users passwords have been reset successfully.'), messages.SUCCESS), reverse('admin_users')
def signin(request): message = request.messages.get_message('security') bad_password = False not_active = False banned_account = False if request.method == 'POST': form = SignInForm( request.POST, show_remember_me=not request.firewall.admin and settings.remember_me_allow, request=request ) if form.is_valid(): try: # Configure correct auth and redirect links if request.firewall.admin: auth_method = auth_admin success_redirect = reverse(site.get_admin_index()) else: auth_method = auth_forum success_redirect = reverse('index') # Authenticate user user = auth_method( request, form.cleaned_data['user_email'], form.cleaned_data['user_password'], ) sign_user_in(request, user) remember_me_token = False if not request.firewall.admin and settings.remember_me_allow and form.cleaned_data['user_remember_me']: remember_me_token = random_string(42) remember_me = Token( id=remember_me_token, user=user, created=timezone.now(), accessed=timezone.now(), ) remember_me.save() if remember_me_token: request.cookiejar.set('TOKEN', remember_me_token, True) messages.success(request, _("Welcome back, %(username)s!") % {'username': user.username}, 'security') return redirect(success_redirect) except AuthException as e: message = Message(e.error, messages.ERROR) bad_password = e.password banned_account = e.ban not_active = e.activation # If not in Admin, register failed attempt if not request.firewall.admin and e.type == auth.CREDENTIALS: SignInAttempt.objects.register_attempt(request.session.get_ip(request)) # Have we jammed our account? if SignInAttempt.objects.is_jammed(request.session.get_ip(request)): request.jam.expires = timezone.now() return redirect(reverse('sign_in')) else: message = Message(form.non_field_errors()[0], messages.ERROR) else: form = SignInForm( show_remember_me=not request.firewall.admin and settings.remember_me_allow, request=request ) return render_to_response('signin.html', { 'message': message, 'bad_password': bad_password, 'banned_account': banned_account, 'not_active': not_active, 'form': form, 'hide_signin': True, }, context_instance=RequestContext(request));
def upload(request): if not 'upload' in request.settings.avatars_types: return error404(request) message = request.messages.get_message('usercp_avatar') if request.method == 'POST': form = UploadAvatarForm(request.POST, request.FILES, request=request) if form.is_valid(): request.user.delete_avatar_temp() image = form.cleaned_data['avatar_upload'] image_name, image_extension = path(smart_str(image.name.lower())).splitext() image_name = '%s_tmp_%s%s' % (request.user.pk, random_string(8), image_extension) image_path = settings.MEDIA_ROOT + 'avatars/' + image_name request.user.avatar_temp = image_name with open(image_path, 'wb+') as destination: for chunk in image.chunks(): destination.write(chunk) request.user.save() try: if is_zipfile(image_path): # Composite file upload raise ValidationError() image = Image.open(image_path) if not image.format in ['GIF', 'PNG', 'JPEG']: raise ValidationError() image.seek(0) image.save(image_path) if request.POST.get('js_check'): return redirect(reverse('usercp_avatar_upload_crop')) # Redirect to crop page didnt happen, handle avatar with old school hollywood way image_path = settings.MEDIA_ROOT + 'avatars/' source = Image.open(image_path + request.user.avatar_temp) image_name, image_extension = path(request.user.avatar_temp).splitext() image_name = '%s_%s%s' % (request.user.pk, random_string(8), image_extension) resizeimage(source, settings.AVATAR_SIZES[0], image_path + image_name, info=source.info, format=source.format) for size in settings.AVATAR_SIZES[1:]: resizeimage(source, size, image_path + str(size) + '_' + image_name, info=source.info, format=source.format) # Update user model one more time request.user.delete_avatar_image() request.user.delete_avatar_original() request.user.avatar_type = 'upload' request.user.avatar_original = '%s_org_%s%s' % (request.user.pk, random_string(8), image_extension) source.save(image_path + request.user.avatar_original) request.user.delete_avatar_temp() request.user.avatar_image = image_name request.user.save(force_update=True) # Set message and adios! request.messages.set_flash(Message(_("Your avatar has changed.")), 'success', 'usercp_avatar') return redirect(reverse('usercp_avatar')) except ValidationError: request.user.delete_avatar() request.user.default_avatar(request.settings) message = Message(_("Only gif, jpeg and png files are allowed for member avatars."), 'error') else: message = Message(form.non_field_errors()[0], 'error') else: form = UploadAvatarForm(request=request) return request.theme.render_to_response('usercp/avatar_upload.html', context_instance=RequestContext(request, { 'message': message, 'form': FormLayout(form), 'tab': 'avatar', }));
def generate_token(self): self.token = random_string(32)
def _get_new_session_key(self): return random_string(42)
def create_user(self, username, email, password, timezone=False, ip='127.0.0.1', agent='', no_roles=False, activation=0, request=False): token = '' if activation > 0: token = random_string(12) try: db_settings = request.settings except AttributeError: from misago.dbsettings import DBSettings db_settings = DBSettings() if timezone == False: timezone = db_settings['default_timezone'] # Get first rank try: from misago.models import Rank default_rank = Rank.objects.filter(special=0).order_by('order')[0] except IndexError: default_rank = None # Store user in database new_user = User( last_sync=tz_util.now(), join_date=tz_util.now(), join_ip=ip, join_agent=agent, activation=activation, token=token, timezone=timezone, rank=default_rank, subscribe_start=db_settings['subscribe_start'], subscribe_reply=db_settings['subscribe_reply'], ) validate_username(username, db_settings) validate_password(password, db_settings) new_user.set_username(username) new_user.set_email(email) new_user.set_password(password) new_user.full_clean() new_user.default_avatar(db_settings) new_user.save(force_insert=True) # Set user roles? if not no_roles: from misago.models import Role new_user.roles.add(Role.objects.get(_special='registered')) new_user.make_acl_key() new_user.save(force_update=True) # Load monitor try: monitor = request.monitor except AttributeError: from misago.monitor import Monitor monitor = Monitor() # Update forum stats if activation == 0: monitor['users'] = int(monitor['users']) + 1 monitor['last_user'] = new_user.pk monitor['last_user_name'] = new_user.username monitor['last_user_slug'] = new_user.username_slug else: monitor['users_inactive'] = int(monitor['users_inactive']) + 1 # Return new user return new_user