def login(self, context={}): set_active_user(None) data = context["data"] db_name = data.get("db_name") if not db_name: raise Exception("Missing db name") database.set_active_db(db_name) login = data["login"] password = data["password"] user_id = get_model("base.user").check_password(login, password) if not user_id: audit_log("Invalid login (%s)" % login) db = database.get_connection() db.commit() raise Exception("Invalid login") try: print("login ok", login) set_active_user(1) user = get_model("base.user").browse(user_id) if user.profile_id.prevent_login or not user.active: raise Exception("User not allowed to login") t = time.strftime("%Y-%m-%d %H:%M:%S") user.write({"lastlog": t}) profile = user.profile_id action = profile.home_action or "account_board" token = new_token(db_name, user_id) db = database.get_connection() res = db.get("SELECT * FROM pg_class WHERE relname='settings'") settings = get_model("settings").browse(1) version = settings.version mod_version = get_module_version() if version != mod_version: raise Exception("Database version (%s) is different than modules version (%s), please upgrade database before login." % ( version, mod_version)) company_id = user.company_id.id or profile.login_company_id.id if not company_id: res = get_model("company").search([["parent_id", "=", None]]) if not res: raise Exception("No company found") company_id = res[0] comp = get_model("company").browse(company_id) return { "cookies": { "dbname": database.get_active_db(), "user_id": user_id, "token": token, "user_name": user.name, "package": settings.package, "company_id": company_id, "company_name": comp.name, }, "next": { "type": "url", "url": "/ui#name=%s" % action, }, "login_action": action, } finally: set_active_user(user_id) audit_log("Login")
def get(self): self.get_argument("token") # TODO: check token dbname=database.get_active_db() db=database.get_connection() try: db.begin() set_active_user(None) user_id=1 user=get_model("base.user").browse(user_id) t=time.strftime("%Y-%m-%d %H:%M:%S") user.write({"lastlog":t}) comp=get_model("company").browse(1) set_active_user(user_id) audit_log("Login token") url="http://nf1.netforce.com/update_lastlogin?dbname=%s"%dbname req=urllib.request.Request(url) try: urllib.request.urlopen(req).read() except: print("ERROR: failed to update last login time") token=new_token(dbname,user_id) self.set_cookie("dbname",dbname) self.set_cookie("user_id",str(user_id)) self.set_cookie("token",token) self.set_cookie("user_name",quote(user.name)) # XXX: space self.set_cookie("company_name",quote(comp.name)) self.set_cookie("package",comp.package) self.redirect("http://%s.my.netforce.com/action#name=account_board"%dbname.replace("_","-")) db.commit() except: db.rollback()
def login(self,email,password,context={}): print("EcomInterface.login",email,password) user_id=get_model("base.user").check_password(email,password) if not user_id: raise Exception("Invalid login") user=get_model("base.user").browse(user_id) contact=user.contact_id dbname=database.get_active_db() return { "user_id": user_id, "token": utils.new_token(dbname,user_id), "contact_id": contact.id, }
def post(self): db = get_connection() try: try: print("CHECK protocol XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") print(self.request.protocol) print("CHECK protocol XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") fields = ["email", "password"] field_errors = {} form_vals = {} for n in fields: v = self.get_argument(n, None) form_vals[n] = v if not v: field_errors[n] = True if field_errors: raise Exception("Some required fields are missing") user_id = get_model("base.user").check_password( form_vals["email"], form_vals["password"]) if not user_id: raise Exception("Invalid login") set_active_user(user_id) dbname = get_active_db() token = new_token(dbname, user_id) self.set_cookie("user_id", str(user_id)) self.set_cookie("token", token) cart_id = self.get_cookie("cart_id") if cart_id: cart_id = int(cart_id) get_model("ecom.cart").set_default_address([cart_id]) db.commit() url = self.get_argument("return_url", None) if not url: url = "/cms_account" self.redirect(url) except Exception as e: db = get_connection() error_message = str(e) ctx = self.context ctx["form_vals"] = form_vals ctx["error_message"] = error_message ctx["field_errors"] = field_errors content = render("cms_login", ctx) ctx["content"] = content html = render("cms_layout", ctx) self.write(html) db.commit() except: import traceback traceback.print_exc() db.rollback()
def post(self): db=get_connection() try: try: print("CHECK protocol XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") print(self.request.protocol) print("CHECK protocol XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") fields=["email","password"] field_errors={} form_vals={} for n in fields: v=self.get_argument(n,None) form_vals[n]=v if not v: field_errors[n]=True if field_errors: raise Exception("Some required fields are missing") user_id=get_model("base.user").check_password(form_vals["email"],form_vals["password"]) if not user_id: raise Exception("Invalid login") set_active_user(user_id) dbname=get_active_db() token=new_token(dbname,user_id) self.set_cookie("user_id",str(user_id)) self.set_cookie("token",token) cart_id=self.get_cookie("cart_id") if cart_id: cart_id=int(cart_id) get_model("ecom.cart").set_default_address([cart_id]) db.commit() url=self.get_argument("return_url",None) if not url: url="/cms_account" self.redirect(url) except Exception as e: db=get_connection() error_message=str(e) ctx=self.context ctx["form_vals"]=form_vals ctx["error_message"]=error_message ctx["field_errors"]=field_errors content=render("cms_login",ctx) ctx["content"]=content html=render("cms_layout",ctx) self.write(html) db.commit() except: import traceback traceback.print_exc() db.rollback()
def sign_up(self,vals,context={}): print("EcomInterface.sign_up",vals,context) res=get_model("base.user").search([["email","=",vals["email"]]]) if res: raise Exception("User already exists with same email") res=get_model("contact").search([["email","=",vals["email"]]]) if res: raise Exception("Contact already exists with same email") cont_vals={ "first_name": vals["first_name"], "last_name": vals["last_name"], "email": vals["email"], "customer":True, } contact_id=get_model("contact").create(cont_vals) res=get_model("profile").search([["code","=","ECOM_CUSTOMER"]]) if not res: raise Exception("Customer user profile not found") profile_id=res[0] user_vals={ "name": "%s %s"%(vals["first_name"],vals["last_name"]), "login": vals["email"], "profile_id": profile_id, "contact_id": contact_id, "password": vals["password"], } user_id=get_model("base.user").create(user_vals) addr_vals = { "first_name": vals["first_name"], "last_name": vals["last_name"], "province_id": vals["province_id"], "type": "billing", "postal_code" : vals["postal_code_id"], "address": vals["address"], "contact_id": contact_id, "mobile": vals["mobile"], "instructions_messenger" :vals['messenger'], } if vals.get("subdistrict_id"): subdistrict_id = vals["subdistrict_id"] if subdistrict_id: addr_vals['subdistrict_id'] = subdistrict_id get_model("address").create(addr_vals) get_model("contact").trigger([contact_id],"ecom_sign_up") dbname=database.get_active_db() return { "user_id": user_id, "token": utils.new_token(dbname,user_id), "contact_id" : contact_id, }
def post(self): website=self.context["website"] db = get_connection() try: if self.get_argument("commit", None): cart_id = self.get_argument("cart_id") cart_id = int(cart_id) fnames = [ "accept_marketing", ] vals = {} for n in fnames: v = self.get_argument(n, None) f = get_model("ecom.cart")._fields[n] if v: if isinstance(f, fields.Boolean): v = v and True or False elif isinstance(f, fields.Many2One): v = int(v) vals[n] = v if self.get_argument("check_tax", None): if not self.get_argument("tax_no", None): raise Exception("Please Enter Tax ID") vals["tax_no"] = self.get_argument("tax_no", None) else: vals["tax_no"] = "" if self.get_argument("tax_branch_no",None): vals["tax_branch_no"]= self.get_argument("tax_branch_no",None) else: vals["tax_branch_no"]= "" pay_method=self.get_argument("pay_method",None) if not pay_method: raise Exception("Missing payment method") if pay_method=="bank_transfer": pay_method_id=website.bank_method_id.id elif pay_method=="paypal": pay_method_id=website.paypal_method_id.id elif pay_method=="paysbuy": pay_method_id=website.paysbuy_method_id.id elif pay_method=="scb_gateway": pay_method_id=website.scb_method_id.id else: raise Exception("Invalid payment method") if not pay_method_id: raise Exception("Payment method not configured") vals["pay_method_id"]=pay_method_id print("CART VALS", vals) get_model("ecom.cart").write([cart_id], vals) for arg in self.request.arguments: if not arg.startswith("LINE_SHIP_METHOD_"): continue line_id=int(arg.replace("LINE_SHIP_METHOD_","")) ship_method_code=self.get_argument(arg) if ship_method_code: res=get_model("ship.method").search([["code","=",ship_method_code]]) if not res: raise Exception("Shipping method not found: %s"%ship_method_code) ship_method_id=res[0] else: ship_method_id=None vals={ "ship_method_id": ship_method_id, } print("line_id=%s => ship_method_id=%s"%(line_id,ship_method_id)) get_model("ecom.cart.line").write([line_id],vals) cart = get_model("ecom.cart").browse(cart_id) is_accept = self.get_argument("accept_marketing", None) if is_accept == 'on': user_id = 1 res = get_model("sale.lead").search([["email", "=", cart.email]]) if not res: # Check if this email already exist in Newsletter contact vals = { "state": "open", "first_name": cart.bill_first_name, "last_name": cart.bill_last_name, "email": cart.email, "user_id": user_id, } get_model("sale.lead").create(vals) if not website.target_list_id: raise Exception("No target list") list_id = website.target_list_id.id res = get_model("mkt.target").search([["email", "=", cart.email], ["list_id", "=", list_id]]) if not res: target_vals = { "list_id": list_id, "first_name": cart.bill_first_name, "last_name": cart.bill_last_name, "email": cart.email, "company": cart.bill_company, "city": cart.bill_city, "province_id": cart.bill_province_id.id, "country_id": cart.bill_country_id.id, "phone": cart.bill_phone, "zip": cart.bill_postal_code, } get_model("mkt.target").create(target_vals) user_id = get_active_user() if not user_id and website.auto_create_account: user_id = cart.create_account() dbname = get_active_db() token = new_token(dbname, user_id) self.set_cookie("user_id", str(user_id)) self.set_cookie("token", token) set_active_user(1) set_active_company(1) cart.copy_to_contact({'force_write': False}) if not user_id and website.auto_create_account: #First time create account get_model("contact").trigger([cart.contact_id.id],"ecom_register") cart.copy_to_sale() cart = get_model("ecom.cart").browse(cart_id) db.commit() # XXX: need otherwise browser redirect before commit? self.clear_cookie("cart_id") meth=cart.pay_method_id if not meth: raise Exception("Missing payment method") if meth.type == "bank": self.redirect("/ecom_order_confirmed?cart_id=%s" % cart.id) elif meth.type == "paypal": if not meth.paypal_user: raise Exception("Missing paypal user") if not meth.paypal_password: raise Exception("Missing paypal password") if not meth.paypal_signature: raise Exception("Missing paypal signature") if not meth.paypal_url: raise Exception("Missing paypal URL Server") if meth.paypal_url == "test": url = "https://api-3t.sandbox.paypal.com/nvp" else: url = "https://api-3t.paypal.com/nvp" params = { "method": "SetExpressCheckout", "PAYMENTREQUEST_0_ITEMAMT": "%.2f" % (cart.amount_total - cart.amount_ship), "PAYMENTREQUEST_0_AMT": "%.2f" % cart.amount_total, "PAYMENTREQUEST_0_SHIPPINGAMT": "%.2f" % cart.amount_ship, "PAYMENTREQUEST_0_CURRENCYCODE": "THB", "PAYMENTREQUEST_0_PAYMENTACTION": "Sale", "PAYMENTREQUEST_0_INVNUM": cart.number, "returnUrl": "%s://%s/ecom_return_paypal?cart_id=%s" % (self.request.protocol, self.request.host, cart.id), "cancelUrl": "%s://%s/ecom_order_cancelled?cart_id=%s" % (self.request.protocol, self.request.host, cart.id), "version": "104.0", "user": meth.paypal_user, "pwd": meth.paypal_password, "signature": meth.paypal_signature, } for i, line in enumerate(cart.lines): params.update({ "L_PAYMENTREQUEST_0_NAME%d" % i: line.product_id.name, "L_PAYMENTREQUEST_0_AMT%d" % i: "%.2f" % (line.amount / line.qty), "L_PAYMENTREQUEST_0_QTY%d" % i: "%d" % line.qty, }) try: r = requests.get(url, params=params) print("URL", r.url) print("params", params) res = urllib.parse.parse_qs(r.text) print("RES", res) token = res["TOKEN"][0] except: raise Exception("Failed start paypal transaction") print("TOKEN", token) if meth.paypal_url == "test": url = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=%s" % token else: url = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=%s" % token self.redirect(url) elif meth.type == "paysbuy": psbID = meth.paysbuy_id if not meth.paysbuy_username: raise Exception("Missing paysbuy username") username = meth.paysbuy_username if not meth.paysbuy_securecode: raise Exception("Missing paysbuy secure code") secureCode = meth.paysbuy_securecode if not meth.paysbuy_url: raise Exception("Missing paysbuy server URL") if meth.paysbuy_url == "test": url = "http://demo.paysbuy.com/api_paynow/api_paynow.asmx/api_paynow_authentication_new" else: url = "https://paysbuy.com/api_paynow/api_paynow.asmx/api_paynow_authentication_new" itm = " & ".join(["%s x %s" % (line.product_id.name, line.qty) for line in cart.lines]) data = { "psbId": psbID, "username": username, "secureCode": secureCode, "inv": cart.number, "itm": itm, "amt": "%.2f" % cart.amount_total, "curr_type": "TH", "method": 1, "language": "T", "resp_front_url": "%s://%s/ecom_return_paysbuy?cart_id=%s" % (self.request.protocol, self.request.host, cart.id), "resp_back_url": "%s://%s/ecom_notif_paysbuy?cart_id=%s" % (self.request.protocol, self.request.host, cart.id), "paypal_amt": "", "com": "", "opt_fix_redirect": "1", "opt_fix_method": "", "opt_name": "", "opt_email": "", "opt_mobile": "", "opt_address": "", "opt_detail": "", } print("url", url) print("Data sent to paysbuy:") pprint(data) try: r = requests.post(url, data=data) print("Paysbuy response:", r.text) res = r.text.encode(encoding="utf-8") parser = etree.XMLParser(ns_clean=True, recover=True, encoding='utf-8') tree = etree.fromstring(res, parser) response = tree.text code = response[0:2] refid = response[2:] print("refid: %s" % refid) except: raise Exception("Failed start paysbuy transaction") if code == "00": if meth.paysbuy_url == "test": url = "http://demo.paysbuy.com/api_payment/paynow.aspx?refid=%s" % refid else: url = "https://paysbuy.com/api_payment/paynow.aspx?refid=%s" % refid else: raise Exception("Invalid paysbuy response code: %s" % code) self.redirect(url) elif meth.type == "scb_gateway": if not meth.scb_mid: raise Exception("Missing SCB merchant ID") mid = meth.scb_mid if not meth.scb_terminal: raise Exception("Missing SCB terminal ID") terminal = meth.scb_terminal if not meth.scb_url: raise Exception("Missing SCB server URL") sale_date = time.strptime(cart.date_created, '%Y-%m-%d %H:%M:%S') date = time.strftime('%Y%m%d%H%M%S', sale_date) params = [ ('mid', mid), ('terminal', terminal), ('command', 'CRAUTH'), ('ref_no', cart.number), ('ref_date', date), ('service_id', 10), ('cur_abbr', 'THB'), ('amount', '%.2f' % float(cart.amount_total)), ('backURL', 'http://%s/ecom_returnscb?cart_id=%s' % (self.request.host, cart.id)) ] urlparams = '&'.join(['%s=%s' % (k, v) for (k, v) in params]) if meth.scb_url == "test": url = 'https://nsips-test.scb.co.th:443/NSIPSWeb/NsipsMessageAction.do?' + urlparams else: url = 'https://nsips.scb.co.th/NSIPSWeb/NsipsMessageAction.do?' + urlparams self.redirect(url) else: raise Exception("Unsupported payment method") db.commit() except Exception as e: import traceback traceback.print_exc() error_message = str(e) ctx = self.context cart = ctx.get("cart") if not cart: db.commit() self.redirect("/index") return ctx["ship_methods"] = cart.get_ship_methods() website=self.context["website"] ctx["error_message"] = error_message content = render("ecom_checkout2", ctx) ctx["content"] = content html = render("cms_layout", ctx) self.write(html) db.rollback()
def post(self): db=get_connection() try: try: cart_id=self.get_argument("cart_id",None) fields=["first_name","last_name","email","password","re_password"] form_vals={} if cart_id: cart_id=int(cart_id) cart=get_model("ecom.cart").browse(cart_id) password=self.get_argument("password",None) form_vals={ "first_name": cart.bill_first_name, "last_name": cart.bill_last_name, "email": cart.email, "password": password, "re_password": password, } else: cart_id=self.get_cookie("cart_id") #In case of have a cart and register with register form for n in fields: form_vals[n]=self.get_argument(n,None) field_errors={} for n in fields: if not form_vals.get(n): field_errors[n]=True if field_errors: raise Exception("Some required fields are missing") website=self.context["website"] if not website.user_profile_id.id: raise Exception("Missing user profile in website settings") res=get_model("base.user").search([["login","=",form_vals["email"]]]) if res: raise Exception("An account with this email already exists") if len(form_vals["password"])<6: raise Exception("Password is too short (Minimum 6 Characters)") if form_vals["password"] != form_vals["re_password"]: raise Exception("Password and Re-Type Password does not match!") vals={ "name": form_vals["first_name"]+" "+form_vals["last_name"], "login": form_vals["email"], "password": form_vals["password"], "email": form_vals["email"], "profile_id": website.user_profile_id.id, } user_id=get_model("base.user").create(vals) get_model("base.user").trigger([user_id],"create_user",context={"password": form_vals["password"]}) if not website.contact_categ_id.id: raise Exception("Missing contact category in website settings") if not utils.check_email_syntax(form_vals["email"]): raise Exception("Invalid email syntax!!") res=get_model("contact").search([["email","=",form_vals["email"]],["categ_id","=",website.contact_categ_id.id]]) if res: contact_id=res[0] else: vals={ "type": "person", "first_name": form_vals["first_name"], "last_name": form_vals["last_name"], "email": form_vals["email"], "categ_id": website.contact_categ_id.id, "account_receivable_id": website.account_receivable_id.id, "customer" : True, } contact_id=get_model("contact").create(vals) get_model("contact").trigger([contact_id],"ecom_register") get_model("contact").write([contact_id],{"user_id":user_id}) get_model("base.user").write([user_id],{"contact_id":contact_id}) tmpl=website.create_account_email_tmpl_id if tmpl: data={ "email": form_vals["email"], "first_name": form_vals["first_name"], "last_name": form_vals["last_name"], "new_password": form_vals["password"], } tmpl.create_email(data) dbname=get_active_db() token=new_token(dbname,user_id) print("commit") db.commit() self.set_cookie("user_id",str(user_id)) self.set_cookie("token",token) print("redirect") if cart_id: if user_id: set_active_user(user_id) cart_id=int(cart_id) get_model("ecom.cart").set_default_address([cart_id]) self.next_page() except Exception as e: db=get_connection() error_message=str(e) ctx=self.context ctx["form_vals"]=form_vals ctx["error_message"]=error_message ctx["field_errors"]=field_errors content=render("cms_register",ctx) ctx["content"]=content html=render("cms_layout",ctx) self.write(html) print("commit") db.commit() except: import traceback traceback.print_exc() print("rollback") db.rollback()
def login(self, context={}): set_active_user(None) data = context["data"] db_name = data.get("db_name") if not db_name: raise Exception("Missing db name") database.set_active_db(db_name) login = data["login"] password = data["password"] user_id = get_model("base.user").check_password(login, password) if not user_id: audit_log("Invalid login (%s)" % login) db = database.get_connection() db.commit() raise Exception("Invalid login") try: print("login ok", login) set_active_user(1) user = get_model("base.user").browse(user_id) if user.profile_id.prevent_login or not user.active: raise Exception("User not allowed to login") t = time.strftime("%Y-%m-%d %H:%M:%S") user.write({"lastlog": t}) profile = user.profile_id action = profile.home_action or "account_board" token = new_token(db_name, user_id) db = database.get_connection() res = db.get("SELECT * FROM pg_class WHERE relname='settings'") settings = get_model("settings").browse(1) version = settings.version mod_version = get_module_version_name() if version != mod_version: raise Exception( "Database version (%s) is different than modules version (%s), please upgrade database before login." % (version, mod_version)) company_id = user.company_id.id or profile.login_company_id.id if not company_id: res = get_model("company").search([["parent_id", "=", None]]) if not res: raise Exception("No company found") company_id = res[0] comp = get_model("company").browse(company_id) return { "cookies": { "dbname": database.get_active_db(), "user_id": user_id, "token": token, "user_name": user.name, "package": settings.package, "company_id": company_id, "company_name": comp.name, }, "next": { "type": "url", "url": "/ui#name=%s" % action, }, "login_action": action, } finally: set_active_user(user_id) audit_log("Login")