Django how to maintain a session? - django-sessions

I'm developing an e-commerce site and I'm working on the shopping cart functionality. When the user is not connected I create a session for him so that he can add products to the basket which is normal, when the user decides to place this order I ask him to connect but when he connects he loses the session that I had created for him and another session is assigned to him. The cause is that once connected it loses all its products selected in the screen. After reading the documentation on django sessions I found nothing that could help me.
here is my code for more details:
models.py
class Cart(models.Model):
session_id = models.CharField(max_length=150)
product = models.ForeignKey(Products, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=0, validators=[MinValueValidator(1)])
updated = models.fields.DateTimeField(auto_now=True)
created = models.fields.DateTimeField(auto_now_add=True)
deleted = models.fields.BooleanField(default=False)
def __str__(self) -> str:
return str(self.product)
views.py
class FrontProductAddCart(View):
def post(self, request, product_pk):
session_id = request.session._get_or_create_session_key()
product = models.Products.objects.get(pk=product_pk)
objet, create = models.Cart.objects.get_or_create(session_id=session_id, product=product)
quantity = request.POST.get("quantity")
if quantity:
objet.quantity = quantity
objet.save()
else:
objet.quantity += 1
objet.save()
return HttpResponse(
"",
headers={
"HX-Trigger": json.dumps({
"product_add_cart": context_processors.get_total_number_products(request)
})
}
)

Related

Shopify Multipass created_at Field

I am currently trying to implement a login to Shopify over the Storefront API via Multipass.
However, what it isn't clear to me from the Documentation on that Page, how the "created_at" Field is used. Since it states that this field should be filled with the current timestamp.
But what if the same users logs in a second time via Multipass, should it be filled with the timestamp of the second login.
Or should the original Multipass token be stored somewhere, and reused at a second login, instead of generating a new one?
Yes you need to set it always to the current time. I guess it stands for "token created at".
This is the code I use in Python:
class Multipass:
def __init__(self, secret):
key = SHA256.new(secret.encode('utf-8')).digest()
self.encryptionKey = key[0:16]
self.signatureKey = key[16:32]
def generate_token(self, customer_data_hash):
customer_data_hash['created_at'] = datetime.datetime.utcnow().isoformat()
cipher_text = self.encrypt(json.dumps(customer_data_hash))
return urlsafe_b64encode(cipher_text + self.sign(cipher_text))
def generate_url(self, customer_data_hash, url):
token = self.generate_token(customer_data_hash).decode('utf-8')
return '{0}/account/login/multipass/{1}'.format(url, token)
def encrypt(self, plain_text):
plain_text = self.pad(plain_text)
iv = get_random_bytes(AES.block_size)
cipher = AES.new(self.encryptionKey, AES.MODE_CBC, iv)
return iv + cipher.encrypt(plain_text.encode('utf-8'))
def sign(self, secret):
return HMAC.new(self.signatureKey, secret, SHA256).digest()
#staticmethod
def pad(s):
return s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size)
And so
...
customer_object = {
**user,# customer data
"verified_email": True
}
multipass = Multipass(multipass_secret)
return multipass.generate_url(customer_object, environment["url"])
How can someone login a second time? If they are already logged in, they would not essentially be able to re-login without logging out. If they logged out, the multi-pass would assign a new timestamp. When would this flow occur of a user logging in a second time and not being issued a brand new login? How would they do this?

Using telebot register_next_step_handler structure I get error with mixed users' data

I want to get user's nickname and after that to get user's screenshot. Than all the data will be send to Google Sheet. But I have the problem. When multiple users(at least 2) are using bot at the same time, their data are mixed up. For example first user's nickname is second user's nickname or first user's id is second user's id. Can I make a unique user session to store data in unique user class. It means for each user it will be created their own user class. Here is the code:
#bot.message_handler(commands=['start'])
def send_hello(message):
bot.send_message(message.chat.id, "Hi! Let`s start verification.")
msg = bot.send_message(message.chat.id, "Enter your nickname:")
bot.register_next_step_handler(msg, process_nickname)
def process_nickname(message):
user.name=message.text
user.id=message.from_user.id
msg = bot.send_message(message.chat.id, 'Super! Now send screenshot:')
bot.register_next_step_handler(msg, process_screenshot)
def process_screenshot(message):
fileID = message.photo[-1].file_id
file = bot.get_file(fileID)
file_path=file.file_path
metadata = {
'name': user.name,
'parents':[folder_id]
}
url=(f"https://api.telegram.org/file/bot{token}/{file_path}")
response = requests.get(url)
image_data = BytesIO(response.content)
media=MediaIoBaseUpload(image_data, 'image/jpeg')
serviceDrive.files().create(body=metadata,media_body=media,fields='id').execute()

Telegram bot: How to get chosen inline result

I'm sending InlineQueryResultArticle to clients and i'm wondering how to get chosen result and it's data (like result_id,...).
here is the code to send results:
token = 'Bot token'
bot = telegram.Bot(token)
updater = Updater(token)
dispatcher = updater.dispatcher
def get_inline_results(bot, update):
query = update.inline_query.query
results = list()
results.append(InlineQueryResultArticle(id='1000',
title="Book 1",
description='Description of this book, author ...',
thumb_url='https://fakeimg.pl/100/?text=book%201',
input_message_content=InputTextMessageContent(
'chosen book:')))
results.append(InlineQueryResultArticle(id='1001',
title="Book 2",
description='Description of the book, author...',
thumb_url='https://fakeimg.pl/300/?text=book%202',
input_message_content=InputTextMessageContent(
'chosen book:')
))
update.inline_query.answer(results)
inline_query_handler = InlineQueryHandler(get_inline_results)
dispatcher.add_handler(inline_query_handler)
I'm looking for a method like on_inline_chosen(data) to get id of the chosen item. (1000 or 1001 for snippet above) and then send the appropriate response to user.
You should set /setinlinefeedback in #BotFather, then you will get this update
OK, i got my answer from here
Handling user chosen result:
from telegram.ext import ChosenInlineResultHandler
def on_result_chosen(bot, update):
print(update.to_dict())
result = update.chosen_inline_result
result_id = result.result_id
query = result.query
user = result.from_user.id
print(result_id)
print(user)
print(query)
print(result.inline_message_id)
bot.send_message(user, text='fetching book data with id:' + result_id)
result_chosen_handler = ChosenInlineResultHandler(on_result_chosen)
dispatcher.add_handler(result_chosen_handler)

Get Transaction Id after completing Payment Objective c?

I was trying to get transation Id when paypal payment is done that is on didCompletePayment method, i can get only these details
Confirmation: {
client = {
environment = sandbox;
"paypal_sdk_version" = "2.12.2";
platform = iOS;
"product_name" = "PayPal iOS SDK";
};
response = {
"create_time" = "2017-02-01T07:40:43Z";
id = "PAY-4RK70135CF912010FLCIZB5A";
intent = sale;
state = approved;
};
"response_type" = payment;
}
I don't find transation ID here. Can any one suggest me how to get transation Id in detail so that i can save that to database.
I found some Curl concepts but i'm not sure where to start with.Please give me some suggestions.
Thanks in advance

Integration Quickbook online api to rails app

I am integrating
rails application to Quickbooks online
using API.
Use gem Quickbooks-ruby
But want to add discount, add taxes into invoice but not success even not found how to pass in API.
invoice = Quickbooks::Model::Invoice.new
invoice.customer_id = 1
invoice.txn_date = Date.civil(2014, 3, 27)
invoice.doc_number = "001"
transaction_tax = Quickbooks::Model::TransactionTaxDetail.new
# Point to a saved tax code in QBO, e.g. this points to id = 2,
# which is a NYC tax code saved on QBO account = 10% sales tax
transaction_tax.txn_tax_code_id = 2
transaction_tax.total_tax = 134.10
invoice.txn_tax_detail = transaction_tax
sales_line_item = Quickbooks::Model::InvoiceLineItem.new
sales_line_item.amount = 1490
sales_line_item.description = "CCM ice skates"
sales_line_item.sales_item! do |detail|
detail.unit_price = 149
detail.quantity = 10
detail.item_id = 1 # Item ID here
detail.tax_code_id = 'TAX' # for US must be 'NON' or 'TAX'
end
discount_line_item = Quickbooks::Model::InvoiceLineItem.new
discount_line_item.amount = 149
discount_line_item.discount_item! do |detail|
detail.discount_percent = 10
detail.percent_based = true
detail.discount_account_id = 99
end
invoice.line_items << sales_line_item
invoice.line_items << discount_line_item
service = Quickbooks::Service::Invoice.new
service.access_token = OAuth::AccessToken.new($qb_oauth_consumer, "token", "secret")
service.company_id = "9991111222"
created_invoice = service.create(invoice)
There should be something like JAXB in ruby for object serialization/deserialization.
From the following link, you can download QB endpoint definations and data class defination(as XSD). You need to generate data classes from it.
https://developer.intuit.com/docs/#api/deki/files/2466/v3.1_dataservices.zip
Then using any standard ruby based OAuth lib, you can make call to QB API Endpoints.
You can use the setter methods of the data class( in your case - invoice ) to populate data/to construct the payload. ( I don't have any ready example of this. But I guess it is not hard to find in net)
For doc, you can refer the following two links.
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/030_entity_services_reference/invoice
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/030_entity_services_reference/invoice#DiscountLineDetail
Thanks