Browse Source

New Login flow for user creation

master
administrator 2 years ago
parent
commit
e23364b056
  1. 4
      .gitignore
  2. 473
      smart_service/apis/app_user_login.py

4
.gitignore

@ -1,2 +1,2 @@
*.pyc #Ignore all pyc files
__pycache__/ *.pyc

473
smart_service/apis/app_user_login.py

@ -1,19 +1,19 @@
import frappe
import time
from frappe.model.document import Document
import json import json
import requests
import re import re
from frappe.utils import now import time
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
from copy import copy
import frappe
import requests
from frappe.utils import now
current_db_name = frappe.conf.get("db_name") current_db_name = frappe.conf.get("db_name")
# Temporary Login # Temporary Login
@frappe.whitelist(allow_guest=True) @frappe.whitelist(allow_guest=True)
def app_user_validation_test(): def app_user_validation_test():
dicData= {} dicData = {}
try: try:
doc = frappe.get_doc("Fish", None) doc = frappe.get_doc("Fish", None)
dicData['token'] = doc.apple dicData['token'] = doc.apple
@ -22,24 +22,19 @@ def app_user_validation_test():
return {'status': 0, 'error': 'Site Error'} return {'status': 0, 'error': 'Site Error'}
return dicData return dicData
@frappe.whitelist(allow_guest=True) @frappe.whitelist(allow_guest=True)
def app_user_validation(usr=None, pwd=None): def app_user_validation(usr=None, pwd=None):
val=input_validation(usr=usr,pwd=pwd) val = input_validation(usr=usr, pwd=pwd)
if val!='': if val != '':
return {'status': 0, 'error': "Parameter's missing: " + val} return {'status': 0, 'error': "Parameter's missing: " + val}
# if usr == None and pwd == None:
# return {'status': 0, 'error': "Parameter's missing: Usr & pwd"}
# if usr == None:
# return {'status': 0, 'error': "Parameter missing: Usr"}
# if pwd == None:
# return {'status': 0, 'error': "Parameter missing: Pwd"}
preference = frappe.get_last_doc('App Preference') preference = frappe.get_last_doc('App Preference')
mahindra_login = preference.mahindra_login_api mahindra_login = preference.mahindra_login_api
technician_login = preference.technician_login_api technician_login = preference.technician_login_api
# ISmartAuth API - Email available
try: try:
data = {'LoginID': usr, 'Password': pwd} data = {'LoginID': usr, 'Password': pwd}
headers = {"Content-Type": "application/x-www-form-urlencoded"} headers = {"Content-Type": "application/x-www-form-urlencoded"}
@ -92,8 +87,6 @@ def app_user_validation(usr=None, pwd=None):
"EmailId": "{}@email.com".format(usr), "EmailId": "{}@email.com".format(usr),
"isLDAPAuthenticated": ""} "isLDAPAuthenticated": ""}
success_msg = None
user_name = None
msgDic = {} msgDic = {}
try: try:
@ -142,8 +135,6 @@ def app_user_validation(usr=None, pwd=None):
"EmailId": "{}@mahindra.com".format(usr), "EmailId": "{}@mahindra.com".format(usr),
"isLDAPAuthenticated": ""} "isLDAPAuthenticated": ""}
success_msg = None
user_name = None
msgDic = {} msgDic = {}
if len(decoded) > 165: if len(decoded) > 165:
da = re.search("{", decoded) da = re.search("{", decoded)
@ -157,7 +148,7 @@ def app_user_validation(usr=None, pwd=None):
dicData['ID'] = "100" dicData['ID'] = "100"
return dicData return dicData
else: else:
try: try:
msgDic['UserName'] = dictValue['children']['UserName']['text'] msgDic['UserName'] = dictValue['children']['UserName']['text']
@ -176,25 +167,13 @@ def app_user_validation(usr=None, pwd=None):
return {'status': 0, 'error': 'Site Error'} return {'status': 0, 'error': 'Site Error'}
def xml_to_dict(node): @frappe.whitelist(allow_guest=True)
return {'tag': node.tag, 'text': node.text, 'attrib': node.attrib,
'children': {child.tag: xml_to_dict(child) for child in node}}
@frappe.whitelist()
def grant_user_access(userdata=None, iid=None): def grant_user_access(userdata=None, iid=None):
val = input_validation(userdata=userdata,iid=iid) val = input_validation(userdata=userdata, iid=iid)
if val != '': if val != '':
return {'status': 0, 'error': "Parameter's missing: " + val} return {'status': 0, 'error': "Parameter's missing: " + val}
# if userdata == None and iid == None:
# return {'status': 0, 'error': "Parameter's missing: userdata & iid"}
# if userdata == None:
# return {'status': 0, 'error': "Parameter missing: userdata"}
# if iid == None:
# return {'status': 0, 'error': "Parameter missing: iid"}
try: try:
user_details = {}
userdata = json.loads(userdata) userdata = json.loads(userdata)
user_id = userdata['ID'] user_id = userdata['ID']
email = userdata['EmailId'] email = userdata['EmailId']
@ -203,19 +182,14 @@ def grant_user_access(userdata=None, iid=None):
login_name = userdata['LoginName'] login_name = userdata['LoginName']
user_active_status = userdata['IsActive'] user_active_status = userdata['IsActive']
latitude = userdata['latitude']
longitude = userdata['longitude']
user_type = userdata['UserType']
user_type_desc = userdata['UserTypeDesc'] user_type_desc = userdata['UserTypeDesc']
skill_id = userdata['SkillID'] skill_id = userdata['SkillID']
skill_name = userdata['SkillName'] skill_name = userdata['SkillName']
area_name = userdata['AreaName'] area_name = userdata['AreaName']
zone = userdata['Zone'] zone = userdata['Zone']
dealer_code = userdata['Code'] dealer_code = userdata['Code']
location_name = userdata['LocationName']
dealer_name = userdata['DealerName'] dealer_name = userdata['DealerName']
app_current_version = userdata['AppCurrentVersion'] app_current_version = userdata['AppCurrentVersion']
@ -224,6 +198,30 @@ def grant_user_access(userdata=None, iid=None):
os = userdata['Os'] os = userdata['Os']
os_version = userdata['OsVersion'] os_version = userdata['OsVersion']
latitude = userdata['latitude']
longitude = userdata['longitude']
# User validation
frappe.set_user("Administrator")
user_name = frappe.db.sql('''SELECT name FROM {0}.tabUser where email='{1}';'''.format(current_db_name,email),as_dict=1)
# return user_name
if user_name:
token = generate_keys(user_name[0]['name'])
else:
user = frappe.new_doc('User')
user.email = email
user.first_name = first_name
user.enabled = 1
user.send_welcome_email = 0
role = user.append('roles', {})
role.role = "_AppUser"
user.insert(ignore_permissions=True)
user_name = frappe.db.sql('''SELECT name FROM {0}.tabUser where email='{1}';'''.format(current_db_name,email),as_dict=1)
if user_name:
token = generate_keys(user_name[0]['name'])
# return token
'''Inserting Dealer Data''' '''Inserting Dealer Data'''
if frappe.db.exists({'doctype': 'App Dealer', 'dealer_code': dealer_code}): if frappe.db.exists({'doctype': 'App Dealer', 'dealer_code': dealer_code}):
dealer = frappe.get_doc({'doctype': 'App Dealer', 'dealer_code': dealer_code}) dealer = frappe.get_doc({'doctype': 'App Dealer', 'dealer_code': dealer_code})
@ -270,8 +268,8 @@ def grant_user_access(userdata=None, iid=None):
if frappe.db.exists({'doctype': 'App Device', 'device_id': device_id}): if frappe.db.exists({'doctype': 'App Device', 'device_id': device_id}):
frappe.db.sql( frappe.db.sql(
'''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where device_id = "{0}";'''.format(device_id, '''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where device_id = "{0}";'''.format(device_id,
"Inactive", "Inactive",
current_db_name)) current_db_name))
frappe.db.commit() frappe.db.commit()
time.sleep(1) time.sleep(1)
app_user1 = frappe.get_last_doc('App Users', filters={"email_id": email}) app_user1 = frappe.get_last_doc('App Users', filters={"email_id": email})
@ -340,55 +338,345 @@ def grant_user_access(userdata=None, iid=None):
app_logs.longitude = longitude app_logs.longitude = longitude
app_logs.date_time_stamp = now() app_logs.date_time_stamp = now()
app_logs.save() app_logs.save()
lst = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Device` where device_id = "{}" order by name desc limit 1;'''.format(
current_db_name, device_id), as_list=True)
lst1 = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Users` where email_id = "{}" order by name desc limit 1;'''.format(
current_db_name, email), as_list=True)
''' create user with role system manager ''' user_details = {}
if frappe.db.exists('User', email): user_details['Installation ID'] = lst[0][0]
# user = frappe.get_doc('User', email) user_details['User ID'] = lst1[0][0]
docu = frappe.get_doc("Fish", None) user_details['token'] = token
user_details['token'] = docu.apple return user_details
lst = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Device` where device_id = "{}" order by name desc limit 1;'''.format( except Exception as e1:
current_db_name, device_id), as_list=True) return {'status': 0, 'error': e1}
lst1 = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Users` where email_id = "{}" order by name desc limit 1;'''.format( @frappe.whitelist(allow_guest=True)
current_db_name, email), as_list=True) def new_app_user_validation(usr=None, pwd=None,iid=None,device_data=None):
val = input_validation(usr=usr, pwd=pwd,iid=iid,device_data=device_data)
if val != '':
return {'status': 0, 'error': "Parameter's missing: " + val}
preference = frappe.get_last_doc('App Preference')
mahindra_login = preference.mahindra_login_api
technician_login = preference.technician_login_api
# ISmartAuth API - Email available
device_data = json.loads(device_data)
try:
data = {'LoginID': usr, 'Password': pwd}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
if technician_login == 1 and mahindra_login == 0:
response = requests.post(
"http://www.mahindramile.com/ISmartAuth/Service.asmx/ValidateCredential", data=data, headers=headers)
decoded = response.content.decode('utf-8')
if len(decoded) > 165:
frappe.set_user("Administrator")
da = re.search("{", decoded)
da1 = re.search("}", decoded)
trunData = decoded[da.span()[0]:da1.span()[1]]
dicData = json.loads(trunData)
if dicData['ID'] == "":
dicData['ID'] = "100"
dicData.update(device_data)
return new_grant_user_access(dicData,iid)
else:
return {'status': 0, 'error': 'Invalid Credentials'}
elif technician_login == 0 and mahindra_login == 1:
response1 = requests.post("http://www.mahindramile.com/WindowAuth/Service.asmx/ValidateCredential",
data=data, headers=headers)
decoded1 = response1.content.decode('utf-8')
node = ET.fromstring(decoded1)
dictValue = xml_to_dict(node)
frappe.set_user("Administrator")
dicData = {
"ID": "{}@email.com".format(usr),
"LoginName": usr,
"FirstName": usr,
"LastName": "",
"IsActive": "True",
"UserType": "",
"SkillID": "",
"SkillName": "",
"UserTypeDesc": "",
"PasswordChanged": "",
"AreaName": "",
"Zone": "",
"Code": "",
"LocationName": "",
"ChannelNo": "",
"ServerDate": "",
"ServerTime": "",
"DealerName": "",
"EmailId": "{}@email.com".format(usr),
"isLDAPAuthenticated": ""}
dicData.update(device_data)
msgDic = {}
try: try:
user_details['Installation ID'] = lst[0][0] msgDic['UserName'] = dictValue['children']['UserName']['text']
user_details['User ID'] = lst1[0][0] msgDic['IsSuccessfull'] = dictValue['children']['IsSuccessfull']['text']
return user_details if dicData['ID'] == "":
except Exception as role_error: dicData['ID'] = "100"
return {'status': 0, 'error': role_error} return new_grant_user_access(dicData,iid)
except:
msgDic['IsSuccessfull'] = node.text
return {'status': 0, 'error': 'Invalid Credentials'}
elif technician_login == 1 and mahindra_login == 1:
response = requests.post(
"http://www.mahindramile.com/ISmartAuth/Service.asmx/ValidateCredential", data=data, headers=headers)
decoded = response.content.decode('utf-8')
response1 = requests.post("http://www.mahindramile.com/WindowAuth/Service.asmx/ValidateCredential",
data=data, headers=headers)
decoded1 = response1.content.decode('utf-8')
node = ET.fromstring(decoded1)
dictValue = xml_to_dict(node)
dicData = {
"ID": "",
"LoginName": usr,
"FirstName": usr,
"LastName": "",
"IsActive": "True",
"UserType": "",
"SkillID": "",
"SkillName": "",
"UserTypeDesc": "Mahindra User",
"PasswordChanged": "",
"AreaName": "Mahindra",
"Zone": "Mahindra",
"LocationName": "Mahindra",
"ChannelNo": "",
"ServerDate": "",
"ServerTime": "",
"DealerName": "Mahindra",
"EmailId": "{}@mahindra.com".format(usr),
"isLDAPAuthenticated": ""}
msgDic = {}
if len(decoded) > 165:
frappe.set_user("Administrator")
da = re.search("{", decoded)
da1 = re.search("}", decoded)
trunData = decoded[da.span()[0]:da1.span()[1]]
dicData = json.loads(trunData)
dicData['Code'] = ""
if dicData['ID'] == "":
dicData['ID'] = "100"
dicData.update(device_data)
return new_grant_user_access(dicData,iid)
else:
frappe.set_user("Administrator")
msgDic['UserName'] = dictValue['children']['UserName']['text']
msgDic['IsSuccessfull'] = dictValue['children']['IsSuccessfull']['text']
if dicData['ID'] == "":
dicData['ID'] = "100"
dicData['Code'] = ''
dicData.update(device_data)
return new_grant_user_access(dicData,iid)
else: else:
# user = frappe.new_doc('User') return {'status': 0, 'error': 'Login Blocked'}
# user.email = email except:
# user.first_name = first_name return {'status': 0, 'error': 'Site Error'}
# user.send_welcome_email = 0
# user.user_type = 'Website User'
# user.add_roles('_AppUser') def new_grant_user_access(userdata=None, iid=None):
# user.save() try:
user_id = userdata['ID']
docu = frappe.get_doc("Fish", None) email = userdata['EmailId']
user_details['token'] = docu.apple first_name = userdata['FirstName']
lst = frappe.db.sql( last_name = userdata['LastName']
'''SELECT name FROM {}.`tabApp Device` where device_id = "{}" order by creation asc;'''.format( login_name = userdata['LoginName']
current_db_name, device_id), as_list=True) user_active_status = userdata['IsActive']
lst1 = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Users` where email_id = "{}" order by creation asc;'''.format( user_type_desc = userdata['UserTypeDesc']
current_db_name, email), as_list=True) skill_id = userdata['SkillID']
try: skill_name = userdata['SkillName']
user_details['Installation ID'] = lst[-1][0]
user_details['User ID'] = lst1[-1][0] area_name = userdata['AreaName']
return user_details zone = userdata['Zone']
except Exception as e: dealer_code = userdata['Code']
return {'status': 0, 'error': e}
except Exception as e1: dealer_name = userdata['DealerName']
return {'status': 0, 'error': e1 }
app_current_version = userdata['AppCurrentVersion']
device_id = userdata['DeviceID']
device_type = userdata['DeviceType']
os = userdata['Os']
os_version = userdata['OsVersion']
latitude = userdata['latitude']
longitude = userdata['longitude']
# User validation
frappe.set_user("Administrator")
user_name = frappe.db.sql('''SELECT name FROM {0}.tabUser where email='{1}';'''.format(current_db_name,email),as_dict=1)
if user_name:
token = generate_keys(user_name[0]['name'])
else:
user = frappe.new_doc('User')
user.email = email
user.first_name = first_name
user.enabled = 1
user.send_welcome_email = 0
role = user.append('roles', {})
role.role = "_AppUser"
user.insert(ignore_permissions=True)
user_name = frappe.db.sql('''SELECT name FROM {0}.tabUser where email='{1}';'''.format(current_db_name,email),as_dict=1)
if user_name:
token = generate_keys(user_name[0]['name'])
'''Inserting Dealer Data'''
if frappe.db.exists({'doctype': 'App Dealer', 'dealer_code': dealer_code}):
dealer = frappe.get_doc({'doctype': 'App Dealer', 'dealer_code': dealer_code})
else:
dealer = frappe.new_doc('App Dealer')
dealer.dealer_code = dealer_code
dealer.dealer_name = dealer_name
dealer.zone = zone
dealer.area = area_name
dealer.active_status = user_active_status
dealer.save()
dealer = frappe.get_doc({'doctype': 'App Dealer', 'dealer_code': dealer_code})
'''Inserting User data'''
app_dealer1 = frappe.get_last_doc('App Dealer', filters={"dealer_code": dealer_code})
if frappe.db.exists({'doctype': 'App Users', 'email_id': email}):
app_user = frappe.get_doc({'doctype': 'App Users', 'email_id': email})
else:
app_user = frappe.new_doc('App Users')
app_user.email_id = email
app_user.user_id = user_id
app_user.dealer = app_dealer1.name
app_user.login_name = login_name
app_user.user_type = user_type_desc
app_user.first_name = first_name
app_user.last_name = last_name
app_user.skill_id = skill_id
app_user.skill_name = skill_name
app_user.active_status = user_active_status
app_user.save()
'''Inserting Device data'''
if iid == 'None' or iid == 'null':
app_device = frappe.new_doc('App Device')
app_device.device_id = device_id
app_device.publish_type = "Global"
app_device.device_type = device_type
app_device.os = os
app_device.os_version = os_version
app_device.app_current_version = app_current_version
app_device.last_login = now()
app_device.insert()
if frappe.db.exists({'doctype': 'App Device', 'device_id': device_id}):
frappe.db.sql(
'''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where device_id = "{0}";'''.format(device_id,
"Inactive",
current_db_name))
frappe.db.commit()
time.sleep(1)
app_user1 = frappe.get_last_doc('App Users', filters={"email_id": email})
app_device1 = frappe.get_last_doc('App Device', filters={"device_id": device_id})
app_logs = frappe.new_doc('App Log')
app_logs.user = app_user1.name
app_logs.device = app_device.name
app_logs.type = 'Reinstalled'
app_logs.latitude = latitude
app_logs.longitude = longitude
# app_logs.active_status = 'Active'
app_logs.date_time_stamp = now()
app_logs.insert()
app_device_tmp = frappe.get_last_doc('App Device', filters={"device_id": device_id})
frappe.db.sql('''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where name = "{0}";'''.format(
app_device_tmp.name, "Active", current_db_name))
frappe.db.commit()
app_logs3 = frappe.new_doc('App Log')
app_logs3.user = app_user1.name
app_logs3.device = app_device.name
app_logs3.type = 'Logged in'
app_logs3.latitude = latitude
app_logs3.longitude = longitude
app_logs3.date_time_stamp = now()
app_logs3.insert()
else:
app_user1 = frappe.get_last_doc('App Users', filters={"email_id": email})
app_device1 = frappe.get_last_doc('App Device', filters={"device_id": device_id})
app_logs = frappe.new_doc('App Log')
app_logs.user = app_user1.name
app_logs.device = app_device.name
app_logs.type = 'Installed'
# app_logs.active_status = 'Active'
app_logs.latitude = latitude
app_logs.longitude = longitude
app_logs.date_time_stamp = now()
app_logs.save()
app_logs4 = frappe.new_doc('App Log')
app_logs4.user = app_user1.name
app_logs4.device = app_device.name
app_logs4.type = 'Logged in'
app_logs4.latitude = latitude
app_logs4.longitude = longitude
app_logs4.date_time_stamp = now()
app_logs4.save()
def generate_keys(user): else:
user_details = frappe.get_doc('User', user) # frappe.db.sql(
# '''UPDATE {4}.`tabApp Device` set last_login= '{0}', user_name = '{2}', device_type = '{3}' where name = "{1}";'''.format(
# now(), iid, email, user_type_desc, current_db_name))
frappe.db.sql(
'''UPDATE {3}.`tabApp Device` set last_login= '{0}', device_type = '{2}' where name = "{1}";'''.format(
now(), iid, device_type, current_db_name))
frappe.db.commit()
app_user2 = frappe.get_last_doc('App Users', filters={"email_id": email})
app_logs = frappe.new_doc('App Log')
app_logs.user = app_user2.name
app_logs.device = iid
app_logs.type = 'Logged in'
app_logs.latitude = latitude
app_logs.longitude = longitude
app_logs.date_time_stamp = now()
app_logs.save()
lst = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Device` where device_id = "{}" order by name desc limit 1;'''.format(
current_db_name, device_id), as_list=True)
lst1 = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Users` where email_id = "{}" order by name desc limit 1;'''.format(
current_db_name, email), as_list=True)
user_details = {}
user_details['Installation ID'] = lst[0][0]
user_details['User ID'] = lst1[0][0]
user_details['token'] = token
return user_details
except Exception as e1:
return {'status': 0, 'error': e1}
def generate_keys(user_name):
user_details = frappe.get_doc('User', user_name)
api_secret = frappe.generate_hash(length=15) api_secret = frappe.generate_hash(length=15)
if not user_details.api_key: if not user_details.api_key:
api_key = frappe.generate_hash(length=15) api_key = frappe.generate_hash(length=15)
@ -417,4 +705,9 @@ def input_validation(**kwargs):
sts += ',' sts += ','
sts += str(key) + "" sts += str(key) + ""
i += 1 i += 1
return sts return sts
def xml_to_dict(node):
return {'tag': node.tag, 'text': node.text, 'attrib': node.attrib,
'children': {child.tag: xml_to_dict(child) for child in node}}

Loading…
Cancel
Save