public IActionResult Post(UsuarioCadastroModel model,
                                  [FromServices] UsuarioRepository repository,
                                  [FromServices] MD5Service service)
        {
            if (ModelState.IsValid)
            {
                if (repository.Consultar(model.Email) != null)
                {
                    return(BadRequest("Erro. O email informado já encontra-se cadastrado."));
                }
                else
                {
                    try
                    {
                        var usuario = new Usuario();
                        usuario.Nome        = model.Nome;
                        usuario.Email       = model.Email;
                        usuario.Senha       = service.Encriptar(model.Senha);
                        usuario.DataCriacao = DateTime.Now;

                        repository.Inserir(usuario);
                        return(Ok("Usuário cadastrado com sucesso"));
                    }
                    catch (Exception e)
                    {
                        return(StatusCode(500, e.Message));
                    }
                }
            }
            else
            {
                return(BadRequest());
            }
        }
예제 #2
0
 public async Task <UserClass> GetUserByUserPass(string username, string pass)
 {
     return(await _context.User.Where(
                user => user.User == username &&
                user.Password == MD5Service.MD5Hash(pass) &&
                user.Excluded == 0).FirstOrDefaultAsync());
 }
예제 #3
0
        /// <summary>
        /// Get翻译请求
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="from">原文语言</param>
        /// <param name="to">译文语言</param>
        /// <returns></returns>
        public static async Task <BaiduTranslatorResultDto> Translator(string content, string from = null, string to = null)
        {
            // 判断翻译语言
            if (from != null)
            {
                From = from;
            }
            if (to != null)
            {
                To = to;
            }
            // 签名
            Sign = MD5Service.GenerateMD5(APPID + content + Salt + SecretKey);
            // 参数
            var parameter = string.Format(Parameter, HttpUtility.UrlEncode(content), From, To, APPID, Salt, Sign);
            // GetAsync请求
            var resultString = await HttpRequestService.HttpGetAsync(Url + "?" + parameter);

            // 去除转义字符
            //foreach (char c in resultString)
            //{
            //    if (c != '\\') resultStringBuilder.Append(c);
            //}
            // 返回字符串转换为JSON对象
            return(JsonConvert.DeserializeObject <BaiduTranslatorResultDto>(resultString));
        }
예제 #4
0
        public static async Task <BaiduTranslatorResultDto> TranslatorPost(string content, string from = null, string to = null)
        {
            // 判断翻译语言
            if (from != null)
            {
                From = from;
            }
            if (to != null)
            {
                To = to;
            }
            // 签名
            Sign = MD5Service.GenerateMD5(APPID + content + Salt + SecretKey);
            // 参数
            var parameter = string.Format(Parameter, HttpUtility.UrlEncode(content), From, To, APPID, Salt, Sign);
            // GetAsync请求
            // 如使用POST方式,Content-Type请指定为:application/x-www-form-urlencoded
            // PostAsync请求(由于Get请求可能出现Url过长,获取不到数据,所以采用Post请求)
            var resultString = await HttpRequestService.HttpPostAsync(Url, parameter, "application/x-www-form-urlencoded");

            // 去除转义字符
            //foreach (char c in resultString)
            //{
            //    if (c != '\\') resultStringBuilder.Append(c);
            //}
            // 返回字符串转换为JSON对象
            return(JsonConvert.DeserializeObject <BaiduTranslatorResultDto>(resultString));
        }
        // Ham kiem tra login
        public int checkLogin(string userName, string password)
        {
            var result = _context.UserRegMsts.SingleOrDefault(x => x.emailId == userName);

            if (isAdmin(userName, password))
            {
                return(2);
            }
            if (result == null)
            {
                return(0);
            }
            else
            {
                if (result.status == false)
                {
                    return(-1);
                }
                else
                {
                    using (MD5 md5Hash = MD5.Create())
                    {
                        bool verifyPassword = MD5Service.VerifyMd5Hash(md5Hash, password, result.password);
                        if (verifyPassword)
                        {
                            return(1);
                        }
                        else
                        {
                            return(-2);
                        }
                    }
                }
            }
        }
예제 #6
0
        public IActionResult Post(UsuarioCadastroModel model,
                                  [FromServices] IUsuarioRepository usuarioRepository)
        {
            try
            {
                if (usuarioRepository.Get(model.Email) != null)
                {
                    return(StatusCode(403, "Erro. O email informado já encontra-se cadastrado."));
                }

                var usuario = new Usuario();
                usuario.Nome  = model.Nome;
                usuario.Email = model.Email;
                usuario.Senha = MD5Service.Encrypt(model.Senha);

                usuarioRepository.insert(usuario);

                return(Ok("Usuário cadastrado com sucesso!"));
            }
            catch (Exception e)
            {
                //retornar 500 da api cai no error
                return(StatusCode(500, e.Message));
            }
        }
예제 #7
0
 public DbInitializer(ILogger <DbInitializer> logger, IConfiguration configuration, MD5Service mD5Service)
 {
     Initialized   = false;
     Logger        = logger;
     Configuration = configuration;
     MD5Service    = mD5Service;
 }
        public IActionResult Autenticar(AutenticarModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var criptografia      = new MD5Service();
                    var usuarioRepository = new UsuarioRepository();
                    var usuario           = usuarioRepository.Consultar
                                                (model.Email, criptografia.Encriptar(model.Senha));

                    if (usuario != null)
                    {
                        var perfilRepository = new PerfilRepository();
                        var perfil           = perfilRepository.ObterPorId(usuario.IdPerfil);

                        var credenciais = new ClaimsIdentity(
                            new[]
                        {
                            new Claim(ClaimTypes.Name, usuario.Email),
                            new Claim(ClaimTypes.Role, perfil.Nome)
                        },
                            CookieAuthenticationDefaults.AuthenticationScheme);

                        var acesso = new ClaimsPrincipal(credenciais);
                        HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, acesso);

                        HttpContext.Session.SetString("Nome", usuario.Nome);
                        HttpContext.Session.SetString("Email", usuario.Email);
                        HttpContext.Session.SetString("Perfil", perfil.Nome);
                        HttpContext.Session.SetInt32("IdPerfil", usuario.IdPerfil);
                        HttpContext.Session.SetString("Foto", usuario.Foto);

                        switch (perfil.Nome)
                        {
                        case "Pessoa Física":
                            return(RedirectToAction("Index", "PessoaFisica"));

                        case "Pessoa Jurídica":
                            return(RedirectToAction("Index", "PessoaJuridica"));
                        }
                    }
                    else
                    {
                        TempData["Mensagem"] = "Acesso Negado. Usuário não foi encontrado.";
                    }
                }
                catch (Exception e)
                {
                    TempData["Mensagem"] = e.Message;
                }
            }
            return(View());
        }
        public IActionResult CriarConta(CriarContaModel model)
        {
            if (ModelState.IsValid)
            {
                var files = Request.Form.Files;
                if (files != null && files.Count > 0)
                {
                    var extensao = Path.GetExtension(files.First().FileName);

                    if (extensao.Equals(".jpg") || extensao.Equals(".jpeg") || extensao.Equals(".png"))
                    {
                        try
                        {
                            var md5 = new MD5Service();

                            var usuario = new Usuario();
                            usuario.Nome        = model.Nome;
                            usuario.Email       = model.Email;
                            usuario.Senha       = md5.Encriptar(model.Senha);
                            usuario.DataCriacao = DateTime.Now;
                            usuario.Foto        = "/imagens/usuarios/" + usuario.Email + extensao;
                            usuario.IdPerfil    = model.IdPerfil;

                            var repository = new UsuarioRepository();
                            repository.Inserir(usuario);

                            using (var stream = new FileStream(hostingEnvironment.WebRootPath + usuario.Foto, FileMode.Create))
                            {
                                files.First().CopyTo(stream);
                            }

                            TempData["Mensagem"] = "Usuário cadastrado com sucesso.";
                            ModelState.Clear();

                            //EnviarMensagem(usuario);
                        }
                        catch (Exception e)
                        {
                            TempData["Mensagem"] = e.Message;
                        }
                    }
                    else
                    {
                        TempData["Mensagem"] = "Envie apenas arquivos de extensão jpg, jpeg ou png.";
                    }
                }
                else
                {
                    TempData["Mensagem"] = "Por favor, envie a foto do usuário.";
                }
            }
            return(View(new CriarContaModel()));
        }
        public IActionResult Post(LoginModel model, [FromServices] UsuarioRepository repository,
                                  [FromServices] MD5Service service,
                                  [FromServices] TokenConfiguration tokenConfiguration)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var usuario = repository.Consultar(model.Email, service.Encriptar(model.Senha));

                    if (usuario != null)
                    {
                        //GERANDO O TOKEN!!
                        ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(usuario.Email, "Login"),
                                                                     new[] {
                            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                            new Claim(JwtRegisteredClaimNames.UniqueName, model.Email)
                        });

                        DateTime dataCriacao   = DateTime.Now;
                        DateTime dataExpiracao = dataCriacao + TimeSpan.FromSeconds(LoginConfiguration.Seconds);

                        var handler       = new JwtSecurityTokenHandler();
                        var securityToken = handler.CreateToken(new SecurityTokenDescriptor
                        {
                            Issuer             = LoginConfiguration.Issuer,
                            Audience           = LoginConfiguration.Audience,
                            SigningCredentials = tokenConfiguration.SigningCredentials,
                            Subject            = identity,
                            NotBefore          = dataCriacao,
                            Expires            = dataExpiracao
                        });

                        var token = handler.WriteToken(securityToken);
                        return(Ok(token));    //retornando sucesso e enviando o TOKEN!
                    }
                    else
                    {
                        return(Unauthorized());
                    }
                }
                catch (Exception e)
                {
                    return(StatusCode(500, e.Message));
                }
            }
            else
            {
                return(BadRequest());
            }
        }
예제 #11
0
 //==========================================================
 //LOGIN VIEW==========================================================
 public bool CheckAccountExist(string IDUser, string Password)
 {
     foreach (User user in Database.Users)
     {
         if (user.IDUser == IDUser)
         {
             string encodedPass = MD5Service.EncodeToMD5(Password);
             if (encodedPass.ToLower() == user.Password.ToLower())
             {
                 return(true);
             }
             break;
         }
     }
     return(false);
 }
예제 #12
0
        public string Login(string name, string password)
        {
            var passwords = MD5Service.Encrypt(password);

            var admin = db.Admins.FirstOrDefault(a => a.Name == name && a.Password == passwords);

            if (admin != null)
            {
                //Session.
                Session["adminLogedIn"] = true;
                Session["adminId"]      = admin.Name;

                return("Login Success");
            }

            return("登录失败");
        }
예제 #13
0
        public void MD5HashingTest()
        {
            //Arrange
            var md5Service   = new MD5Service();
            var bufferLength = 5000;
            var baseBuffer   = new byte[bufferLength];
            var random       = new Random();

            for (int i = 0; i < bufferLength; i++)
            {
                baseBuffer[i] = (byte)random.Next(255);
            }

            //Act
            var hashedBuffer = md5Service.GetHash(baseBuffer);
            var verifyResult = md5Service.VerifyHash(baseBuffer, hashedBuffer);

            //Assert
            Assert.IsTrue(verifyResult);
        }
 //
 public bool isAdmin(string userName, string password)
 {
     using (MD5 md5Hash = MD5.Create())
     {
         try
         {
             AdminLoginMst adminLogin     = _context.AdminLoginMsts.First(item => item.username.Equals(userName));
             bool          verifyPassword = MD5Service.VerifyMd5Hash(md5Hash, password, adminLogin.password);
             if (adminLogin == null || !verifyPassword)
             {
                 return(false);
             }
             return(true);
         }
         catch (Exception)
         {
             return(false);
         }
     }
 }
예제 #15
0
 public IActionResult Post(LoginModel model,
                           [FromServices] IUsuarioRepository usuarioRepository,
                           [FromServices] TokenService tokenService)
 {
     try
     {
         if (usuarioRepository.Get(model.Email, MD5Service.Encrypt(model.Senha)) != null)
         {
             var token = tokenService.GenerateToken(model.Email);
             return(Ok(token));
         }
         else
         {
             return(StatusCode(403, "Acesso negado. Usuário não foi encontrado."));
         }
     }
     catch (Exception e)
     {
         return(StatusCode(500, e.Message));
     }
 }
예제 #16
0
        public async void Reset()
        {
            if (!CheckValidNewPassword())
            {
                return;
            }
            ShowError = false;

            user.Password = MD5Service.EncodeToMD5(NewPassword);

            try
            {
                using (UserDialogs.Instance.Loading("Reseting.."))
                {
                    //update user ở database server
                    var httpClient = new HttpClient();
                    await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "user/update", user);

                    //update user ở database local
                    DataUpdater.UpdateUser(user);
                }
            }
            catch
            {
                await App.Current.MainPage.DisplayAlert("Error", "Action fail, check your internet connection and try again!", "OK");

                return;
            }



            MessageService.Show("Update infor successfully", 0);

            //PUSH NOTI
            string datas = PushNotificationService.ConvertDataUpdateUser(user);

            PushNotificationService.Push(NotiNumber.UpdateUser, datas, true);

            await App.Current.MainPage.Navigation.PopToRootAsync();
        }
예제 #17
0
        public string ValidationSuccess(Member memberData)
        {
            Member newMember = new Member()
            {
                Id           = Guid.NewGuid().ToString(),
                Email        = memberData.Email,
                Password     = MD5Service.Encrypt(memberData.Password),
                Name         = memberData.Name,
                Phone        = memberData.Phone,
                Sex          = memberData.Sex,
                Birth        = memberData.Birth,
                Varification = memberData.Varification
            };

            db.Members.Add(newMember);
            if (db.SaveChanges() > 0)
            {
                //发送邮箱验证
                //如果发送成功,return
                StringBuilder sb = new StringBuilder();
                sb.Append("안녕하세요");
                sb.Append("<br/>");
                sb.Append("청도투어에 오신걸 환영합니다.");
                sb.Append("<br/>");
                sb.Append("아래에 link를 클릭후 메일 인증 바랍니다");
                sb.Append("<br/>");
                sb.Append("http://58.87.108.189:80/Register/Success?email=" + memberData.Email);
                sb.Append("<br/>");
                sb.Append("<br/>");
                sb.Append("감사합니다");
                MailService mailService = new MailService(memberData.Email, "[청도투어]회원가입 인증", sb.ToString());
                if (mailService.isSent() == true)
                {
                    return("회원가입 완료");
                }
            }

            return("회원가입 실패");
        }
예제 #18
0
        public string Login(UserDetails userDetails)
        {
            var password = MD5Service.Encrypt(userDetails.password);

            var member = db.Members.FirstOrDefault(m => m.Email == userDetails.email && m.Password == password);

            if (member != null && member.Varification == 0)
            {
                return("Please varify your email");
            }
            else if (member != null && member.Varification == 1)
            {
                //Session.
                Session["logedIn"]  = true;
                Session["memberId"] = member.Id;
                Session.Timeout     = 60;

                return("Login Success");
            }

            return("Login Failed");
        }
예제 #19
0
        public async Task <UserClass> InsertUser(UserClass userClass)
        {
            userClass.CreateAt   = DateTime.Now;
            userClass.ModifiedAt = DateTime.Now;
            userClass.Password   = MD5Service.MD5Hash(userClass.Password);

            UserClass userClassValidate = await GetUserByUser(userClass.User);

            if (userClassValidate != null)
            {
                throw new Exception("User already exists!");
            }

            _context.User.Add(userClass);
            await _context.SaveChangesAsync();

            userClass.Secret = AppService.SecretGenerate(userClass.UserId).ToUpper();
            _context.Update(userClass);
            await _context.SaveChangesAsync();

            return(userClass);
        }
        public ActionResult Resister(UserRegMst model)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                model.password = MD5Service.GetMd5Hash(md5Hash, model.password);
            }
            model.status = true;
            model.cdate  = DateTime.Now;
            _context.UserRegMsts.Add(model);
            if (_context.UserRegMsts.Where(item => item.emailId == model.emailId).FirstOrDefault() != null)
            {
                ViewBag.ExistsEmail = "Email is already exists";
                return(View("Login"));
            }
            _context.SaveChanges();
            var user        = GetByUserName(model.emailId);
            var userSession = new UserLogin();

            userSession.UserID   = user.userId;
            userSession.UserName = user.emailId; // user.UserName in Database
            userSession.Role     = "user";
            Session.Add(CommonConstants.USER_SESSION, userSession);
            return(RedirectToAction("Index", "Client"));
        }
        public async void SaveChange()
        {
            //TEST INTERNET CONNECTTION
            var    httpClient = new HttpClient();
            string x          = "";

            try
            {
                var testInternet = await httpClient.GetStringAsync(ServerDatabase.localhost + "store/getstorebyid/test");

                x = testInternet;
            }
            catch (Exception ex)
            {
                await App.Current.MainPage.DisplayAlert("Error", "Action fail, check your internet connection and try again!", "OK");

                return;
            }

            string message = CheckInfor();

            if (message != "")
            {
                var app = GroceryApp.Views.Drawer.AppDrawer.GetInstance();
                app.DisplayAlert("Error", message, "OK");
                return;
            }
            if (ImagePath != "" && isNewImage)
            {
                Account account = new Account(
                    "ungdung-grocery-xamarin-by-dk",
                    "378791526477571",
                    "scsyCxQS_C74MbAGdOutpwrzlnU"
                    );

                Cloudinary cloudinary   = new Cloudinary(account);
                var        uploadParams = new ImageUploadParams()
                {
                    File = new FileDescription(ImagePath)
                };
                try
                {
                    using (UserDialogs.Instance.Loading("Saving.."))
                    {
                        var uploadResult = await cloudinary.UploadAsync(uploadParams);

                        string url = uploadResult.SecureUri.ToString();
                        CurrentUser.ImageURL = url;
                        isNewImage           = false;
                    }
                }
                catch (Exception ex)
                {
                    var page = UserSettingView.GetInstance();
                    await page.DisplayAlert("Error", "Error upload image to server, try again!", "Ok");
                }
            }

            CurrentUser.UserName    = FullName;
            CurrentUser.PhoneNumber = PhoneNumber;
            CurrentUser.BirthDate   = BirthDate;
            CurrentUser.Email       = Email;
            CurrentUser.Password    = MD5Service.EncodeToMD5(Infor.Password);
            using (UserDialogs.Instance.Loading("Updating.."))
            {
                //update user ở database server
                await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "user/update", CurrentUser);

                //update user ở database local
                DataUpdater.UpdateUser(CurrentUser);
            }

            MessageService.Show("Update infor successfully", 0);

            //PUSH NOTI
            string datas = PushNotificationService.ConvertDataUpdateUser(CurrentUser);

            PushNotificationService.Push(NotiNumber.UpdateUser, datas, true);
        }
예제 #22
0
        public async void SignUp()
        {
            if (!CheckValidNewPassword())
            {
                return;
            }
            if (CheckExistUsername())
            {
                return;
            }

            ShowError = false;

            //TEST INTERNET CONNECTTION =========================================
            var    httpClient = new HttpClient();
            string x          = "";

            try
            {
                var testInternet = await httpClient.GetStringAsync(ServerDatabase.localhost + "store/getstorebyid/test");

                x = testInternet;
            }
            catch (Exception ex)
            {
                var stack = App.Current.MainPage.Navigation.NavigationStack;
                var page  = stack[stack.Count - 1];
                await page.DisplayAlert("Error", "Action fail, check your internet connection and try again!", "OK");

                return;
            }
            //===================================================
            //TẠO STORE
            string idStore  = "Store_" + DateTime.Now.ToString("HHmmss");
            Store  newStore = new Store
            {
                IDStore          = idStore,
                StoreName        = "",
                ImageURL         = "defaultstore",
                StoreDescription = "",
                StoreAddress     = "###",
                RatingStore      = 0,
                IsActive         = 0,
            };
            //encode password
            string encodePass = MD5Service.EncodeToMD5(NewPassword);
            //TẠO USER TƯƠNG ỨNG
            User newUser = new User
            {
                IDUser      = Username,
                Password    = encodePass,
                IDStore     = idStore,
                PhoneNumber = "",
                Address     = "###",
                Email       = "",
                ImageURL    = "defaultuser",
                BirthDate   = DateTime.Today,
                UserName    = "",
                IsLogined   = 0
            };

            //insert STORE và USER lên database local
            DataUpdater.AddStore(newStore);
            DataUpdater.AddUser(newUser);
            //insert STORE và USER lên database online
            await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "store/insert", newStore);

            await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "user/insert", newUser);

            await App.Current.MainPage.Navigation.PopAsync();
        }