Beispiel #1
0
    public static object login(string text1, string text2)
    {
        // create filter paramters
        string _pass = EncryptDecryptString.Encrypt(text2, "Taj$$Key");

        string[,] _params = { { "Username", text1 }, { "Password", _pass } };
        // get all of data.
        var _ds = new Select().SelectLists("Clients_Login", _params);
        var dt  = _ds.Tables[0];

        object result = new { Status = false, Name = "" };

        if (dt.Rows.Count > 0)
        {
            SessionManager.Current.ID   = string.Format("{0}", dt.Rows[0][0]);
            SessionManager.Current.Name = string.Format("{0}", dt.Rows[0][1]);
            CookiesManager.SaveCoockie();

            result = new
            {
                Status = true,
                Name   = SessionManager.Current.Name
            };
        }
        return(result);
    }
Beispiel #2
0
    private void ShowUserInformation(int Id)
    {
        var result = new UsersManager().GetUsers(Id);

        if (result != null)
        {
            Email.Text          = result.Email;
            UserFullName.Text   = result.UserFullName;
            Phone.Text          = result.Phone;
            Mobile.Text         = result.Mobile;
            Nationality.Text    = result.Nationality;
            Username.Text       = result.Username;
            EmpID.Text          = result.EmpID;
            JobID.SelectedValue = string.Format("{0}", result.JobID);
            JoinDate.Text       = string.Format("{0:dd/MM/yyyy}", result.JoinDate);
            IsActive.Checked    = (bool)result.IsActive;
            Password.Text       = EncryptDecryptString.Decrypt(result.Password, "Taj$$Key");

            if (!string.IsNullOrEmpty(result.Sig))
            {
                sig.InnerHtml = result.Sig;
                clear.Visible = SaveSignature.Visible = false;
            }
        }
    }
        public int LogIn(LogInParams _LogInViewModel)
        {
            try
            {
                UserService _userService = new UserService();
                string      _pass        = EncryptDecryptString.Encrypt(_LogInViewModel.Password, "Taj$$Key");
                var         _paramters   = new LogInParams()
                {
                    Username = _LogInViewModel.Username,
                    Password = _pass
                };

                List <UserViewModel> User_List = new List <UserViewModel>();
                User_List = _userService.Find(_paramters);
                if (User_List.Count <= 0)
                {
                    return(-1);
                }

                SessionHandler.Instance.Set(User_List, SessionEnum.User_Info); // Save User Session.
                return(1);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #4
0
    public static bool SelectSetting(string value)
    {
        bool good = false;

        SqlCommand command = DataAccess.CreateCommandText();

        try
        {
            string _pass = EncryptDecryptString.Encrypt(value, "Taj$$Key");
            command.CommandText = string.Format("select TOP 1 Password from SystemSettings where Password='******'", _pass);
            command.Connection.Open();
            var            dt  = new DataTable();
            SqlDataAdapter adp = new SqlDataAdapter(command);
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0][0] != DBNull.Value)
                {
                    good = true;
                }
            }
        } //catch { }
        finally { command.Connection.Close(); }

        return(good);
    }
Beispiel #5
0
        public HttpResponseMessage LogIn(LogInParams _LogInViewModel)
        {
            try
            {
                UserService _userService = new UserService();
                string      _pass        = EncryptDecryptString.Encrypt(_LogInViewModel.Password, "Taj$$Key");
                var         _paramters   = new LogInParams()
                {
                    Username = _LogInViewModel.Username,
                    Password = _pass
                };

                List <UserViewModel> User_List = new List <UserViewModel>();
                User_List = _userService.Find(_paramters);
                if (User_List.Count > 0)
                {
                    return(Request.CreateResponse(HttpStatusCode.Accepted, User_List));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, "Invalid username or password"));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
Beispiel #6
0
    public static bool login(string text1, string text2)
    {
        bool login_state = false;

        string _pass = EncryptDecryptString.Encrypt(text2, "Taj$$Key");

        // create filter paramters
        string[,] _params = { { "UserName", text1 }, { "Password", _pass } };

        // get all of data.
        var _ds = new Select().SelectLists("Users_Login", _params);

        var dt = _ds.Tables[0];

        if (dt.Rows.Count > 0)
        {
            SessionManager.Current.ID   = string.Format("{0}", dt.Rows[0][0]);
            SessionManager.Current.Name = string.Format("{0}", dt.Rows[0][1]);
            //SessionManager.Current.Level = string.Format("{0}", dt.Rows[0][2]);

            CookiesManager.SaveCoockie();

            login_state = true;
        }

        return(login_state);
    }
Beispiel #7
0
        public string CheckPassword(string username, string password)
        {
            ResultHelper _resultHelper = new ResultHelper();

            password = EncryptDecryptString.Encrypt(password);
            using (var db = new nasccoEntities())
            {
                try
                {
                    var data = db.users.FirstOrDefault(x => x.username == username &&
                                                       (x.statuses_id == 1 || x.statuses_id == 3 || x.statuses_id == 7));
                    if (data != null)
                    {
                        if (data.password == password)
                        {
                            return(_resultHelper.Success());
                        }
                        else
                        {
                            return("failed");
                        }
                    }
                }
                catch (Exception ex)
                {
                    string err = ex.Message;
                }
            }

            return("failed");
        }
Beispiel #8
0
        public HttpResponseMessage LogIn(LogInParams _LogInViewModel)
        {
            try
            {
                UserService _userService = new UserService();
                string      _pass        = EncryptDecryptString.Encrypt(_LogInViewModel.Password, "Taj$$Key");
                var         _paramters   = new LogInParams()
                {
                    Username = _LogInViewModel.Username,
                    Password = _pass
                };

                List <UserViewModel> User_List = new List <UserViewModel>();
                User_List = _userService.Find(_paramters);
                if (User_List.Count <= 0)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, -1));
                }

                SessionHandler.Instance.Set(User_List, SessionEnum.User_Info); // Save User Session.
                return(Request.CreateResponse(HttpStatusCode.OK, User_List));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
Beispiel #9
0
    void LoginUSers(string _userName, string _pass)
    {
        _pass = EncryptDecryptString.Encrypt(_pass, "Taj$$Key");

        string[,] _params = { { "Username", _userName }, { "Password", _pass } };
        var user = new UsersManager().UserLogin(_userName, _pass);

        if (user != null)
        {
            var _user = new LoginModel
            {
                ID              = string.Format("{0}", user.UserID),
                Name            = string.Format("{0}", user.UserFullName),
                PermID          = string.Format("{0}", user.PermID), // jordan users permission
                MasterAccountID = "",
            };

            IdentityHelper.SignIn(_user);
            IdentityHelper.RedirectToReturnUrl("/jordan/home", Response);
        }
        else
        {
            lblError.Text = Resources.AdminResources_ar.ErrorLogin;
            lblWarning.Attributes.Add("class", "alert alert-warning");
        }
    }
Beispiel #10
0
        public int SaveRow(string procedureName, string[] paramters, string[] paramtersVal)
        {
            var parameters = new SqlParameter[paramtersVal.Length];

            // build stored procedure paramters.
            for (int i = 0; i < paramtersVal.Length; i++)
            {
                if (string.IsNullOrEmpty(paramtersVal[i]))
                {
                    parameters[i] = new SqlParameter("@" + paramters[i], DBNull.Value);
                }
                else if (paramters[i].ToLower().Contains("password"))
                {
                    parameters[i] = new SqlParameter("@" + paramters[i], EncryptDecryptString.Encrypt(paramtersVal[i], "Taj$$Key"));
                }
                else if (paramtersVal[i].Length >= 50)
                {
                    parameters[i]       = new SqlParameter("@" + paramters[i], System.Data.SqlDbType.NVarChar, paramtersVal[i].Length * 2);
                    parameters[i].Value = paramtersVal[i];
                }
                else
                {
                    parameters[i] = new SqlParameter("@" + paramters[i], paramtersVal[i]);
                }
            }

            // start save to db.
            int RowsAffected = 0;
            int Result       = new DbObject().RunProcedure(procedureName, parameters, out RowsAffected);

            return(Result);
        }
Beispiel #11
0
        public string RecoverPassoerd(string Email)
        {
            try
            {
                // check Email in our database or not.
                UserService _userService = new UserService();
                var         _paramters   = new LogInParams()
                {
                    Email = Email
                };

                List <UserViewModel> User_List = new List <UserViewModel>();
                User_List = _userService.Find(_paramters);
                if (User_List.Count <= 0)
                {
                    return("This email does not exsit in our database");
                }

                //---------------------------------------------------------------

                System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
                client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                client.EnableSsl      = true;
                client.Host           = "smtp.gmail.com";
                client.Port           = 587;

                string AppEmail = EncryptDecryptString.Decrypt(ConfigurationManager.AppSettings["Email"], "Taj$$Key");
                string AppPass  = EncryptDecryptString.Decrypt(ConfigurationManager.AppSettings["EmailAuth"], "Taj$$Key");

                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(AppEmail, AppPass);
                client.UseDefaultCredentials = false;
                client.Credentials           = credentials;

                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                msg.From = new MailAddress(AppEmail);
                msg.To.Add(new MailAddress(Email));

                msg.Subject = "Maskan Rest Password";

                msg.IsBodyHtml = true;
                string _pass = EncryptDecryptString.Encrypt(Email, "Taj$$Key");

                string CurrentUrl = "http://" + Request.Url.DnsSafeHost + ":" + Request.Url.Port + "/ResetPassword/restpass/" + _pass;
                // Email Body.
                string body = "Dear User <br />";
                body += "Please fllow this link to recover your passord </br>";
                body += "<a href =" + CurrentUrl + "> Maskan rest your Password </ a >  <br />";

                msg.Body       = body;
                msg.IsBodyHtml = true;

                client.Send(msg);

                return("Success");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Beispiel #12
0
        public string Save(UserModel model)
        {
            ResultHelper _resultHelper = new ResultHelper();

            using (var db = new nasccoEntities())
            {
                using (DbContextTransaction dbTran = db.Database.BeginTransaction())
                {
                    try
                    {
                        var data = db.users.Create();
                        data.member_id          = model.UserMemberId;
                        data.roles_id           = model.RolesId;
                        data.statuses_id        = model.UserStatusesId;
                        data.username           = model.Username;
                        data.password           = EncryptDecryptString.Encrypt(model.Password);
                        data.date_created       = DateTime.Now;
                        data.created_by_user_id = model.CreatedByUserId;
                        db.users.Add(data);
                        db.SaveChanges();

                        //Save if no issues
                        dbTran.Commit();
                        return(_resultHelper.Success());
                    }
                    catch (Exception ex)
                    {
                        dbTran.Rollback();
                        return(ex.Message);
                    }
                }
            }
        }
Beispiel #13
0
        public string ChangePassword(UserModel model)
        {
            ResultHelper _resultHelper = new ResultHelper();

            using (var db = new nasccoEntities())
            {
                using (DbContextTransaction dbTran = db.Database.BeginTransaction())
                {
                    try
                    {
                        var data = db.users.FirstOrDefault(x => x.id == model.UserId);
                        data.password = EncryptDecryptString.Encrypt(model.Password);
                        db.SaveChanges();

                        //Save if no issues
                        dbTran.Commit();
                        return(_resultHelper.Success());
                    }
                    catch (Exception ex)
                    {
                        dbTran.Rollback();
                        return(ex.Message);
                    }
                }
            }
        }
Beispiel #14
0
        public ActionResult RestPass(RecoverPass_VM recoverPass_VM)
        {
            if (recoverPass_VM.NewPassword == "" || recoverPass_VM.NewPassword == null)
            {
                return(View("Index"));
            }

            if (recoverPass_VM.NewPassword != recoverPass_VM.ConfirmedPassword)
            {
                ViewBag.ErrorMessage = "Please make shure Passowrds are matched";
                return(View("Index"));
            }
            else
            {
                // Update User Row With new password.
                string Email = EncryptDecryptString.Decrypt(Request.Url.Segments.Last(), "Taj$$Key");
                ResetPasswordService ResetService = new ResetPasswordService();
                var Model = new RegisterViewModel {
                    Email = Email, Password = EncryptDecryptString.Encrypt(recoverPass_VM.NewPassword, "Taj$$Key")
                };
                Model.IsActive = null; Model.Mobile = null; Model.Phone = null; Model.UserID = null; Model.Username = null;
                int Result = ResetService.Update(Model);
                if (Result < 0)
                {
                    ViewBag.ErrorMessage = _GlobalizationManager.GetTranslatedText("There is an Error while recovering your password", Enum_LangModule.MaskanWeb, "84");
                    return(View("Index"));
                }
                else
                {
                    ViewBag.ErrorMessage = _GlobalizationManager.GetTranslatedText("Your password successfully recovered, Please login with your new password.", Enum_LangModule.MaskanWeb, "83");
                    return(View("Index"));
                }
            }
        }
Beispiel #15
0
    public static void UserLogin(HttpCookie _userInfo)
    {
        string cookieIDVal       = EncryptDecryptString.Decrypt(_userInfo[Config.cookieID], Config.encrypptKey),
               cookieUsernameVal = HttpContext.Current.Server.UrlDecode(EncryptDecryptString.Decrypt(_userInfo[Config.cookieUsername], Config.encrypptKey)),
               cookieLevelVal    = EncryptDecryptString.Decrypt(_userInfo[Config.cookieLevel], Config.encrypptKey);

        SessionManager.Current.ID    = cookieIDVal;
        SessionManager.Current.Name  = cookieUsernameVal;
        SessionManager.Current.Level = cookieLevelVal;
    }
Beispiel #16
0
 protected void bntLogin_Click(object sender, EventArgs e)
 {
     if (txtUsername.Text.Trim() != String.Empty && txtPassword.Text.Trim() != String.Empty)
     {
         string _pass = EncryptDecryptString.Encrypt(txtPassword.Text.Trim(), "Taj$$Key");
         LoginUSers(txtUsername.Text, _pass);
     }
     else
     {
         lblError.Text = Resources.AdminResources_ar.DataRequired;
     }
 }
Beispiel #17
0
        public ActionResult SaveProfile(UserViewModel model, HttpPostedFileBase file)
        {
            if (String.IsNullOrEmpty(model.UserFullName) || String.IsNullOrEmpty(model.Password) || string.IsNullOrEmpty(model.Email))
            {
                ViewBag.SuccessMsg = "Please, fill all required fileds";
                return(View("Index"));
            }
            UserViewModel user = (UserViewModel)Session[SessionEnum.User_Info.ToString()]; // User session.

            if (file != null)
            {
                if (file != null && file.ContentLength > 0)
                {
                    SaveImageOnserver.SaveImg(file, "~/Images/Profile/", 200, 200, Convert.ToInt32(user.UserID));
                }
            }

            // update DB.

            UserService   service   = new UserService();
            UserViewModel Usermodel = new UserViewModel()
            {
                UserID       = user.UserID,
                UserFullName = model.UserFullName,
                Password     = EncryptDecryptString.Encrypt(model.Password, "Taj$$Key"),
                Address      = model.Address,
                Phone        = user.Phone,
                Username     = user.Username,
                Country      = user.Country,
                Email        = model.Email,
                Mobile       = user.Mobile,
                Nationality  = user.Nationality
            };

            if (file != null)
            {
                Usermodel.Image = Path.GetExtension(file.FileName);
            }
            else
            {
                Usermodel.Image = user.Image;
            }

            int ResultDB = service.Update(Usermodel);

            // Update user sesstion.
            Session[SessionEnum.User_Info.ToString()] = Usermodel;

            ViewBag.SuccessMsg = "Your data saved successfully";
            return(View("Index"));
        }
Beispiel #18
0
        public int Register(UserViewModel model)
        {
            try
            {
                UserService _userService = new UserService();
                string      _pass        = string.Empty;
                if (!String.IsNullOrEmpty(model.Password))
                {
                    _pass = EncryptDecryptString.Encrypt(model.Password, "Taj$$Key");
                }

                var _paramters = new UserViewModel()
                {
                    Username     = model.Username,
                    UserFullName = model.Username,
                    Password     = _pass,
                    Email        = model.Email,
                    Phone        = model.Phone,
                    Address      = model.Address,
                    Country      = model.Country,
                    AouthType    = model.AouthType,
                    Image        = model.Image
                };
                _paramters.UserID    = null;
                _paramters.IsActive  = null;
                _paramters.IsDeleted = null;

                int Result = _userService.Insert(_paramters);

                if (Result == -1 && model.AouthType == "facebook")
                {
                    Result = 1;
                }

                // set Current session.
                Session[SessionEnum.User_Info.ToString()] = new UserViewModel();
                Session[SessionEnum.User_Info.ToString()] = _paramters;

                return(Result);
            }
            catch (Exception ex)
            {
                return(-1);
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            ApplicationUser user = new ApplicationUser();

            UserService _userService = new UserService();
            string      _pass        = EncryptDecryptString.Encrypt(context.Password, "Taj$$Key");
            var         _paramters   = new LogInParams()
            {
                Username = context.UserName,
                Password = _pass
            };

            List <UserViewModel> User_List = new List <UserViewModel>();

            User_List = _userService.Find(_paramters);

            if (User_List.Count <= 0)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            user.UserName = User_List[0].UserFullName;
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Beispiel #20
0
        public HttpResponseMessage Register(UserViewModel model)
        {
            try
            {
                UserService _userService = new UserService();
                string      _pass        = EncryptDecryptString.Decrypt(model.Password, "Taj$$Key");
                var         _paramters   = new UserViewModel()
                {
                    Username     = model.Username,
                    UserFullName = model.Username,
                    Password     = _pass,
                    Email        = model.Email,
                    Phone        = model.Phone,
                    Address      = model.Address,
                    Country      = model.Country
                };
                _paramters.UserID    = null;
                _paramters.IsActive  = null;
                _paramters.IsDeleted = null;

                int Result = _userService.Insert(_paramters);

                if (Result == -1)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, Result)); //User with this Email or Username Already Exists
                }
                if (Result <= 1)
                {
                    SessionHandler.Instance.Set(_paramters, SessionEnum.User_Info); // Save User Session.
                    return(Request.CreateResponse(HttpStatusCode.OK, Result));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.InternalServerError));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
Beispiel #21
0
    public static void SaveCoockie()
    {
        string cookieIDVal       = EncryptDecryptString.Encrypt(SessionManager.Current.ID, Config.encrypptKey),
               cookieUsernameVal = EncryptDecryptString.Encrypt(HttpContext.Current.Server.UrlEncode(SessionManager.Current.Name), Config.encrypptKey),
               cookieLevelVal    = EncryptDecryptString.Encrypt(SessionManager.Current.Level, Config.encrypptKey);

        //Creting a Cookie Object
        HttpCookie _userInfoCookies = new HttpCookie(Config._cookName, Config._encrypted_ticket);

        //Setting values inside it
        _userInfoCookies[Config.cookieID]       = cookieIDVal;
        _userInfoCookies[Config.cookieUsername] = cookieUsernameVal;
        _userInfoCookies[Config.cookieLevel]    = cookieLevelVal;;

        //Adding Expire Time of cookies
        _userInfoCookies.Expires = DateTime.Now.AddDays(1);
        //_userInfoCookies.Path = "/sys";

        //Adding cookies to current web response
        HttpContext.Current.Response.Cookies.Add(_userInfoCookies);
    }
Beispiel #22
0
        public IActionResult SaveZipFiles(IEnumerable <ZipFileViewModel> model)
        {
            try {
                var fileList = new List <ZipFileViewModel>();
                var key      = configuration.GetSection("AppSettings").GetSection("EncKey").Value;

                foreach (var item in model)
                {
                    fileList.Add(new ZipFileViewModel {
                        Name     = EncryptDecryptString.Encrypt(item.Name, key),
                        IsFolder = item.IsFolder
                    });
                }
                var fileListJson = JsonConvert.SerializeObject(fileList);
                var response     = ApiJsonRequest("/api/values/savezipfiles", fileListJson);

                return(RedirectToAction("Save"));
            }
            catch (Exception) {
                return(RedirectToAction("Error"));
            }
        }
        public IActionResult SaveZipFiles(IEnumerable <ZipFileViewModel> model)
        {
            var repo     = new ZipFileRepo();
            var fileList = new List <ZipFileDetailDto>();
            var key      = configuration.GetSection("AppSettings").GetSection("EncKey").Value;

            foreach (var item in model)
            {
                fileList.Add(new ZipFileDetailDto {
                    FileName    = EncryptDecryptString.Decrypt(item.Name, key),
                    IsDerectory = item.IsFolder
                });
            }

            var fileHeader = new ZipFileHeaderDto()
            {
                FileName       = fileList[0].FileName,
                ZipFileDetails = fileList
            };

            repo.SaveFile(fileHeader);
            return(Ok());
        }
Beispiel #24
0
        public ActiveUserDataModel CheckRecord(string username, string password)
        {
            password = EncryptDecryptString.Encrypt(password);
            using (var db = new nasccoEntities())
            {
                try
                {
                    var data = db.users.FirstOrDefault(x => x.username == username &&
                                                       (x.statuses_id == 1 || x.statuses_id == 3 || x.statuses_id == 7));
                    if (data != null)
                    {
                        if (data.password == password)
                        {
                            return(new ActiveUserDataModel
                            {
                                UserId = data.id,
                                FullName = data.member.firstname + " " + data.member.lastname,
                                RoleId = data.roles_id,
                                RoleName = data.role.description,
                                UserName = data.username
                            });
                        }
                        else
                        {
                            return(null);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string err = ex.Message;
                }
            }

            return(null);
        }
Beispiel #25
0
    public static string decryptPassword(string value)
    {
        string _pass = EncryptDecryptString.Decrypt(value, "Taj$$Key");

        return(_pass);
    }
Beispiel #26
0
        public IHttpActionResult SendLoginOtp(Login model)
        {
            Otp otpModel = new Otp();

            otpModel.MobileOtp = sendOtp.GenerateOtp();
            try
            {
                string otpQuery = string.Empty;
                if (model.DocType != "individual")
                {
                    otpQuery = @"SELECT meta().id as Id,email,mobNum,emirateId From " + _bucket.Name + " as APTCCRM where meta().id like 'login_%' and email='" + model.Email + "' and `password`='" + EncryptDecryptString.EncodePasswordToBase64(model.Password) + "' and docType='user'";
                }
                else
                {
                    otpQuery = @"SELECT meta().id as Id,email,mobNum,emirateId From " + _bucket.Name + " as APTCCRM where meta().id like 'login_%' and email='" + model.Email + "' and `password`='" + EncryptDecryptString.EncodePasswordToBase64(model.Password) + "' and docType='individual'";
                }

                var userDocument = _bucket.Query <object>(otpQuery).ToList();
                if (userDocument.Count > 0)
                {
                    string mobileNo  = "";
                    string emirateId = "";
                    foreach (var item in userDocument)
                    {
                        mobileNo       = ((Newtonsoft.Json.Linq.JToken)item).Root["mobNum"].ToString();
                        otpModel.Email = ((Newtonsoft.Json.Linq.JToken)item).Root["email"].ToString();
                        if (((Newtonsoft.Json.Linq.JToken)item).Root["mobNum"]["countryCodeM"].ToString().Contains("+"))
                        {
                            otpModel.MobileNo = ((Newtonsoft.Json.Linq.JToken)item).Root["mobNum"]["countryCodeM"].ToString() + ((Newtonsoft.Json.Linq.JToken)item).Root["mobNum"]["areaM"].ToString() + ((Newtonsoft.Json.Linq.JToken)item).Root["mobNum"]["numM"].ToString();
                        }
                        else
                        {
                            otpModel.MobileNo = "+" + ((Newtonsoft.Json.Linq.JToken)item).Root["mobNum"]["countryCodeM"].ToString() + ((Newtonsoft.Json.Linq.JToken)item).Root["mobNum"]["areaM"].ToString() + ((Newtonsoft.Json.Linq.JToken)item).Root["mobNum"]["numM"].ToString();
                        }
                        otpModel.MobileOtp = otpModel.MobileOtp;
                    }

                    if (string.IsNullOrEmpty(emirateId))
                    {
                    }
                    //JObject jsonObj = JObject.Parse(userDocument[0].ToString());
                    //JObject jsonmobNumObj = JObject.Parse(jsonObj["APTCCRM"]["mobNum"].ToString());
                    //string area = (string)jsonmobNumObj["areaM"].ToString();
                    //if (string.IsNullOrEmpty("area"))
                    //{
                    //    area = string.Empty;
                    //}
                    //string mobileNo = (string)jsonmobNumObj["countryCodeM"] + area + (string)jsonmobNumObj["numM"];
                    //otpModel.KeyId = (string)jsonObj["APTCCRM"]["keyID"];
                    //otpModel.MobileNo = mobileNo;
                    //otpModel.MobileOtp = otpModel.MobileOtp;

                    var sendResult = mobileSMS.SendOtpViaMobile(otpModel.MobileNo, otpModel.MobileOtp, otpModel.Email);
                    if (sendResult == "200")
                    {
                        return(Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), MessageDescriptions.Add, otpModel.Email), new JsonMediaTypeFormatter()));
                    }
                    else
                    {
                        return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), sendResult), new JsonMediaTypeFormatter()));
                    }
                }
                else
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "179-invalid userid or password"), new JsonMediaTypeFormatter()));
                }
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter()));
            }
        }
Beispiel #27
0
        public async Task <IHttpActionResult> InsertUser(Login model)
        {
            //string ppp = EncryptDecryptString.DecodePasswordToFrom64("MTIzNDU2OTk5");
            try
            {
                if (string.IsNullOrEmpty(model.Name))
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "224-name is required"), new JsonMediaTypeFormatter()));
                }
                if (string.IsNullOrEmpty(model.Email))
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "112-email is required"), new JsonMediaTypeFormatter()));
                }
                if (string.IsNullOrEmpty(model.Password))
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "158-Password is required"), new JsonMediaTypeFormatter()));
                }
                var userDocumentEmail = _bucket.Query <object>(@"SELECT * From " + _bucket.Name + " where email= '" + model.Email + "'  and isActive=true and isActive=true and meta().id like'%login_%'").ToList();
                if (userDocumentEmail.Count > 0)
                {
                    return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "105-The e-mail already exists"), new JsonMediaTypeFormatter()));
                }
                if (model.MobNum == null)
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "199-mobnum is required"), new JsonMediaTypeFormatter()));
                }
                else
                {
                    if (string.IsNullOrEmpty(model.MobNum.AreaM))
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "200-areaM is required"), new JsonMediaTypeFormatter()));
                    }
                    if (string.IsNullOrEmpty(model.MobNum.NumM))
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "201-NumM is required"), new JsonMediaTypeFormatter()));
                    }
                    if (string.IsNullOrEmpty(model.MobNum.CountryCodeM))
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "202-CountryCodeM is required"), new JsonMediaTypeFormatter()));
                    }
                }
                if (model.Roles == null)
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "203-roles is required"), new JsonMediaTypeFormatter()));
                }
                else
                {
                    if (string.IsNullOrEmpty(model.Roles.PrimaryRole))
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "204-PrimaryRole is required"), new JsonMediaTypeFormatter()));
                    }
                    if (model.Roles.OtherRoles == null)
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "205-OtherRoles is required"), new JsonMediaTypeFormatter()));
                    }
                }

                var userDocumentPhone = _bucket.Query <object>(@"SELECT * From " + _bucket.Name + " where " + _bucket.Name + ".mobNum.num= '" + model.MobNum.NumM + "' and isActive=true and meta().id like'%login_%'").ToList();

                if (userDocumentPhone.Count > 0)
                {
                    return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "Mobile number already exists"), new JsonMediaTypeFormatter()));
                }

                try
                {
                    List <PrevPassword> prevPassword = new List <PrevPassword>();
                    var    loginDocumentId           = "login_" + Guid.NewGuid();
                    MobNum mobNum = new MobNum();
                    mobNum.CountryCodeM = model.MobNum.CountryCodeM;
                    mobNum.NumM         = model.MobNum.NumM;
                    mobNum.AreaM        = model.MobNum.AreaM;
                    TelNum telNum = new TelNum();
                    if (model.TelNum != null)
                    {
                        telNum.CountryCodeT = model.TelNum.CountryCodeT;
                        telNum.NumT         = model.TelNum.NumT;
                        telNum.AreaT        = model.TelNum.AreaT;
                    }
                    var loginDocument = new Document <Login>()
                    {
                        Id      = loginDocumentId,
                        Content = new Login
                        {
                            Lang        = model.Lang,
                            DocType     = "user",
                            Name        = model.Name,
                            PassSetDate = DataConversion.ConvertYMDHMS(DateTime.Now.ToString()),
                            Password    = EncryptDecryptString.EncodePasswordToBase64(model.Password),
                            Email       = model.Email,
                            EmirateId   = model.EmirateId,
                            //Mobile = model.Mobile,
                            MobNum     = mobNum,
                            TelNum     = telNum,
                            Department = model.Department,
                            Roles      = model.Roles,
                            PrevPass   = prevPassword,
                            IsActive   = true,
                            Created_By = model.Email,
                            UserPhoto  = model.UserPhoto,
                            Created_On = DataConversion.ConvertYMDHMS(DateTime.Now.ToString()),
                        },
                    };
                    var result = _bucket.Insert(loginDocument);
                    if (!result.Success)
                    {
                        //_bucket.Remove(loginResult.Document.Content.Email);
                        return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), result.Message), new JsonMediaTypeFormatter()));
                    }
                    return(Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), MessageDescriptions.Add, result.Document.Content.Email), new JsonMediaTypeFormatter()));
                }
                catch (Exception ex)
                {
                    //_bucket.Remove(result.Document.Id);
                    return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.Message), new JsonMediaTypeFormatter()));
                }

                //}
                // return Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), MessageDescriptions.Add, result..Id), new JsonMediaTypeFormatter());
                //}
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter()));
            }
        }
Beispiel #28
0
 public static string decryptPassword(string value)
 {
     return(EncryptDecryptString.Decrypt(value, "Taj$$Key"));
 }