def confirm(request): if request.user.profile.auth_scheme == "sms": return render_to_response( "otp/confirmation.html", RequestContext(request, {"have_sms_binding": True})) result = sms_check(request, request.user) if result: return render_to_response("otp/confirmation.html", RequestContext(request, result)) phone_raw = request.POST["phone_mobile_0"] + request.POST["phone_mobile_1"] phone = "".join(c for c in phone_raw if c in "1234567890+") profile = request.user.profile if profile.phone_mobile != phone: Logger(event=Events.PROFILE_CHANGED, user=request.user, ip=request.META["REMOTE_ADDR"], content_object=profile, params={ 'phone_mobile': { "from": profile.phone_mobile, "to": phone } }).save() profile.phone_mobile = phone profile.save() validation, created = request.user.validations.get_or_create( key="phone_mobile") old_status = validation.is_valid validation.is_valid = True validation.save() Logger(user=request.user, content_object=profile, ip=request.META["REMOTE_ADDR"], event=Events.PHONE_VALIDATION_BY_USER, params={ "field": "phone_mobile", "from": old_status, "to": True }).save() return redirect(request.GET.get("next", "profiles_edit_profile"))
def password_recovery(request, account_id): account = get_object_or_404(TradingAccount, mt4_id=account_id, user=request.user, is_deleted=False) form = PasswordRecoveryForm(data=request.POST or None) if form.is_valid(): if not account.is_demo: result = security_check(request, request.user) if result: return result form.save(account=account) Logger(user=request.user, content_object=account, ip=request.META["REMOTE_ADDR"], event=Events.ACCOUNT_PASSWORD_RESTORED).save() messages.success(request, _("Password recovery request for account #%(id)s " "created successfully. Notification with the account " "password has been sent to your e-mail.") % \ {"id": account.mt4_id}) return redirect("mt4_account_list") return {"form": form}
def withdraw_request_committed(sender, instance, created, **kwargs): if created: return is_committed = instance.changes.get("is_committed") if is_committed is None or is_committed[1] is None: return if is_committed[1]: notification_name = "withdraw_request_committed" if instance.requisit is not None: instance.requisit.is_valid = True instance.requisit.save() else: notification_name = "withdraw_request_failed" users = set(Group.objects.get(name="Back office").user_set.all()) users.add(instance.account.user) notification.send(users, notification_name, { "paymentrequest": instance, "empty": {} }) if instance.is_committed: Logger(user=None, content_object=instance, ip=None, event=Events.WITHDRAW_REQUEST_COMMITTED).save() if instance.group: instance.group.process()
def save(self, **kwargs): res = super(DepositForm, self).save(**kwargs) Logger(user=self.request.user, ip=self.request.META["REMOTE_ADDR"], event=Events.DEPOSIT_REQUEST_CREATED, content_object=res).save() return res
def save_model(self, request, obj, form, change): obj.save() if 'is_valid' in obj.changes: Logger(user=request.user, content_object=obj, ip=request.META["REMOTE_ADDR"], event=Events.REQUISIT_VALIDATION_UPDATE, params={ 'is_valid': obj.is_valid }).save()
def password_change(request, *args, **kwargs): response = pass_change( request, *args, post_change_redirect=reverse("auth_password_change_done"), **kwargs) if request.method == "POST": if isinstance(response, HttpResponseRedirect): Logger(ip=request.META["REMOTE_ADDR"], event=Events.PASSWORD_CHANGE_OK, user=request.user, content_object=request.user.profile).save() else: # user may have failed password confirmation only; not a crime if not request.user.check_password(request.POST["old_password"]): Logger(ip=request.META["REMOTE_ADDR"], event=Events.PASSWORD_CHANGE_FAIL, user=request.user, content_object=request.user.profile).save() return response
def reset(self): """ Resets all approvals. For example, on new request create. """ self.processing_level = 0 for approval in self.approvals.all(): approval.is_accepted = False approval.save() Logger(user=None, content_object=approval, ip=None, event=Events.WITHDRAW_REQUESTS_GROUP_APPROVAL_RESET).save() self.save()
def register_mt4account(details, user, account_type_details, form_class, partner_api_id, additional_fields=None): additional_fields = additional_fields or dict() engine = "demo" if account_type_details["is_demo"] else "default" mt4_id = mt4api.RemoteMT4Manager(engine).create_account(**details) # mt4_id = api.SocketAPI(engine=account_type_details['engine']).create_account(**details) account = TradingAccount( user=user, mt4_id=mt4_id, _login=str(mt4_id), group_name=account_type_details['slug'], agreement_type=additional_fields.get('agreement_type')) if partner_api_id: try: account.registered_from_partner_domain = PartnerDomain.objects.get( api_key=partner_api_id) except PartnerDomain.DoesNotExist: pass account.save() Logger(user=user, content_object=account, ip=account_type_details["ip"], event=Events.ACCOUNT_CREATED).save() form_class.send_notification(account, account_type_details['slug'], **details) account_created.send( sender=account, type_details=account_type_details, mt4data=details, ) account_group = get_account_type(account_type_details['slug']) if account_group.creation_callback is not None: account_group.creation_callback(account, **additional_fields) return { 'mt4_id': mt4_id, 'mt4_password': details['password'], 'slug': account_type_details['slug'], 'account_pk': account.pk }
def _security_notification(limit_type, email=True): Logger(user=user, event=Events.ACCOUNT_DATA_VIEW_EXCEEDED, ip=ip, params={ 'limit_type': limit_type, }).save() if email: subject = "%s has exceeded his %s CRM limit" % (user.email, limit_type) send_mail(subject=subject, message="At %s %s from IP %s" % (datetime.now(), subject, ip), from_email="*****@*****.**", recipient_list=('*****@*****.**', '*****@*****.**'))
def upload_document(request): form = DocumentForm(request.POST or None, request.FILES or None) if form.is_valid(): document = form.save(commit=False) document.user = request.user document.save() Logger(user=request.user, content_object=document, ip=request.META["REMOTE_ADDR"], event=Events.DOCUMENT_UPLOADED).save() messages.success(request, _("Successfully uploaded document %s") % document) return redirect(request.GET.get("next", "profiles_my")) return {"form": form}
def save(self, *args, **kwargs): res = super(WithdrawForm, self).save(*args, **kwargs) last_deposit = DepositRequest.objects.filter( account__user=res.account.user, is_committed=True, payment_system="ecommpay", ).order_by('-creation_ts', ).first() if last_deposit: res.last_transaction_id = last_deposit.transaction_id Logger(user=self.request.user, ip=self.request.META["REMOTE_ADDR"], event=Events.WITHDRAW_REQUEST_CREATED, content_object=res).save() return res
def verify_partner(request): docs = [DOCUMENT_TYPES.IB_AGREEMENT, DOCUMENT_TYPES.PASSPORT_SCAN] form = DocumentForm(request.POST or None, request.FILES or None, documents=docs) if form.is_valid(): document = form.save(commit=False) document.user = request.user document.save() Logger(user=request.user, content_object=document, ip=request.META["REMOTE_ADDR"], event=Events.DOCUMENT_UPLOADED).save() messages.success(request, _("Successfully uploaded document %s") % document) form = DocumentForm() from project.templatetags.app_tags import agreement_url return {"form": form, "agreement_link": agreement_url("real_ib_partner")}
def change_leverage(request, account_id): account = get_object_or_404(TradingAccount, mt4_id=account_id, user=request.user, is_deleted=False) max_leverage = request.GET.get("max_leverage") if request.GET.get("next") == reverse("bonus_list"): max_leverage = 100 form = ChangeLeverageForm(request.POST or None, account=account, max_leverage=max_leverage) if form.is_valid(): if not account.is_demo: result = security_check(request, request.user) if result: return result form.save() Logger(user=request.user, content_object=account, ip=request.META["REMOTE_ADDR"], event=Events.LEVERAGE_CHANGED, params={ "from": account.leverage, "to": form.cleaned_data["leverage"] }).save() messages.success( request, _("Leverage for account #%(id)s changed successfully.") % {"id": account.mt4_id}) return redirect(request.GET.get("next", "mt4_account_list")) return {"form": form}
def confirm_field(request, username, field, status=None): """ View, changing the status of a given field. Requires at least two arguments passed via query string: username for the user, who's profile field is validated and field name. Optionally status can be supplied which is either 't' or 'f' for True and False respectively. """ status = {"t": True, "f": False, "c": None}[status] # FIXME: currently UserDataValidation objects can be mutated via # this view, how does it fit with our business logic? if not request.user.has_perm("profiles.change_userdatavalidation"): return HttpResponseForbidden() try: profile = UserProfile.objects.get(user__username=username) except (ObjectDoesNotExist, KeyError): return HttpResponseNotFound() validation, created = profile.user.validations.get_or_create(key=field) old_status = validation.is_valid validation.is_valid = status validation.comment = request.POST.get("comment") validation.save() Logger(user=request.user, content_object=profile, ip=request.META["REMOTE_ADDR"], event=Events.VALIDATION_OK, params={ "field": field, "from": old_status, "to": status }).save() return { "status": "ok", }
def password_reset(request, *args, **kwargs): if request.POST: u = User.objects.filter( email__iexact=request.POST.get("email")).first() if not u: messages.add_message( request, messages.ERROR, _("Your e-mail has not been confirmed or not in the database. " "Please use the form password recovery through SMS")) return HttpResponseRedirect(reverse('password_reset')) elif phone_based_registration( u) and u.last_login == datetime.fromtimestamp(0): messages.add_message( request, messages.ERROR, _("Phone number for your account is not confirmed. Please use " "phone-base password recovery.")) return HttpResponseRedirect(reverse('password_reset_by_phone')) response = django_password_reset( request, *args, post_reset_redirect=reverse("password_reset_done"), **kwargs) if request.method == "POST" and isinstance(response, HttpResponseRedirect): users = User.objects.filter(email=request.POST["email"]) kwargs = { "content_object": users[0], "user": users[0] } if users else {} Logger(ip=request.META["REMOTE_ADDR"], event=Events.PASSWORD_RESTORED, params={ "email": request.POST["email"] }, **kwargs).save() return response
def inner(): initial = (getattr(self.instance, field_name, None) or getattr(self.instance.user, field_name, None)) value = self.cleaned_data[field_name] # you cannot change phone number via profile edit if you have sms-binding if field_name == "phone_mobile": if self.instance.user.profile.auth_scheme == "sms": return initial value = "".join(c for c in value if c in '1234567890+') if value != initial: # Removing Validation object for that field, if the value has changed. self.instance.user.validations.filter( key=field_name).delete() Logger(user=self.request.user, content_object=self.request.user.profile, ip=self.request.META["REMOTE_ADDR"], event=Events.VALIDATION_REVOKED, params={ "field": field_name }).save() return value
def process(self): """ God-function to deal with all processing """ if self.is_closed: return next_required_departments = self.next_required_departments() next_level = self.next_required_level() now = datetime.now().strftime('%d.%m.%Y %H:%M:%S') #if we have no next requirements, we should complete requests if not next_level: self.attention_list.clear() self.processing_departments = '' for wr in self.requests.filter(is_committed=None).exclude( is_payed=True): wr._initial_instance = copy( wr ) # dirty hack to prevent possible bugs in StateSavingModel # why? it does not create initial state if object was created, not retrieved is_chargable, limit = wr.is_chargable_data() if not is_chargable: wr.is_committed = False wr.private_comment = u'REJECTED: not enough funds ({limit} available) @ {now}'.format( now=now, limit=limit) wr.save() continue wr.is_payed = True wr.private_comment = u'AN <{now}>: Approved {by}'.format( now=now, by=', '.join([ a.user.get_full_name() for a in self.approvals.filter(is_accepted=True) ])) try: wr.save() except PlatformError as e: wr.private_comment = wr.private_comment or u'' if e.args and e.args[0] == e.NOT_ENOUGH_MONEY: current_language = get_language() if wr.account.user.profile.language in [ l[0] for l in settings.LANGUAGES ]: target_language = wr.account.user.profile.language else: target_language = "ru" activate(target_language) wr.public_comment = _( "Your account didn't have enough funds when the request was processed." ) activate(current_language) wr.is_committed = False wr.private_comment = u'REJECTED: not enough funds @ {now}'.format( now=now) else: wr.private_comment = u'NOT PROCESSED: error {0} @ {now}'.format( e.args[0], now=now) wr.save() #okay, set flag is_ready_for_payment for each successfull request for wr in self.requests.filter(is_payed=True, is_ready_for_payment=False): wr.is_ready_for_payment = True wr.save() Logger(user=None, content_object=wr, ip=None, event=Events.WITHDRAW_REQUEST_READY_FOR_PAYMENT).save() #and close group self.is_closed = True Logger(user=None, content_object=self, ip=None, event=Events.WITHDRAW_REQUESTS_GROUP_CLOSED).save() #if we have new step in proce ssing... elif self.processing_level != next_level: self.processing_level = next_level self.processing_departments = ','.join( next_required_departments.keys()) # fill deps list self.attention_list.clear() self.notify_next_departments() # fill attention list #if there is requirements level and it is unchanged # clear up lists of attention # repopulate users in attention list, it will remove # users with approvals or if we dont need em # also, clear up processing_departments list else: self.attention_list.clear() for slug, info in next_required_departments.items(): for user in list(info['users']) + info.get('notify', list()): self.attention_list.add(user) self.processing_departments = ','.join( next_required_departments.keys()) self.save()
def wrequest_group_saved(sender, instance, created, **kwargs): if created: Logger(user=None, content_object=instance, ip=None, event=Events.WITHDRAW_REQUESTS_GROUP_CREATED).save()
def security(request): if request.user.profile.has_otp_devices: raise Http404() new_device = OTPDevice(key=random_base32()) new_secret = new_device.key uri_domain = u"%(name)s@%(debug)s%(domain)s" % { "debug": "debug." if settings.DEBUG else "", "name": request.user.username, "domain": settings.ROOT_HOSTNAME, } uri = new_device.uri(uri_domain) old_hash = "" next = request.GET.get("next") or request.POST.get("next") or request.path if request.method == "POST": auth_type = request.POST.get("auth_type") model, check_key = { "sms": (SMSDevice, "sms_check"), "otp": (OTPDevice, "otp_check"), }[auth_type] if auth_type in ["sms", "voice"]: phone_form = PhoneForm(data=request.POST) phone_form.step2 = True if not phone_form.is_valid(): return { "qr_code": convert_to_base64(qrcode.make(uri)), "secret": new_secret, "devices": request.user.profile.otp_devices, "phone_form": phone_form, } else: phone_form = PhoneForm(number=request.user.profile.phone_mobile) phone_form.step2 = False device = model(user=request.user, name=auth_type.upper()) if auth_type == "otp": secret = request.POST["device_secret"] device.key = secret if (check_key in request.POST and device.verify_token(request.POST[check_key], request)): result = security_check(request, request.user) if result: return result if auth_type == "sms": device.phone_number = phone_form.cleaned_data["phone_mobile"] # только один девайс на юзера request.user.profile.otp_devices.update(is_deleted=True) if auth_type == "sms": profile = request.user.profile profile.make_valid("phone_mobile") phone_number = phone_form.cleaned_data["phone_mobile"] phone_number_profile = profile.phone_mobile if profile.phone_mobile else "" profile_phone_clean = "".join(x for x in phone_number_profile if x in "1234567890+") phone_number_clean = "".join(x for x in phone_number if x in "1234567890+") if profile_phone_clean != phone_number_clean: mail_admins( u"Номер в СМС-привязке не совпадает с номером в профиле", u"Клиент %(user)s (%(user_admin_url)s) создал СМС-привязку, " u"номер которой не совпадает с номером телефона в профиле\n" u"%(profile_phone)s - в профиле\n" u"%(binding_phone)s - в привязке\n" u"Телефон в профиле был обновлен на телефон в привязке" % { "user": request.user, "user_admin_url": request.build_absolute_uri( get_admin_url(request.user)), "profile_phone": profile_phone_clean, "binding_phone": phone_number_clean }) profile.phone_mobile = phone_number profile.save() Logger(event=Events.PROFILE_CHANGED, user=request.user, ip=request.META["REMOTE_ADDR"], content_object=profile, params={ 'phone_mobile': { "from": profile.phone_mobile, "to": phone_number } }).save() device.save() Logger(event=Events.OTP_BINDING_CREATED, user=request.user, ip=request.META["REMOTE_ADDR"], content_object=device).save() request.user.profile.auth_scheme = auth_type request.user.profile.lost_otp = False request.user.profile.save() if request.is_ajax(): return { "ok": True, "redirect": next, } messages.success(request, _("Device %s has been saved") % device.name) return redirect(next) else: if request.is_ajax(): return { "nok": True, "errors": { (auth_type + "_check"): [unicode(_("Wrong code"))] } } messages.error(request, _("Wrong code")) old_hash = request.POST.get("preview_hash", "") else: phone_form = PhoneForm(number=request.user.profile.phone_mobile) context = { "qr_code": convert_to_base64(qrcode.make(uri)), "secret": new_secret, "devices": request.user.profile.otp_devices, "phone_form": phone_form, "auth_type": request.REQUEST.get("auth_type", "sms"), "preview_hash": old_hash, "next": next } if request.is_ajax(): return render_to_response("reveal_forms/create_otp.html", RequestContext(request, context)) return context
} else: try: maybe_user = User.objects.get( email__icontains=request.POST["auth-email"]) kwargs = { "user": maybe_user, "content_object": maybe_user, } except User.DoesNotExist, User.MultipleObjectsReturned: kwargs = {} if res is None: Logger(event=Events.OTP_OK, ip=request.META["REMOTE_ADDR"], params={ "path": request.path }, **kwargs).save() cache.delete(cache_key) return res elif "hash" in request.POST: Logger(event=Events.OTP_FAIL, ip=request.META["REMOTE_ADDR"], params={ "path": request.path }, **kwargs).save() if return_form: return render_to_string("otp/includes/otp_form.html", RequestContext(request, res))
def edit_profile(request, username=None): """ Edit the current User's profile. If the user does not already have a profile (as determined by User.profile), a redirect will be issued to the `profiles.views.create_profile` view; if no profile model has been specified in the `AUTH_PROFILE_MODULE` setting, `django.contrib.auth.models.SiteProfileNotAvailable` will be raised. """ if username: # Making sure the logged in user has Managers groups. if not (request.user.profile.has_group("Managers") or request.user.is_superuser): return redirect("profiles_profile_detail", username) user = get_object_or_404(User, username=username) else: user = request.user try: profile = user.profile except ObjectDoesNotExist: return redirect("profiles_create_profile") form = ProfileForm(request.POST or None, request.FILES or None, instance=profile, request=request) if form.is_valid(): result = security_check(request, request.user) if result: return result old_values = { "email": request.user.email, "username": request.user.username, "first_name": request.user.first_name, "last_name": request.user.last_name, } updated_profile = form.save() changes = { change[0]: { "from": unicode(change[1][0]), "to": unicode(change[1][1]) } for change in updated_profile.changes.items() } for field_name in old_values.keys(): old = old_values[field_name] new = form.cleaned_data[field_name] if new != old: changes[field_name] = {"from": old, "to": new} Logger(user=request.user, content_object=profile, ip=request.META["REMOTE_ADDR"], event=Events.PROFILE_CHANGED, params=changes).save() return redirect(request.GET.get("next") or "profiles_my") return {"form": form, "profile": profile}
def make_payment(self, comment=None): log.debug("Making payment ID = %s..." % self.id) if self.is_committed: log.debug("Oops, already committed; terminating") return if isinstance(self, DepositRequest): form = self.payment_system.DepositForm is_deposit = True self.is_committed = True # We must take all care to not process same deposit twice self.save(refresh_state=True) c = self.payment_system.DepositForm.calculate_commission(self) c_full = self.payment_system.DepositForm.calculate_commission( self, full_commission=True) amount = c_full.amount - c_full.commission # Will be deposited as ExternalPay bonus_amount = c.amount - c.commission - amount # Commission compensation, deposited as BonusPaid if bonus_amount < Decimal("0.01"): bonus_amount = 0 elif isinstance(self, WithdrawRequest): is_deposit = False amount = -self.amount bonus_amount = 0 form = self.payment_system.WithdrawForm else: log.debug("Oops, unknown request type; terminating") raise TypeError("Unknown request type: %r" % type(self)) if self.account.currency != self.currency: if self.conversion_rate: amount = float(amount) * self.conversion_rate bonus_amount = float(bonus_amount) * self.conversion_rate else: amount = convert_currency(amount, from_currency=self.currency, to_currency=self.account.currency)[0] bonus_amount = convert_currency( bonus_amount, from_currency=self.currency, to_currency=self.account.currency)[0] mail_admins( u"Payment request id={} processed without saved exchange rate!" .format(self.pk), "") try: comment = comment or form.generate_mt4_comment(self) except Exception as e: log.debug("Oops, couldnt generate comment: %s; terminating" % unicode(e)) comment = unicode(self.id) try: log.debug("Sending change_balance command to TradingAccount...") res = self.account.change_balance( amount=amount, request_id=form.generate_mt4_request_id(self), comment=comment, transaction_type="ExternalPay") if bonus_amount: self.account.change_balance( amount=bonus_amount, request_id=form.generate_mt4_request_id(self) + 'B', comment=comment, transaction_type="BonusPaid") if is_deposit \ and self.needs_verification \ and not (self.params.get('cardnumber') and self.account.user.profile.is_card_verified(self.params['cardnumber'])): self.account.block( block_reason=TradingAccount.REASON_CHARGEBACK) self.params['chargeback_suspect'] = True user_profile = self.account.user.profile if not user_profile.manager: user_profile.autoassign_manager(force=True) # self.account.user.gcrm_contact.add_task(u"Client's account blocked to prevent chargeback. " # u"Monitor the situation.") notification.send( [self.account.user], "deposit_needs_verification", { "paymentrequest": self, 'usd_amount': self.amount_money.to("USD") }) except PlatformError as e: log.debug("Command change_balance failed: %s" % unicode(e)) if is_deposit: self.is_committed = None else: self.is_payed = False send_mail( u"Withdraw request failed", u"Withdraw request failed:\n" u"https://%s%s\n\n" u"Error: %s" % (settings.ROOT_HOSTNAME, get_admin_url(self), unicode(e)), from_email=settings.SERVER_EMAIL, recipient_list=[x[1] for x in settings.ADMINS]) Logger(user=None, content_object=self, ip=None, event=Events.WITHDRAW_REQUEST_FAILED, params={ 'error': e.message }).save() self.save() raise e else: if res is not None: self.refresh_state() self.trade_id = res.get("order_id") self.save(refresh_state=False) log.debug("Payment OK. OrderID = %s" % self.trade_id) else: log.debug("Payment OK, but OrderID is unknown :(") Logger(user=None, content_object=self, ip=None, event=Events.WITHDRAW_REQUEST_PAYED).save()
def update_requisit(request, create=False, commit=True): payment_system = load_payment_system(request.POST["ps"]) if create: form = payment_system.WithdrawForm(request.POST, request=request) if form.is_valid(): requisits = request.user.requisits.filter( purse=form.cleaned_data[form.get_purse_field_name()], is_deleted=False) if requisits: return True, requisits[0] req = form.save(commit=commit) req.user = request.user req.save() Logger(user=request.user, content_object=req, ip=request.META["REMOTE_ADDR"], event=Events.REQUISIT_CREATED).save() return True, req else: if hasattr(payment_system, "LinkForm") and 'requisit' in request.POST: requisit = request.user.requisits.filter( pk=request.POST['requisit']) if not requisit: raise requisit = requisit[0] form = payment_system.WithdrawForm(request.POST, request=request, instance=requisit) if form.is_valid(): instance = form.save(commit=False) changes = dict(instance.changes) # если изменили еще что-то кроме названия реквизита, # то создаем его копию, но уже с обновленными данными if changes: req = request.user.requisits.get( pk=request.POST['requisit']) if not (len(changes) == 1 and "alias" in changes): instance.previous = req instance.alias = request.POST.get("alias", False) or req.alias instance.pk = None instance.is_valid = False req.is_deleted = True if instance.user.profile.auth_scheme and instance.user.date_joined > datetime( 2013, 12, 6): instance.is_valid = True req_changes = { change[0]: { "from": unicode(change[1][0]), "to": unicode(change[1][1]) } for change in changes.items() } req_changes["new_requisit_id"] = instance.pk Logger(user=request.user, ip=request.META["REMOTE_ADDR"], event=Events.REQUISIT_CHANGED, content_object=req, params=req_changes).save() return True, instance else: instance.alias = changes["alias"][1] if commit: instance.save() return True, instance return False, form
def post(self, request, slug): # post form account_type = get_account_type(slug or request.POST.get("account_type")) if not account_type.is_demo and request.user.profile.status == request.user.profile.UNVERIFIED: return self.json_response({"redirect": redirect("verify_docs")}) if not account_type.is_demo and request.user.profile.status < request.user.profile.UNVERIFIED: return self.json_response({"redirect": redirect("account_app")}) if self.max_accounts_reached(request.user, account_type): return self.json_response( {"redirect": redirect("mt4_create_account", args=[slug])}) assert 'OK' if not (account_type.is_demo or request.user.profile.has_otp_devices): return security(request) form = account_type.account_form(request.POST, request=request, account_type=account_type) if form.is_valid(): form_result = form.save(profile=request.user.profile) if getattr(form.save, 'async', None): return self.json_response({ "ok": True, "wait": reverse("mt4_ajax_account_creation_done", args=[form_result]), }) account = form_result['account'] Logger(user=request.user, content_object=account, ip=request.META["REMOTE_ADDR"], event=Events.ACCOUNT_CREATED).save() return self.json_response({ "ok": True, "no_wait": True, "slug": account_type.slug, "mt4_id": account.mt4_id, "mt4_password": form_result["password"], "platform": account.platform_type, "login": account._login, "redirect": reverse("mt4_account_welcome", args=[account_type.slug, account.mt4_id]), }) return self.json_response({ "nok": True, "errors": {k: map(unicode, v) for k, v in form.errors.items()}, })
def login(request, next=None, *args, **kwargs): """ Main login view. """ next = request.REQUEST.get('next', next) user = None user_id = request.session.get("user_id") if user_id: del request.session[ "user_id"] # We probably don't need it for more than one pageload if User.objects.filter(pk=user_id).exists(): user = User.objects.get(pk=user_id) if next is None: if request.path != reverse('auth_login'): next = request.path else: next = '/account/profile/info' if request.method == "POST": ip = request.META["REMOTE_ADDR"] cache_key = 'login_%s' % ip login_try = cache.get(cache_key) # Anti-Bruteforce if login_try > 19: request.method = 'GET' messages.error( request, _(u'Your IP address has been blocked due to 20 unsuccessfull logon ' u'attempts. Please wait at least 20 minutes before trying again' )) cache.set(cache_key, login_try + 1, 20 * 60) subject = u'Возможная попытка взлома системы' message = u'IP %s пытается войти в систему. Данный IP был заблокирован на ближайшие ' \ u'20 минут, вследствие 20 неудачных попыток войти в систему.' % ip mail_admins(subject=subject, message=message) form = EmailAuthenticationForm( data=request.POST or None, request=request, prefix="auth", label_suffix='', initial={ 'login_from': get_private_office_from_next(next), 'email_phone': user.profile.phone_mobile if user else None }) if request.method == "POST": if form.is_valid(): user = form.get_user() if user.last_login == datetime.fromtimestamp( 0) and not user.profile.has_otp_devices: SMSDevice.objects.create( user=user, phone_number=user.profile.phone_mobile) user.profile.make_valid("phone_mobile") user.profile.lost_otp = False user.profile.save() # if user.profile.ask_on_login: # result = security_check(request, user) # if result: # return result django_login(request, user) Logger(content_object=request.user, ip=request.META["REMOTE_ADDR"], user=request.user, event=Events.LOGIN_OK).save() profile = request.user.profile language = request.session.get('django_language', settings.LANGUAGE_CODE) if profile.language != language: profile.language = language profile.save() if not form.cleaned_data["remember"]: days = 0 # Log the user out after a day. else: days = settings.LOGIN_FOR request.session.set_expiry(60 * 60 * 24 * days) if request.user.profile.lost_otp: if request.is_ajax(): return { "ok": True, "redirect": reverse("otp_security") + "?next=" + next } next_url = '{}://{}{}'.format(request.META['wsgi.url_scheme'], request.get_host(), request.GET.get("next", "/")) request.session['login_ts'] = time.time() request.session['xnext'] = '{}://{}{}'.format( request.META['wsgi.url_scheme'], request.get_host(), request.GET.get("next", "/")) if settings.XDOMAINS and not request.user.profile.registered_from: request.session['redirect_ts'] = time.time() request.session['xnext'] = next_url session_hashed = hashlib.md5( request.session.session_key).hexdigest() cache.set('sess_' + session_hashed, request.session.session_key, 30) redirect_to = '{}://{}{}?token={}'.format( request.META['wsgi.url_scheme'], settings.XDOMAINS[0], reverse('xdomain_auth'), session_hashed) else: redirect_to = next_url if request.is_ajax(): return {"ok": True, "simple_redirect": redirect_to} print redirect_to return redirect(redirect_to) else: # сделано из-за странной ошибки с именованием поля. # видимо, где-то есть форма со старым названием поля; # можно удалить лет через 10, когда все устаканится email = request.POST.get("auth-email_phone") or request.POST.get( "email") users = User.objects.filter(email=email) kwargs = {"content_object": users[0]} if users else {} Logger(ip=request.META["REMOTE_ADDR"], event=Events.LOGIN_FAIL, params={ "email": email }, **kwargs).save() if login_try: cache.set(cache_key, login_try + 1, 20 * 60) else: cache.set(cache_key, 1, 20 * 60) if request.is_ajax(): return { "nok": True, "errors": {k: map(unicode, v) for k, v in form.errors.items()} } if request.is_ajax(): return render_to_response( "reveal_forms/login.html", RequestContext(request, { "form": form, "next": next })) return {"form": form, "next": next, "first_login": True if user else False}
def create_account(request, slug, extra_context=None): account_type = get_account_type(slug) if not account_type: raise Http404() if account_type.login_required and request.user.is_anonymous(): return redirect(settings.LOGIN_URL + "?next=%s" % request.path) if not (account_type.is_demo or request.user.profile.has_otp_devices): messages.info( request, _("You need to set up a secure authentication method before opening a Real account." )) return redirect(reverse("otp_security") + "?next=" + request.path) num_of_accounts = CreateAccountView.max_accounts_reached( request.user, account_type) if num_of_accounts: return { 'documents_unverified': False, "too_many_accounts": True, "num_of_accounts": num_of_accounts, "acc_type": account_type } if request.POST: form = account_type.account_form(request.POST, request.FILES, request=request) if form.is_valid(): form_result = form.save(profile=request.user.profile) if form.save. async: return redirect("mt4_wait_for_account_creation", form_result) else: if isinstance(form_result, HttpResponse): return form_result Logger(user=request.user, content_object=form_result, ip=request.META["REMOTE_ADDR"], event=Events.ACCOUNT_CREATED).save() kwargs = { "slug": account_type.slug, "account_id": form_result.mt4_id } done_url = reverse('mt4_account_welcome', kwargs=kwargs) if request.GET.get('next'): return redirect(done_url + '?next=%s' % request.GET.get('next')) else: return redirect(done_url) else: form = account_type.account_form(request=request) result = {"forms": {"account": form}} if extra_context is not None: result.update(extra_context) return result