let AUTH_LOGIN_APIS_URL = {
isUser(user) {
return `account/getuserbyphoneormail/${user}/${user}`;
},
login() {
return `bizgaze/crm/webapi/crmuserlogin`
},
signUp() {
return `bizgaze/crm/webapi/registercrmuser`;
},
resendOTP() {
return `bizgaze/crm/webapi/ReSendOtp`;
},
sendOTP() {
return `account/sendotp`;
},
updatePassword() {
return `account/UpdatePassword`;
}
}
initLogin();
function initLogin() {
let userDetails = {
otpid: null,
email: null,
password: null,
unibaseid: null
}
let backotp = null;
let backOptions = {
forgotPassword:'forgotPassword',
EmailnotV:'EmailnotV',
signUp:'signUp'
}
let authloginLoadingBtnAction = {
addLoading() {
$('.authloginLoading').addClass('d-none');
$('.authloginLoadingBtn').removeClass('d-none');
},
removeLoading() {
$('.authloginLoading').removeClass('d-none');
$('.authloginLoadingBtn').addClass('d-none');
}
}
let otpLoadingAction = {
addLoadingOTP() {
$('.otploading').removeClass('d-none');
$('.otploadingtext').addClass('d-none');
},
removeLoadingOTP() {
$('.otploading').addClass('d-none');
$('.otploadingtext').removeClass('d-none');
}
}
let formErrorAction = {
addError(message) {
$('.error_msg').removeClass('d-none');
$('.error_msg_res').html(message);
},
removeClass() {
$('.error_msg').addClass('d-none');
$('.error_msg_res').html('');
}
}
function init() {
const logoauth = $('.logoauth');
logoauth.removeClass('d-none');
loginUI();
//updatePasswordUI();
//OTP_UI()
}
function checkPassword(value){
const specailHelper = containsSpecialCharsHelper(value);
const isUpperCase = isUpperCaseHelper(value);
const isLowerCase = isLowerCaseHelper(value);
const isNumber = isNumberContainsHelper(value);
const len = value.length>=8;
return specailHelper && isUpperCase && isLowerCase && isNumber && len;
}
init();
function updatePasswordUI() {
formErrorAction.removeClass();
let html = `
`;
$('.authContainerUI').html(html);
updatepasswordEvents();
}
function updatepasswordEvents() {
$('.needs-validation').off('submit');
loadPasswordListener();
$('.needs-validation').on('submit', async (event) => {
event.preventDefault();
let ele = document.querySelector('.needs-validation')
if (!ele.checkValidity()) {
ele.classList.add('was-validated')
return;
}
let newPassword = $('#updatepassword').val();
let passwordConfirm = $('#updateconfirmpassword').val();
if (newPassword != passwordConfirm) {
formErrorAction.addError("Password doesn't match");
return;
}
if(!checkPassword(newPassword)){
formErrorAction.addError("Password doesn't match");
return;
}
const forgotpassPayload = {
username: userDetails.unibaseid,
password: passwordConfirm,
};
const res = await postAPIService(AUTH_LOGIN_APIS_URL.updatePassword(), forgotpassPayload);
console.log(res);
if (res.data.message == 'Password Updated Successfully') {
loginUI();
toasterHelper("success", "Password updated successfull");
}
});
}
function loadPasswordListener(){
$('.passwordvalidui').off().on('keyup',function (e){
$(this).parent().find('.pswd_info').css('display','block');
let value = $(this).val();
const specailHelper = containsSpecialCharsHelper(value);
const isUpperCase = isUpperCaseHelper(value);
const isLowerCase = isLowerCaseHelper(value);
const isNumber = isNumberContainsHelper(value);
if(isLowerCase){
$(this).parent().find('#chck_small').addClass('text-decoration-line-through');
}else{
$(this).parent().find('#chck_small').removeClass('text-decoration-line-through');
}
if(specailHelper){
$(this).parent().find('#chck_special').addClass('text-decoration-line-through');
}else{
$(this).parent().find('#chck_special').removeClass('text-decoration-line-through');
}
if(isUpperCase){
$(this).parent().find('#chck_capital').addClass('text-decoration-line-through');
}else{
$(this).parent().find('#chck_capital').removeClass('text-decoration-line-through');
}
if(value.length>=8){
$(this).parent().find('#chck_length').addClass('text-decoration-line-through');
}else{
$(this).parent().find('#chck_length').removeClass('text-decoration-line-through');
}
if(isNumber){
$(this).parent().find('#chck_number').addClass('text-decoration-line-through');
}else{
$(this).parent().find('#chck_number').removeClass('text-decoration-line-through');
}
}).blur(function (e){
$(this).parent().find('.pswd_info').css('display','none');
})
$('.eyePassword').off();
$('.eyePassword').click(function (e){
e.stopPropagation();
let eyeOpen = '';
let eyeClose = '';
console.log(this);
let isClose = $(this).find(`.fa-eye-slash`).length;
if(isClose){
$(this).html(eyeOpen);
$(this).parent().find('.passwordvalidui').attr('type','text');
}else{
$(this).html(eyeClose);
$(this).parent().find('.passwordvalidui').attr('type','password');
}
});
}
async function resendOTP() {
otpLoadingAction.addLoadingOTP();
let payload = {
"FirstName": "",
"LastName": "",
"ContactNumber": "",
"Email": "",
"TenantName": "",
"ContactOrEmail": userDetails.email,
"IsSignup": false,
"IsRegisterUser": true,
"IsForgotPswd": false,
"UnibaseId": userDetails.unibaseid,
"OtpId": parseInt(userDetails.otpid),
"UserOtp": ""
}
let res = await postAPIService(AUTH_LOGIN_APIS_URL.resendOTP(), payload);
res = res.data;
if (res.code != '0' || res.message != 'OTP resent successfully') {
return;
}
userDetails = { ...userDetails, otpid: res.result };
otpLoadingAction.removeLoadingOTP();
}
function loadForpasswordsEvents() {
$('.needs-validation').off('submit');
$('.needs-validation').on('submit', async (event) => {
event.preventDefault()
let ele = document.querySelector('.needs-validation')
if (!ele.checkValidity()) {
ele.classList.add('was-validated')
return;
}
debugger;
const email = $('#forgotpassword').val();
await sendOTPService(email,1,backOptions.forgotPassword);
authloginLoadingBtnAction.removeLoading();
});
$('.btnForgotback').click(function (e) {
loginUI();
})
}
function forgotPasswordUIEmail() {
formErrorAction.removeClass();
let html = ` Forgot Password?
Enter the email associated with your account and we'll send an email with instructions to reset your password.
`;
$('.authContainerUI').html(html);
loadForpasswordsEvents();
}
function loginEvents() {
// submit event
$('.needs-validation').off('submit');
$('.needs-validation').on('submit', async (event) => {
event.preventDefault();
let ele = document.querySelector('.needs-validation')
if (!ele.checkValidity()) {
ele.classList.add('was-validated')
return;
}
debugger;
const email = $('#User_Email').val();
const isUserURL = AUTH_LOGIN_APIS_URL.isUser(email);
authloginLoadingBtnAction.addLoading();
const user = await getAPIService(isUserURL);
const isUser = user.data.result === null && user.data.message === `Email/Phonenumber doesn't exist`;
if (!isUser) {
loginUser();
} else {
debugger;
signUpUser();
}
});
// forgot password
$('.forgotpasswordBtn').click(function (e) {
forgotPasswordUIEmail();
});
loadPasswordListener();
}
async function loginUserService(email, passord) {
const loginPayload = {
username: email,
Password: passord,
UnibaseId: "",
RememberMe: false,
};
let res = await postAPIService(AUTH_LOGIN_APIS_URL.login(),
loginPayload
);
return res;
}
async function loginUser() {
formErrorAction.removeClass();
let userEmail = $("#User_Email").val();
let userPassword = $("#User_password").val();
let res = await loginUserService(userEmail, userPassword);
res = res.data;
let isError = res.code != '0';
userDetails['email'] = userEmail;
userDetails['password'] = userPassword;
debugger;
if (isError) {
if (res.message === 'Email is not verified') {
formErrorAction.addError(`${res.message} Valid here`);
$('.validemail').off('click')
$('.validemail').click(async function (e) {
await sendOTPService(userEmail,2,backOptions.EmailnotV);
formErrorAction.removeClass();
authloginLoadingBtnAction.removeLoading();
});
authloginLoadingBtnAction.removeLoading();
return;
}
formErrorAction.addError(`${res.message}`);
authloginLoadingBtnAction.removeLoading();
return;
}
let authObj = {
token: res.result.sessionId,
userId: res.result.userId,
unibaseId:res.result.unibaseId,
sessionId:res.result.sessionId,
tenantId:res.result.tenantId,
name:res.result.name,
assetUrl:res.result.assetUrl
};
COOKIE_HELPER_ACTIONS.setCookie(authObj);
localStorage.setItem("userdata",JSON.stringify(res.result));
const isCartAdded = localStorage.getItem(CART_ADD);
if(isCartAdded){
localStorage.removeItem(CART_ADD);
window.location.href = `/selectdelivery.html`;
return;
}
localStorage.setItem(USER_AUTH_OKAY,2);
window.location.href = '/';
//authloginLoadingBtnAction.removeLoading();
console.log(res);
}
async function sendOTPService(userEmail,num=0,option) {
const isUserURL = AUTH_LOGIN_APIS_URL.isUser(userEmail);
authloginLoadingBtnAction.addLoading();
const user = await getAPIService(isUserURL);
const isUser = user.data.result === null || user.data.message === `Email/Phonenumber doesn't exist`;
if (isUser) {
formErrorAction.addError(user.data.message);
authloginLoadingBtnAction.removeLoading();
return;
}
const forgotpassPayload = {
firstname: "",
lastname: "",
contactnumber: "",
email: "",
tenantname: "",
contactoremail: user.data.result.email,
IsSignup: false,
IsRegisterUser: false,
IsForgotPswd: true,
UnibaseId: user.data.result.userName,
OtpId: 0,
UserOtp: "",
};
const forgetpassRes = await postAPIService(
AUTH_LOGIN_APIS_URL.sendOTP(),
forgotpassPayload
);
userDetails.email = userEmail;
userDetails.otpid = forgetpassRes.data;
userDetails.unibaseid = user.data.result.userName;
console.log(forgetpassRes, userDetails);
backotp = option
OTP_UI(num);
}
async function signUpUser() {
formErrorAction.removeClass();
let userEmail = $("#User_Email").val();
let userPassword = $("#User_password").val();
let checkPasswordValue = checkPassword(userPassword);
if(!checkPasswordValue){
authloginLoadingBtnAction.removeLoading();
formErrorAction.addError('Password must contain one specail letter ,number,small letter, uppercase letter and 8 letters');
return;
}
const userRegistratioNPayload = {
organizationtypeid: "2",
organizationid: "0",
contactid: "0",
userid: "0",
username: "0",
users_phonenumber: "0",
password: userPassword,
users_emailaddress: "0",
emailaddress: userEmail,
contactname: userEmail.split('@')[0],
phonenumber: "0",
branchid: "0",
tenantname: "Anwi Systems",
rolename: "Customer Admin",
currencyid: "0",
customerformuniqueid: "Bizgaze_Platform_Crm_RegisterCRMUser",
};
let res = await postAPIService(
AUTH_LOGIN_APIS_URL.signUp(),
userRegistratioNPayload
);
console.log(res);
res = res.data;
if (res.code != '0') {
formErrorAction.addError(res.message);
authloginLoadingBtnAction.removeLoading();
return;
}
res = res.result;
userDetails['otpid'] = res.OtpId;
userDetails['email'] = userEmail;
userDetails['password'] = userPassword;
userDetails['unibaseid'] = res.UnibaseId;
backotp = backOptions.signUp
OTP_UI();
}
function loginUI() {
formErrorAction.removeClass();
let html = `
Login / Signup
Forgot password?
`;
$('.authContainerUI').html(html);
loginEvents();
}
function OTP_UI(forgot = 0) {
formErrorAction.removeClass();
let html = `
`;
$('.authContainerUI').html(html);
loadOTPEvents(forgot);
}
async function validOTP(email, id, otp) {
const validateForgotpass = {
email: email,
otpid: id,
userotp: otp,
};
const res = await postAPIService(
`hyperfusion/validateotp`,
validateForgotpass
);
return res;
}
function loadOTPEvents(forgot) {
$('.resendOTP').click(function (e) {
resendOTP();
})
$('.btnForgotback').off().click(function(e){
debugger;
if(backotp === backOptions.forgotPassword){
forgotPasswordUIEmail();
}else if(backotp === backOptions.EmailnotV){
loginUI();
}else if(backotp === backOptions.signUp){
loginUI();
}
});
$("#email_validate_proceed").click(async function () {
debugger;
otpLoadingAction.addLoadingOTP();
let userotp = '';
$(".otp-validation .otp-input-group input").each(function () {
let presVal = $(this).val();
userotp += presVal;
});
debugger;
if (userotp.length == 6) {
// const validateForgotpass = {
// email: userDetails.email,
// otpid: userDetails.otpid,
// userotp: userotp,
// };
$('#email_validate_proceed').hide()
$(".loader-btn").show();
const validate_email_resopt = await validOTP(userDetails.email, userDetails.otpid, userotp);
$(".loader-btn").hide();
$('#email_validate_proceed').show()
const Resotp = validate_email_resopt.data.result;
if (Resotp == "Otp verified successfully") {
if (forgot == 1) {
updatePasswordUI();
return;
} else if (forgot == 2) {
loginUI();
toasterHelper("success", "Email has been verified");
return;
}
let res = await loginUserService(userDetails.email, userDetails.password);
res = res.data;
let authObj = {
token: res.result.sessionId,
userId: res.result.userId,
unibaseId:res.result.unibaseId,
sessionId:res.result.sessionId,
tenantId:res.result.tenantId,
name:res.result.name,
assetUrl:res.result.assetUrl
};
COOKIE_HELPER_ACTIONS.setCookie(authObj);
localStorage.setItem("userdata",JSON.stringify(res.result));
const isCartAdded = localStorage.getItem(CART_ADD);
if(isCartAdded){
localStorage.removeItem(CART_ADD);
window.location.href = `/selectdelivery.html`;
return;
}
localStorage.setItem(USER_AUTH_OKAY,1);
window.location.href = '/';
otpLoadingAction.removeLoadingOTP();
} else {
// toasterOpts()
// Command: toastr["error"]("Please enter Valid OTP");
otpLoadingAction.removeLoadingOTP();
formErrorAction.addError("Please enter Valid OTP")
}
}
else {
otpLoadingAction.removeLoadingOTP();
formErrorAction.addError("Please enter Valid OTP")
}
});
$(".otp-validation .otp-input-group").on("paste", function (p) {
let data = p.originalEvent.clipboardData.getData("text");
let dataLength = data.length;
for (let i = 0; i < dataLength; i++) {
let input = $(
'.otp-validation .otp-input-group input[tabindex="' + (i + 1) + '"]'
);
input.val(data.charAt(i));
if (input.val().length >= input.attr("maxlength")) {
let nextInput = $(
'.otp-validation .otp-input-group input[tabindex="' +
(i + 2) +
'"]'
);
if (nextInput) {
nextInput.focus();
}
}
}
p.preventDefault();
});
$('.otp-validation .otp-input-group input[type="text"]').on(
"keyup",
function (e) {
if ($(this).val().length >= $(this).attr("maxlength")) {
if (e.keyCode !== 9 && e.keyCode !== 16) {
let tabIndex = parseInt($(this).attr("tabindex")) + 1;
$(
'.otp-validation .otp-input-group input[tabindex="' +
$(this).attr("tabindex") +
'"]'
).val($(this).val());
$(
'.otp-validation .otp-input-group input[tabindex="' +
tabIndex +
'"]'
).focus();
}
} else {
if (e.keyCode === 8) {
let tabIndex = parseInt($(this).attr("tabindex")) - 1;
$(
'.otp-validation .otp-input-group input[tabindex="' +
tabIndex +
'"]'
).focus();
}
}
}
);
}
}