Example #1
0
        public JsonResult InsertUser([Bind(Exclude = "userId")] User nUser)
        {
            if (ModelState.IsValid)
            {
                User newUser = new User()
                {
                    userName  = nUser.userName,
                    emailAdd  = nUser.emailAdd,
                    FirstName = nUser.FirstName,
                    SurName   = nUser.SurName,
                    mobileNo  = nUser.mobileNo,
                    disabled  = nUser.disabled,
                    Pwd       = MD5Crypt.Encrypt(nUser.Pwd, "admin", true),
                    shiftid   = nUser.shiftid
                };
                try
                {
                    db.Users.Add(newUser);
                    db.SaveChanges();

                    return(Json(new { isError = "F", message = "New user has been added!" }));

                    //return Json(new { isError = "T", message = "Email address already exist." });
                }
                catch (Exception ex)
                {
                    return(Json(new { isError = "T", message = "Could not insert data." }));
                }
            }
            else
            {
                return(Json(new { isError = "T", message = "Could not insert data." }));
            }
        }
Example #2
0
        public HttpResponseMessage RetornarArquivo(string docClienteId)
        {
            //docClienteId = System.Web.HttpUtility.UrlDecode(docClienteId);
            docClienteId = MD5Crypt.Descriptografar(docClienteId);

            DocumentoCliente _documentoCliente = new UploadFileBL().RetornarArquivo(new DocumentoCliente()
            {
                DocClienteId = long.Parse(docClienteId)
            });
            UploadFileBL uploadFileBl = new UploadFileBL();

            WorkingFolder += "\\" + new UploadFileBL().RecuperarCaminhoPastaDocumentosByDocClienteId(long.Parse(docClienteId));

            var file = WorkingFolder + "\\" + _documentoCliente.DocClienteNomeArquivoSalvo;
            HttpResponseMessage result = null;

            if (!File.Exists(file))
            {
                result = new HttpResponseMessage(HttpStatusCode.Conflict);
                return(result);
            }
            else
            {
                result = new HttpResponseMessage(HttpStatusCode.OK);
                var stream = new FileStream(file, FileMode.Open);
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = _documentoCliente.DocClienteNomeArquivoOriginal
                };
                result.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");
                return(result);
            }
        }
Example #3
0
 private void SavePassword_Click(object sender, RoutedEventArgs e)
 {
     if (txtCurrentPassword.Password.Length >= 3 && txtNewPassword.Password.Length >= 3 && txtNewPassword2.Password.Length >= 3)
     {
         if (txtNewPassword.Password.Equals(txtNewPassword2.Password))
         {
             if (User.password.Equals(MD5Crypt.MD5Hash(txtCurrentPassword.Password)))
             {
                 User.password = MD5Crypt.MD5Hash(txtNewPassword.Password);
                 DB.UpdateUser(User);
                 result.Visibility = Visibility.Visible;
                 result.Content    = Lang.SettingsResultPasswordUp;
                 result.Background = Brushes.Green;
             }
             else
             {
                 result.Visibility = Visibility.Visible;
                 result.Content    = Lang.WelcomeLoginFailedWrongPassword;
                 result.Background = Brushes.Red;
             }
         }
         else
         {
             result.Visibility = Visibility.Visible;
             result.Content    = Lang.WelcomeSignPasswordsNotMatch;
             result.Background = Brushes.Red;
         }
     }
     else
     {
         result.Visibility = Visibility.Visible;
         result.Content    = Lang.SettingsPasswordMustGreaterThanThreeChars;
         result.Background = Brushes.Red;
     }
 }
Example #4
0
        public ActionResult Verifychpass(FormCollection frm)
        {
            try
            {
                if (Session["UserID"] == null)
                {
                    return(RedirectToAction("Index", "Home"));
                }


                Chatpata_dabbaEntities1 en = new Chatpata_dabbaEntities1();
                CustomerMaster          cm = new CustomerMaster();

                var pass = Convert.ToString(frm["new_pass"]);
                var id   = Convert.ToInt32(Session["UserID"]);
                var user = en.CustomerMasters.Where(q => q.CustId == id).FirstOrDefault();
                user.Password        = MD5Crypt.Encrypt(pass, "Dabba");
                en.Entry(user).State = System.Data.Entity.EntityState.Modified;

                en.SaveChanges();
                return(RedirectToAction("Admin", "Admin"));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Admin"));
            }
        }
Example #5
0
        public virtual tbl_users GetUserInfo(string userNickName, string pswd)
        {
            MD5Crypt md5     = new MD5Crypt();
            string   encpswd = md5.EncryptMessage(pswd);

            return(uiDao.GetUserInfo(userNickName, encpswd));
        }
        public ActionResult Forgotque(FormCollection frm)
        {
            try
            {
                Chatpata_dabbaEntities1 EntityFile = new Chatpata_dabbaEntities1();


                var email = Convert.ToString(frm["Email"]);

                var user = EntityFile.CustomerMasters.Where(q => q.EmailID == email).FirstOrDefault();
                //Session["UserID"]=details.CustId;

                string pass    = GenerateRandomPassword(6);
                int    chkmail = Mail.SendMail("Your New Password", pass, email);
                user.Password = MD5Crypt.Encrypt(pass, "Dabba");
                EntityFile.Entry(user).State = System.Data.Entity.EntityState.Modified;
                EntityFile.SaveChanges();
                return(RedirectToAction("Index"));
            }

            catch (Exception ex)
            {
                return(RedirectToAction("Forgotpass_new", "Home"));
            }
        }
 public User Create(User user)
 {
     user.AccessKey = MD5Crypt.Criptografar(user.AccessKey);
     _context.Add(user);
     _context.SaveChanges();
     return(user);
 }
        public void ChecarUserAdm()
        {
            PerfilDAL perDAL = new PerfilDAL(db);

            MLL.Perfil perfil = new Perfil();
            perfil = perDAL.Tudo()
                     .Where(p => p.Nome_Perfil == "Administrador")
                     .OrderBy(p => p.Nome_Perfil).FirstOrDefault();

            if (perfil != null)
            {
                UsuarioDAL  usuDAL      = new UsuarioDAL(db);
                MLL.Usuario userCurrent = usuDAL.Tudo()
                                          .Where(u => u.Codigo_Perfil == perfil.Codigo_Perfil)
                                          .FirstOrDefault();

                if (userCurrent == null)
                {
                    MLL.Usuario usuario = new Usuario();

                    usuario.Nome_Usuario = "Wellington Fagundes";
                    usuario.Cargo        = "Programador";
                    usuario.Email        = "*****@*****.**";
                    //Acertar o caminho do arquivo
                    usuario.Path_Image = "C:\\expenses";

                    MD5Crypt md5 = new MD5Crypt();
                    usuario.Senha         = md5.Criptografar(usuario.Email + ";" + "Wsf123@");
                    usuario.Codigo_Perfil = perfil.Codigo_Perfil;
                    usuario.Excluido      = null;

                    usuDAL.Adicionar(usuario);
                }
            }
        }
        public bool Login(Usuario usuario)
        {
            //JObject obj = new JObject();
            bool status = false;

            UsuarioDAL usuDAL = new UsuarioDAL(db);

            //Criptografar senha
            MLL.MD5Crypt cript = new MD5Crypt();
            string       senhacript;

            senhacript = cript.Criptografar(usuario.Email + ";" + usuario.Senha);


            var v = db.Usuario.Where(u => u.Email.Equals(usuario.Email) && u.Senha.Equals(senhacript)).FirstOrDefault();

            if (v != null)
            {
                status = true;
            }
            else
            {
                status = false;
            }

            return(status);
        }
        public JObject InsereUsuario(MLL.Usuario usu)
        {
            JObject obj = new JObject();

            UsuarioDAL usuDAL = new UsuarioDAL(db);

            usu.Email = usu.Email.ToLower();

            if (usuDAL.ObterPorEmail(usu.Email) != null)
            {
                obj.Add(new JProperty("erro", "Email já existe na base"));
                return(obj);
            }

            //Criptografar Senha
            MD5Crypt cript = new MD5Crypt();

            usu.Senha = cript.Criptografar(usu.Email + ";" + usu.Senha);

            if (usuDAL.Adicionar(usu))
            {
                obj.Add(new JProperty("ok", "ok"));
            }
            else
            {
                obj.Add(new JProperty("erro", usuDAL.erro));
            }

            return(obj);
        }
Example #11
0
        public JsonResult UpdateUser(oUser uUser)
        {
            User User = db.Users.SingleOrDefault(x => x.userId == uUser.ID);

            User.userName  = uUser.username;
            User.FirstName = uUser.FirstName;
            User.SurName   = uUser.SurName;
            if (uUser.Password != null)
            {
                User.emailAdd = uUser.EmailAdd;
            }
            User.Pwd      = MD5Crypt.Encrypt(uUser.Password, "admin", true);
            User.mobileNo = uUser.Mobileno;

            try
            {
                db.SaveChanges();

                return(Json(new { isError = "F", message = "Successfully Saved." }));
            }
            catch (Exception ex)
            {
                return(Json(new { isError = "T", message = "Could not insert data." }));
            }
        }
Example #12
0
        public String decryptPassword(int userid)
        {
            String recoveredpassword = "";
            User   user    = db.Users.Single(p => p.userId == userid);
            string oldpass = user.Pwd;

            try
            {
                recoveredpassword = MD5Crypt.Decrypt(oldpass, "admin", true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                user.Pwd = MD5Crypt.Encrypt(user.Pwd, "admin", true);
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            return(recoveredpassword);
        }
Example #13
0
        private bool RequestIsValid(string dealerUserName, string dealerPassword)
        {
            string userName = dealerUserName;
            // MAKE THE PASSWORD MD5 ENCRYPTION
            string    passWord = MD5Crypt.MDee5(dealerPassword);
            ClsDealer dl       = new ClsDealer();

            int isLoginValid = dl.IsDealerLoginValid(userName, passWord);

            return(isLoginValid == 1 ? true : false);
        }
Example #14
0
        public async Task <IActionResult> UpdateAccount([Bind("ID, FirstName, LastName, Email, Password")] User user)
        {
            if (ModelState.IsValid)
            {
                using var _context = new WebAppContext();
                var me = await _context.Users.FindAsync(int.Parse(User.Identity.Name));

                if (me.Password != MD5Crypt.GetMD5Hash(user.Password))
                {
                    ModelState.AddModelError("Password", "Incorrect account password.");
                    return(View(nameof(Update)));
                }

                if (me.Email != user.Email)
                {
                    var userWithEmail = await _context.Users.SingleOrDefaultAsync(u => u.Email == user.Email);

                    if (userWithEmail != null)
                    {
                        ModelState.AddModelError("Email", "Email is already taken.");
                        return(View(nameof(Update)));
                    }
                }
                me.FirstName = user.FirstName;
                me.LastName  = user.LastName;
                me.Email     = user.Email;
                try
                {
                    await _context.SaveChangesAsync();

                    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

                    var identity = new ClaimsIdentity(new[]
                    {
                        new Claim(ClaimTypes.Name, me.ID.ToString()),
                        new Claim("FirstName", me.FirstName),
                        new Claim("Email", me.Email),
                        new Claim(ClaimTypes.Role, "User")
                    }, CookieAuthenticationDefaults.AuthenticationScheme);
                    var principal = new ClaimsPrincipal(identity);
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                    return(RedirectToAction("Index"));
                }
                catch (DbUpdateException ex)
                {
                    Debug.WriteLine(ex.Message);
                    ModelState.AddModelError("", "There was an internal server error. Please try again later.");
                    return(View(nameof(Update)));
                }
            }
            return(View(nameof(Update)));
        }
        public int DescriptografaID(string id)
        {
            MD5Crypt cript = new MD5Crypt();

            try
            {
                return(Int32.Parse(cript.Descriptografar(id)));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public ActionResult CheckLogin(FormCollection frm)
        {
            try
            {
                var Emailid  = Convert.ToString(frm["EmailID"]);
                var password = Convert.ToString(frm["Password"]);


                Chatpata_dabbaEntities1 Entity = new Chatpata_dabbaEntities1();
                CustomerMaster          reg    = new CustomerMaster();
                password = MD5Crypt.Encrypt(password, "Dabba");


                var chkEntry = Entity.CustomerMasters.Where(q => q.EmailID == Emailid && q.Password == password).FirstOrDefault();
                if (chkEntry != null)
                {
                    int?[] rid = (Entity.CustomerMasters.Where(p => p.EmailID == Emailid).Select(q => q.Roleid)).ToArray();

                    int r = Convert.ToInt16(rid[0]);

                    if (r == 1)
                    {
                        Session["UserID"] = chkEntry.CustId;

                        Session["cname"] = chkEntry.FirstName;
                        return(RedirectToAction("Admin", "Admin"));
                    }
                    else if (r == 2)
                    {
                        Session["UserID"] = chkEntry.CustId;
                        Session["cname"]  = chkEntry.FirstName;
                        return(RedirectToAction("Driver", "Driver"));
                    }
                    else
                    {
                        Session["UserID"] = chkEntry.CustId;
                        Session["cname"]  = chkEntry.FirstName;
                        return(RedirectToAction("Customer", "Customer"));
                    }
                }
                else
                {
                    TempData["ErrMsg"] = "Invalid user name or password";
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception e)
            {
                return(RedirectToAction("Index"));
            }
        }
        public string CriptografaID(int id)
        {
            MD5Crypt cript = new MD5Crypt();


            try
            {
                return(cript.Criptografar(id.ToString()));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Example #18
0
        public void MD5Crypt_Encrypt_Decrypt()
        {
            string senha = "Paulo Rogério";

            string senhaCriptografada = MD5Crypt.Encrypt(senha);

            string senhaDesCriptografada = MD5Crypt.Decrypt(senhaCriptografada);


            string senhaMD5 = MD5Crypt.EncryptMD5(senha);

            Assert.AreEqual(senhaCriptografada, "sE0hI8fXaecNxoHI2IokuQ==");
            Assert.AreEqual(senhaDesCriptografada, senha);
            Assert.AreEqual(senhaMD5, "69103C8FA326DB8B39CB87A6492390C6");
        }
Example #19
0
        public async Task <IActionResult> UpdatePassword([Bind("ID, OldPassword, NewPassword, NewConfirmPassword")] UserPassword user)
        {
            if (ModelState.IsValid)
            {
                using var _context = new WebAppContext();
                var me = await _context.Users.FindAsync(int.Parse(User.Identity.Name));

                if (me.Password != MD5Crypt.GetMD5Hash(user.OldPassword))
                {
                    ModelState.AddModelError("OldPassword", "Incorrect account old password.");
                    return(View(nameof(Update)));
                }

                if (me.Password == MD5Crypt.GetMD5Hash(user.NewPassword))
                {
                    ModelState.AddModelError("NewPassword", "Old and new passwords are the same.");
                    return(View(nameof(Update)));
                }

                me.Password = MD5Crypt.GetMD5Hash(user.NewPassword);
                try
                {
                    await _context.SaveChangesAsync();

                    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

                    var identity = new ClaimsIdentity(new[]
                    {
                        new Claim(ClaimTypes.Name, me.ID.ToString()),
                        new Claim("FirstName", me.FirstName),
                        new Claim("Email", me.Email),
                        new Claim(ClaimTypes.Role, "User")
                    }, CookieAuthenticationDefaults.AuthenticationScheme);
                    var principal = new ClaimsPrincipal(identity);
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                    return(RedirectToAction("Index"));
                }
                catch (DbUpdateException ex)
                {
                    Debug.WriteLine(ex.Message);
                    ModelState.AddModelError("", "There was an internal server error. Please try again later.");
                    return(View(nameof(Update)));
                }
            }
            return(View(nameof(Update)));
        }
Example #20
0
        public string ResetPassword(string dealerUserName, string dealerEmail, string mtid)
        {
            string returnString = "0|Wrong details supplied";

            ClsDealer dl = new ClsDealer();

            string reqParams = $"dealerUserName:{dealerUserName}|dealerEmail:{dealerEmail}";

            //log the mobile request
            ClsPayment.LogMobileRequest2(dl.GetDealerCode(dealerUserName).ToString(), DateTime.Now, mtid + "|REQ", "ResetPassword", reqParams);

            //the algorithm seems ideal but kinda slow
            //List<char> l = mtid.ToList<char>();
            //l = l.OrderBy(o => Guid.NewGuid().ToString()).ToList();

            //StringBuilder newPassword = new StringBuilder();

            //foreach (char c in l)
            //    newPassword.Append(c.ToString());

            string newPassword = mtid.Substring(2, 6);

            if (dl.DealerEmailIsCorrect(dealerUserName, dealerEmail))
            {
                dl.ChangeDealerPassword(dealerUserName, MD5Crypt.MDee5(newPassword));

                PortalMailer mailer = new PortalMailer();

                mailer.subject = "Pawakad Password Reset Notification.";
                mailer.emailTo = dealerEmail;
                mailer.body    = "Dear " + dealerUserName + ",<br><br>"
                                 + "You initiated a password reset from your mobile device<br>"
                                 + $"You new password is {newPassword}<br>"
                                 + $"We advice you logon to the web and change t to something different and suitable for you<br>"
                                 + "<br><br> Thank You.";

                mailer.SendMail();
                returnString = $"1|newPassword|{newPassword}";
            }

            mtid += "|RESP";
            //log the mobile response
            ClsPayment.LogMobileRequest2(dl.GetDealerCode(dealerUserName).ToString(), DateTime.Now, mtid, "ResetPassword", returnString);

            return(returnString);
        }
Example #21
0
        public ActionResult AddDriver(FormCollection frm)
        {
            try
            {
                if (Session["UserID"] == null)
                {
                    return(RedirectToAction("Index", "Home"));
                }
                var id = Convert.ToInt32(Session["UserID"]);
                Chatpata_dabbaEntities1 EntityFile = new Chatpata_dabbaEntities1();

                CustomerMaster reg = new CustomerMaster();

                reg.Roleid = 2;

                reg.FirstName = Convert.ToString(frm["FName"]);
                reg.LastName  = Convert.ToString(frm["LName"]);
                reg.Address1  = Convert.ToString(frm["Address1"]);
                reg.Address2  = Convert.ToString(frm["Address2"]);
                reg.Address3  = Convert.ToString(frm["Address3"]);

                reg.Pincode = Convert.ToString(frm["Pincode"]);

                reg.PhoneNo = Convert.ToString(frm["PhoneNo"]);
                //reg.Gender = "";

                //reg.Birthdate = Convert.ToDateTime(frm["Birthdate"]);

                string[] dtarray = frm["Birthdate"].ToString().Split('/');
                reg.Birthdate = Convert.ToDateTime("" + dtarray[1] + "/" + dtarray[0] + "/" + dtarray[2]);

                reg.EmailID = Convert.ToString(frm["EmailID"]);

                reg.Password = MD5Crypt.Encrypt(frm["Password"], "Dabba");
                EntityFile.CustomerMasters.Add(reg);
                EntityFile.SaveChanges();

                return(RedirectToAction("Admin", "Admin"));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #22
0
        public int saveNewPassword(int userid, String newPassword)
        {
            int  success = 0;
            User user    = db.Users.Single(p => p.userId == userid);

            user.Pwd = MD5Crypt.Encrypt(newPassword, "admin", true);

            //string recipient = "soc.alcantara.delonix.com.au";
            try
            {
                success = db.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            //new HRIS_WEB.Controllers.TimecardController().sendMail(recipient, null, "Password Reset.", mailbody.ToString());
            return(success);
        }
Example #23
0
        public async Task <IActionResult> LogIn([Bind("Email, Password")] UserLogIn user, string returnURL = null)
        {
            if (ModelState.IsValid)
            {
                using var _context = new WebAppContext();
                var userdb = await _context.Users.SingleOrDefaultAsync(u => u.Email == user.Email);

                if (userdb == null)
                {
                    ModelState.AddModelError("Email", "Invalid email address.");
                    return(View(user));
                }

                if (!MD5Crypt.VerifyMD5Hash(user.Password, userdb.Password))
                {
                    ModelState.AddModelError("Password", "Incorrect password.");
                    return(View());
                }

                var identity = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, userdb.ID.ToString()),
                    new Claim("FirstName", userdb.FirstName),
                    new Claim("Email", userdb.Email),
                    new Claim(ClaimTypes.Role, "User")
                }, CookieAuthenticationDefaults.AuthenticationScheme);

                var principal = new ClaimsPrincipal(identity);

                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                if (!string.IsNullOrEmpty(returnURL))
                {
                    return(Redirect(returnURL));
                }
                else
                {
                    return(RedirectToAction(nameof(Index), "Devices"));
                }
            }
            return(View(user));
        }
Example #24
0
        private void Login()
        {
            RepositoryFactory factory = new RepositoryFactory();
            IEntityRepository Repo    = factory.Create("user");

            string          loginName = Helper.GetParameterFromRequest("loginName");
            IUserRepository UserRepo  = Repo as IUserRepository;
            User            user      = UserRepo.GetOne(loginName);

            MD5Crypt md5 = new MD5Crypt();
            string   pwd = md5.Encrypt(Helper.GetParameterFromRequest("pwd"));

            if (user.Pwd != pwd)
            {
                Helper.ResponseError(604);
                return;
            }

            Helper.GetSession().Add("userId", user.UserId);
            Helper.Response(user.Serialize());
        }
        public JObject CadastrarUsuario(HttpPostedFileBase arquivo, MLL.Usuario usu, FormCollection form, string caminho, string caminhoRelativo)
        {
            JObject obj = new JObject();

            UsuarioDAL usuDAL = new UsuarioDAL(db);

            usu.Email = usu.Email.ToLower();

            if (usuDAL.ObterPorEmail(usu.Email) != null)
            {
                obj.Add(new JProperty("erro", "Email já existe na base"));
                return(obj);
            }

            //Caminho com o endereço do Web Server para exibir a foto imagem
            var pathSalvarNaBase = Path.Combine("http:\\NOTE\\EXPENSES" + caminhoRelativo);

            //Caminho mapeado no servidor fisicamente
            arquivo.SaveAs(caminho);

            usu.Path_Image = pathSalvarNaBase;


            //Criptografar Senha
            MD5Crypt cript = new MD5Crypt();

            usu.Senha = cript.Criptografar(usu.Email + ";" + usu.Senha);

            if (usuDAL.Adicionar(usu))
            {
                obj.Add(new JProperty("ok", "ok"));
            }
            else
            {
                obj.Add(new JProperty("erro", usuDAL.erro));
            }

            return(obj);
        }
Example #26
0
        public async Task <IActionResult> Register([Bind("FirstName, LastName, Email, Password, ConfirmPassword")] UserRegister newUser, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                using var _context = new WebAppContext();
                var userdb = await _context.Users.SingleOrDefaultAsync(u => u.Email == newUser.Email);

                //email already exists
                if (userdb != null)
                {
                    ModelState.AddModelError("Email", "Email is already taken");
                    return(View());
                }

                User user = new User()
                {
                    FirstName = newUser.FirstName,
                    LastName  = newUser.LastName,
                    Email     = newUser.Email,
                    Password  = MD5Crypt.GetMD5Hash(newUser.Password),
                    CreatedAt = DateTime.Now
                };
                _context.Users.Add(user);
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index", "LogIn", new { returnUrl }));
                }
                catch (DbUpdateException ex)
                {
                    Debug.WriteLine(ex.Message);
                    ModelState.AddModelError("", "There was an internal server error. Please try again later.");
                    return(View());
                }
            }
            return(View());
        }
Example #27
0
        public object FindByLogin(UserVO user)
        {
            bool credentialIsValid = false;

            if (user != null && !string.IsNullOrWhiteSpace(user.Login))
            {
                var baseUser        = _repository.FindByLogin(user.Login);
                var accessEncrypted = MD5Crypt.Criptografar(user.AccessKey);
                credentialIsValid = (baseUser != null && user.Login == baseUser.Login && accessEncrypted == baseUser.AccessKey);
            }

            if (credentialIsValid)
            {
                ClaimsIdentity identity = new ClaimsIdentity(
                    new GenericIdentity(user.Login, "Login"),
                    new []
                {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                    new Claim(JwtRegisteredClaimNames.UniqueName, user.Login)
                }

                    );

                DateTime createDate     = DateTime.Now;
                DateTime expirationDate = createDate + TimeSpan.FromSeconds(_tokenConfiguration.Seconds);

                var    handler = new JwtSecurityTokenHandler();
                string token   = CreateToken(identity, createDate, expirationDate, handler);

                return(SuccessObject(createDate, expirationDate, token));
            }
            else
            {
                return(ExceptionObject());
            }
        }
Example #28
0
 /// <summary>
 /// 创建一个16位流水号
 /// </summary>
 /// <returns></returns>
 public static string GenerateCodeBy16()
 {
     return(MD5Crypt.EncryptBy16(Guid.NewGuid().ToString()).ToLower());
 }
        public ActionResult AddUser(FormCollection frm, HttpPostedFileBase file)
        {
            try
            {
                Chatpata_dabbaEntities1 EntityFile = new Chatpata_dabbaEntities1();

                CustomerMaster reg = new CustomerMaster();

                reg.Roleid = 3;

                reg.FirstName = Convert.ToString(frm["FName"]);
                reg.LastName  = Convert.ToString(frm["LName"]);
                reg.Address1  = Convert.ToString(frm["Address1"]);
                reg.Address2  = Convert.ToString(frm["Address2"]);
                reg.Address3  = Convert.ToString(frm["Address3"]);

                reg.Pincode = Convert.ToString(frm["Pincode"]);

                reg.PhoneNo = Convert.ToString(frm["PhoneNo"]);
                if (Convert.ToString(frm["gender"]) == "male")
                {
                    reg.Gender = "Male";
                }
                else
                {
                    reg.Gender = "Female";
                }

                var newFileName = "";
                if (file != null)
                {
                    string   pic           = System.IO.Path.GetFileName(file.FileName);
                    FileInfo fi            = new FileInfo(pic);
                    string   fileextension = fi.Extension.Substring(1).ToUpper();
                    newFileName = Convert.ToString(Guid.NewGuid()) + "." + fileextension;
                    var FolderPath = "~/Images/";
                    var Imgpath    = Path.Combine(Server.MapPath(FolderPath), newFileName);
                    file.SaveAs(Imgpath);
                    newFileName = FolderPath + newFileName;
                }

                reg.Image = Convert.ToString(frm["Image"]);
                reg.Image = newFileName;

                string[] dtarray = frm["Birthdate"].ToString().Split('/');
                reg.Birthdate = Convert.ToDateTime("" + dtarray[1] + "/" + dtarray[0] + "/" + dtarray[2]);

                reg.EmailID  = Convert.ToString(frm["EmailID"]);
                reg.Password = MD5Crypt.Encrypt(frm["Password"], "Dabba");

                reg.QuestionID = Convert.ToInt32(frm["AID"]);
                reg.Answer     = frm["Answer"];

                EntityFile.CustomerMasters.Add(reg);
                EntityFile.SaveChanges();
                int chkmail = Mail.SendMail("Registration", "Thanks", reg.EmailID);
                //  TempData["msg"] = "Your are successfully registered , please login in to website for further details";

                return(RedirectToAction("Index", "Home"));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #30
0
        public string Login(string dealerUserName, string dealerPassword, string mtid)
        {
            string userName = dealerUserName;
            // MAKE THE PASSWORD MD5 ENCRYPTION
            string    passWord = MD5Crypt.MDee5(dealerPassword);
            ClsDealer dl       = new ClsDealer();

            string reqParams = "dealerUserName:"******"|REQ", "Login", reqParams);

            mtid += "|RESP";

            //FIRST CHECK THAT USER IS NOT LOGGED IN ELSWHERE
            //if logged in elsewhere then inform user and  terminate login proces
            int isDuplicateLogin = 0;// dl.CheckMultiLogin(userName);

            if (isDuplicateLogin == 1)
            {
                string errorMsg = "0|You Have Loged in elsewhere and cannot login at this terminal. Please log out from the other terminal.";
                //log the mobile request
                ClsPayment.LogMobileRequest2(dl.GetDealerCode(userName).ToString(), DateTime.Now, mtid, "Login", errorMsg);

                return(errorMsg);
            }
            else
            {
                int isLoginValid = dl.IsDealerLoginValid(userName, passWord);

                if (isLoginValid == 1)
                {
                    SqlDataReader dr = dl.GetDealerDetails(userName);
                    string        fullName = "", availableCredit = "", dealerEmail = "";

                    while (dr.Read())
                    {
                        fullName        = dr["fullName"].ToString();
                        availableCredit = dr["availableCredit"].ToString();
                        dealerEmail     = dr["dealerEmail"].ToString();
                    }

                    string verNum = dl.GetLatestMobileVersion().ToString();

                    dl.AddMultiLogin(userName);
                    //dl.AddLoginLocation(userName, longitude, latitude, address, mtid);

                    string format = "username_fullname_availableCredit_versionNum_apkLink_brandMsg|"; //vernum = @vernum + | + apkLink

                    string returnString = "1|" + format + userName + "|" + fullName + "|" + availableCredit + "|" + verNum + "|" + dl.GetPushMsg() + "|";

                    //log the mobile request
                    ClsPayment.LogMobileRequest2(dl.GetDealerCode(userName).ToString(), DateTime.Now, mtid, "Login", returnString);

                    return(returnString);
                }
                else
                {
                    string errorMsg = "0|Your Login Is not VALID  ";
                    //log the mobile request
                    ClsPayment.LogMobileRequest2(dl.GetDealerCode(userName).ToString(), DateTime.Now, mtid, "Login", errorMsg);

                    return(errorMsg);
                }
            }
        }