public ActionResult Login([Bind(Include = "Email, Password")] LoginViewModel loginViewModel)
 {
     if (ModelState.IsValid)
     {
         UserLoginDTO loggedInUserCredentialsDTO = LoginMapper.Map <LoginViewModel, UserLoginDTO>(loginViewModel);
         try
         {
             UserInfoDTO loggedInUserInfoDTO = UserBusinessContextObject.LoginUser(loggedInUserCredentialsDTO);
             Session["UserID"] = loggedInUserInfoDTO.ID;
             return(RedirectToAction("Index", "Home"));
         }
         catch (InvalidLoginException ex)
         {
             ModelState.AddModelError("", "Invalid Login Credentials");
             return(View(loginViewModel));
         }
         catch (IncorrectPasswordException ex)
         {
             ModelState.AddModelError("", "Incorrect password");
             return(View(loginViewModel));
         }
         catch (Exception ex)
         {
             ModelState.AddModelError("", "Something Went wrong. Please Try again later");
             return(View("Error"));
         }
     }
     return(View(loginViewModel));
 }
Exemplo n.º 2
0
        public async Task <IActionResult> Login(UserLoginDTO userLoginDTO)
        {
            var userFromRepo = await _repo.Login(userLoginDTO.Username, userLoginDTO.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.Username)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }
Exemplo n.º 3
0
        public async Task <AuthUserDTO> Authorize(UserLoginDTO userDto)
        {
            var userEntity = await _context.Users2
                             .Include(u => u.Avatar)
                             .FirstOrDefaultAsync(u => u.Email == userDto.Email);

            if (userEntity == null)
            {
                throw new NotFoundException(nameof(User));
            }

            if (!SecurityHelper.ValidatePassword(userDto.Password, userEntity.Password, userEntity.Salt))
            {
                throw new InvalidUsernameOrPasswordException();
            }

            var token = await GenerateAccessToken(userEntity.Id, userEntity.UserName, userEntity.Email);

            var user = _mapper.Map <UserDTO>(userEntity);

            return(new AuthUserDTO
            {
                User = user,
                Token = token
            });
        }
        public async Task <IActionResult> Login([FromBody] UserLoginDTO userLoginDto)
        {
            Console.WriteLine(userLoginDto);
            var userFromRepo = await _repo.Login(userLoginDto.Username.ToLower(), userLoginDto.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            // generate token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = System.Text.Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:Token").Value);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                    new Claim(ClaimTypes.Name, userFromRepo.Username),
                    new Claim(ClaimTypes.Role, userFromRepo.Role)
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                            SecurityAlgorithms.HmacSha512Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            var user = _mapper.Map <UserDetailsDTO>(userFromRepo);

            return(Ok(new { tokenString, user }));
        }
Exemplo n.º 5
0
        public async Task <IActionResult> UserLogin(UserLoginDTO userLoginDTO)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(userLoginDTO.Email);

                if (user != null)
                {
                    var result = await _signInManager.PasswordSignInAsync(user, userLoginDTO.Password, userLoginDTO.RememberMe, false);//hesap kilitlenme istemiyorum false verdim.

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError("", "E-Mail adresi veya şifre hatalı tekrar deneyiniz.");
                        return(View());
                    }
                }
                else
                {
                    ModelState.AddModelError("", "E-Mail adresi veya şifre hatalı tekrar deneyiniz.");
                    return(View());
                }
            }

            else
            {
                return(View());
            }
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Login(UserLoginDTO userLoginDTO)
        {
            try
            {
                var user = await _userManager.FindByNameAsync(userLoginDTO.UserName);

                var result = await _signInManager.CheckPasswordSignInAsync(user, userLoginDTO.Password, false);

                if (result.Succeeded)
                {
                    var appUser = await _userManager.Users.FirstOrDefaultAsync(u => u.NormalizedUserName == userLoginDTO.UserName.ToUpper());

                    var userToReturn = _mapper.Map <UserLoginDTO>(appUser);

                    return(Ok(new
                    {
                        token = GenerateJWToken(appUser).Result,
                        user = userToReturn
                    }));
                }

                return(Unauthorized());
            }
            catch (Exception)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Banco dados Falhou"));
            }
        }
Exemplo n.º 7
0
 public User CreateUserLoginEntity(UserLoginDTO userDTO)
 {
     return(new User()
     {
         EmailAddress = userDTO.EmailAddress,
         Password = userDTO.Password
     });
 }
Exemplo n.º 8
0
 [HttpPost("addProduct")] //locahost:123123/api/Product/addProduct, MODEL
 public async Task <ResultDTO> addProduct([FromBody] UserLoginDTO model)
 {
     return(new ResultDTO
     {
         Message = "OK",
         Status = 200
     });
 }
Exemplo n.º 9
0
        public async Task <UserLoginDTO> GetDataAsync(string hos_code)
        {
            UserLoginDTO menu = new UserLoginDTO();

            menu = await _apiHelper.GetDataByIdAsync <UserLoginDTO>("userlogin_api/Get_Data", hos_code);

            return(menu);
        }
        public ValidUserCreateableToken GetValidUserCreateableToken([FromBody] UserLoginDTO userLoginDTO)
        {
            //Tuple<bool,string> response = _UsersRepo.ValidateUserCrendentialsAndGetType
            //      (userLoginDTO.Email, userLoginDTO.Password).ToTuple();
            var token = new ValidUserCreateableToken();

            return(token);
        }
Exemplo n.º 11
0
        public ActionResult UserInfo()
        {
            ViewBag.CrruentAuthority = GetAuthority("095006001");
            UserLoginDTO user = (UserLoginDTO)Session["UserLoginInfo"];

            ViewBag.UserType = user.UserType;
            return(View());
        }
Exemplo n.º 12
0
        public async Task <AppUser> CheckOutUser(UserLoginDTO userLoginDTO)
        {
            var user = await genericDal.GetByFilter(
                I => I.Username.Equals(userLoginDTO.Username) &&
                I.Password.Equals(userLoginDTO.Password));

            return(user);
        }
Exemplo n.º 13
0
 protected void Page_Load(object sender, EventArgs e)
 {
     userLogin = getUserLogin();
     if (!IsPostBack)
     {
         LoadData();
         Page.Header.Title = "Thông tin tài khoản!!!";
     }
 }
Exemplo n.º 14
0
        public void LoginTest()
        {
            var userLogin = new UserLoginDTO {
                Login = "******", Password = "******"
            };
            var loginResult = this.userService.Login(userLogin);

            Assert.AreEqual(OperationStatus.Success, loginResult.OperationStatus);
        }
        public async Task <ResultDTO> Login([FromBody] UserLoginDTO model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(new ResultErrorDTO
                    {
                        Code = 405,
                        Message = "ERROR!",
                        Errors = CustomValidator.getErrorsByModelState(ModelState)
                    });
                }
                else
                {
                    var result = _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false).Result;

                    if (result.Succeeded)
                    {
                        var user = await _userManager.FindByEmailAsync(model.Email);

                        await _signInManager.SignInAsync(user, false);

                        return(new ResultLoginDTO
                        {
                            Code = 200,
                            Message = "OK!",
                            Token = _IJWTTokenService.CreateToken(user)
                        });
                    }
                    else
                    {
                        return(new ResultErrorDTO
                        {
                            Code = 405,
                            Message = "ERROR!",
                            Errors = new List <string>()
                            {
                                "Incorrect email or password!"
                            }
                        });
                    }
                }
            }
            catch (Exception e)
            {
                return(new ResultErrorDTO
                {
                    Code = 500,
                    Message = "ERROR!",
                    Errors = new List <string>
                    {
                        e.Message
                    }
                });
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="lngdto"></param>
        /// <returns></returns>
        public static UserLoginDTO Login(LoginDTO lngdto)
        {
            //var gg =GlobalStaticData.StructureInfo;
            UserLoginDTO ulngdto = null;

            ulngdto = GetAPI <UserLoginDTO>(WebConfiger.MasterDataServicesUrl + "Login?logins=" + TransformHelper.ConvertDTOTOBase64JsonString(lngdto));

            return(ulngdto);
        }
Exemplo n.º 17
0
        public ActionResult Query(LssSearchDTO dto)
        {
            UserLoginDTO lng = Session["UserLoginInfo"] as UserLoginDTO;

            dto.UserInfo = lng.UserInfo();
            var result = _LssService.Query(dto);

            return(new JsonResult(result));
        }
Exemplo n.º 18
0
        public ActionResult Query(FcpaSearchDTO dto)
        {
            UserLoginDTO lng = Session["UserLoginInfo"] as UserLoginDTO;

            dto.UserInfo = lng.UserInfo();
            var result = FcpaProvider.Query(dto);

            return(new JsonResult(result));
        }
Exemplo n.º 19
0
        public UserLoginDTO RegisterNew(User user)
        {
            UserUtil Util = new UserService();

            if (Util.ObjectIsNull(user))
            {
                throw new NotFoundException("Usuário não está preenchido!");
            }

            if (!Util.ObjectIsNull(_repository.GetUserByCPF(user.CPF)))
            {
                throw new BadRequestException($"Já existe um usuário cadastrado com este cpf: {user.CPF}, faça login :)");
            }

            if (Util.NameIsEmty(user))
            {
                throw new BadRequestException($"Nome deve ser preenchido {user.Name}");
            }

            if (Util.EmailIsEmpty(user))
            {
                throw new BadRequestException($"Email deve ser preenchido {user.Email}");
            }

            if (Util.StringIsNull(user.Password))
            {
                throw new BadRequestException("SENHA deve ser preenchida");
            }

            if (Util.CPFIsEmpty(user))
            {
                throw new BadRequestException("CPF deve ser preenchido");
            }

            if (_cpfValidate.ValidaCPF(user.CPF) == false)
            {
                throw new BadRequestException($"CPF inválido: {user.CPF}");
            }

            try
            {
                _repository.Create(user);
                UserLoginDTO userLogged = new UserLoginDTO();
                userLogged.CPF           = user.CPF;
                userLogged.Email         = user.Email;
                userLogged.Name          = user.Name;
                userLogged.UserCompanies = user.UserCompanies;
                userLogged.UserEnum      = user.UserEnum;
                userLogged.UserRole      = user.UserRole;
                return(userLogged);
            }
            catch (Exception e)
            {
                throw new Exception($"Tipo da excessão: {e.GetType()}");
            }
        }
        public async Task <ActionResult <AuthTokenReadDTO> > Login([FromBody] UserLoginDTO userLogin)
        {
            var request  = new LoginCommand(userLogin);
            var response = await _mediator.Send(request);

            return(response.Match <ActionResult <AuthTokenReadDTO> >(
                       token => Ok(token),
                       credentials => BadRequest("Invalid credentials")
                       ));
        }
Exemplo n.º 21
0
        public void LoginUnitOfWorkReconnectThrowsExceptionReturnsFalse()
        {
            UserLoginDTO userLogin = new UserLoginDTO();

            unitOfWork.Setup(u => u.Reconnect(It.IsAny <string>(), It.IsAny <string>())).Throws(new Exception());

            LoginServiceMessage result = service.Login(userLogin);

            Assert.IsFalse(result.IsSuccessful);
        }
Exemplo n.º 22
0
        public ActionResult AddSiblingTag(int?tagID, int?productLineID, string tagName)
        {
            UserLoginDTO lng = Session["UserLoginInfo"] as UserLoginDTO;
            DocumentDTO  dto = new DocumentDTO {
                UserInfo = lng.UserInfo()
            };
            var result = _LssService.AddSiblingTag(tagID, productLineID, tagName);

            return(new JsonResult(result));
        }
Exemplo n.º 23
0
        public void LoginPasswordIsEncrypted()
        {
            UserLoginDTO userLogin = new UserLoginDTO();

            encryptor.Setup(e => e.Encrypt(It.IsAny <string>())).Verifiable("Encrypt method was not called");

            service.Login(userLogin);

            encryptor.VerifyAll();
        }
Exemplo n.º 24
0
        public ActionResult DeleteTag(int tagID)
        {
            UserLoginDTO lng = Session["UserLoginInfo"] as UserLoginDTO;
            DocumentDTO  dto = new DocumentDTO {
                UserInfo = lng.UserInfo()
            };
            var result = _LssService.DeleteTag(tagID);

            return(new JsonResult(result));
        }
Exemplo n.º 25
0
        public ActionResult RenameTag(int tagID, string tagName)
        {
            UserLoginDTO lng = Session["UserLoginInfo"] as UserLoginDTO;
            DocumentDTO  dto = new DocumentDTO {
                UserInfo = lng.UserInfo()
            };
            var result = _LssService.RenameTag(tagID, tagName);

            return(new JsonResult(result));
        }
Exemplo n.º 26
0
        public ActionResult <User> Login([FromBody] UserLoginDTO user)
        {
            var res = _repository.validateUser(user);

            if (res == null)
            {
                return(StatusCode(401, $"email or password invalid"));
            }
            return(res);
        }
        public IHttpActionResult Login([FromBody] UserLoginDTO login)
        {
            var loginResult = new AccountServices().LoginUser(login.username, login.password);

            if (loginResult != null)
            {
                return(Json(loginResult));
            }
            return(this.NotFound());
        }
Exemplo n.º 28
0
        public void IncorrectPasswordTest()
        {
            var userLogin = new UserLoginDTO {
                Login = "******", Password = "******"
            };
            var validationResult = this.userLoginValidator.Validate(userLogin);

            Assert.False(validationResult.IsValid);
            TestContext.Write(validationResult.ToString());
        }
Exemplo n.º 29
0
        /// <summary>
        /// 修改行政区划信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ActionResult UpdateRegion(RegionOperateDTO dto)
        {
            UserLoginDTO user = (UserLoginDTO)Session["UserLoginInfo"];

            dto.ModifyUser = user.FullName;
            dto.ModifyTime = DateTime.Now;
            var result = AreaRegionProvider.UpdateRegion(dto);

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 30
0
        public void LoginTest()
        {
            var user = new UserLoginDTO {
                Login = "******", Password = "******"
            };
            var response = this.frontServiceClient.Login(user);

            Assert.AreEqual(OperationStatus.Success, response.OperationStatus);
            TestContext.Write(response.AttachedInfo);
        }
Exemplo n.º 31
0
        /// <summary>
        /// 得到所有用户申请信息(含模糊查询)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ActionResult GetUserApply(UserApplySearchDTO dto)
        {
            ResultData <List <UserApplyResultDTOModel> > result = null;
            UserLoginDTO user = (UserLoginDTO)Session["UserLoginInfo"];

            dto.RoleIDlist = user.CurrentRoleIDList;
            result         = UserAuthorityProvider.GetUserApply(dto);

            return(Json(result.Object, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 32
0
 protected void Page_Load(object sender, EventArgs e)
 {
     userLogin = getUserLogin();
     if (!IsPostBack)
     {
         try
         {
             //loadData();
             package();
         }
         catch (Exception)
         {
         }
     }
 }
Exemplo n.º 33
0
 public ActionResult Login(User user)
 {
     if (ModelState.IsValid)
     {
         if (UserManagement.isValid(user.Username, user.Password))
         {
             if (UserManagement.IsAdmin(user.Username, user.Password))
             {
                 FormsAuthentication.SetAuthCookie(user.Username, user.RememberMe);
                 Session["User"] = new UserLoginDTO { Username = user.Username };
                 return RedirectToAction("AdminPage", "User");
             }
             FormsAuthentication.SetAuthCookie(user.Username, user.RememberMe);
             Session["User"] = new UserLoginDTO { Username = user.Username };
             return RedirectToAction("CustomerPage", "User");
         }
         ModelState.AddModelError("General", "Password is incorrect!");
     }
     return View(user);
 }
Exemplo n.º 34
0
 protected void Page_Load(object sender, EventArgs e)
 {
     userLogin = getUserLogin();
     if (!IsPostBack)
     {
         try
         {
             loadData();
         }
         catch (Exception ex)
         {
             pnError.Visible = true;
             lblError.Text = "Hệ thống đang chờ quá lâu, vui lòng tải lại trang !";
         }
     }
 }
Exemplo n.º 35
0
 protected void Page_Load(object sender, EventArgs e)
 {
     userLogin = getUserLogin();
     if (!IsPostBack)
     {
         upgradeservices.Visible = false;
         extendbox.Visible = false;
         LoadData();
         LoadPackageTime();
         LoadAvailableService();
     }
 }
Exemplo n.º 36
0
 public void tblUserLogin_insert(UserLoginDTO dt)
 {
     string sql = "INSERT INTO tblUserLogin(Username, Password, DepartmentId) " +
                  "VALUES(@Username, @Password, @DepartmentId)";
     SqlCommand   cmd = new SqlCommand(sql, ConnectionData._MyConnection);
     cmd.CommandType = CommandType.Text;
     cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = dt.Username;
     cmd.Parameters.Add("@Password", SqlDbType.NVarChar).Value = dt.Password;
     cmd.Parameters.Add("@DepartmentId", SqlDbType.Int).Value = dt.DepartmentId;
     cmd.ExecuteNonQuery();
     cmd.Dispose();
 }
Exemplo n.º 37
0
 protected void Page_Load(object sender, EventArgs e)
 {
     userLogin = getUserLogin();
     if (!IsPostBack)
     {
         InitBUS();
         LoadDepartmentList();
     }
 }
Exemplo n.º 38
0
 public void tblUserLogin_Update(UserLoginDTO dt)
 {
     string sql = "UPDATE tblUserLogin SET " +
             "Password = @Password, " +
             "DepartmentId = @DepartmentId " +
             " WHERE UserId = @UserId";
     SqlCommand cmd = new SqlCommand(sql, ConnectionData._MyConnection);
     cmd.CommandType = CommandType.Text;
     cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = dt.UserId;
     cmd.Parameters.Add("@Password", SqlDbType.NVarChar).Value = dt.Password;
     cmd.Parameters.Add("@DepartmentId", SqlDbType.NVarChar).Value = dt.DepartmentId;
     cmd.ExecuteNonQuery();
     cmd.Dispose();
 }
Exemplo n.º 39
0
 public void tblUserLoginSubClient_insert(UserLoginDTO dt)
 {
     string sql = "INSERT INTO tblUserLogin(Username, Password, UserType,Is_Block,DepartmentId) " +
                  "VALUES(@Email, @Password, @UserType,@Is_Block,@UserId) ";
     SqlCommand cmd = new SqlCommand(sql, ConnectionData._MyConnection);
     cmd.CommandType = CommandType.Text;
     cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = dt.Email;
     cmd.Parameters.Add("@Password", SqlDbType.NVarChar).Value = dt.Password;
     cmd.Parameters.Add("@UserType", SqlDbType.Int).Value = dt.UserType;
     cmd.Parameters.Add("@Is_Block", SqlDbType.Bit).Value = dt.Is_Block;
     cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = dt.UserId;
     cmd.ExecuteNonQuery();
     cmd.Dispose();
 }
Exemplo n.º 40
0
    protected void Page_Load(object sender, EventArgs e)
    {
        userLogin = getUserLogin();
        if (!IsPostBack)
        {
            try
            {
                InitialBUS();
                LoadMailGroupLists();
                LoadMailConfigList();
                LoadEventList(); LoadSignatureList();
                // Khoi tao session for store contentSendEvent
                ContentSendEventBUS cseBus = new ContentSendEventBUS();
                Session["listContentSendEvent"] = cseBus.GetById(0);

                LoadContentList();
            }
            catch (Exception ex)
            {
                logs.Error(userLogin.Username + "-Create-Event - Page_Load", ex);
                pnError.Visible = true;
                lblError.Text = ex.Message;
            }

        }
    }
Exemplo n.º 41
0
    protected void Page_Load(object sender, EventArgs e)
    {
        userLogin = getUserLogin();
        if (!IsPostBack)
        {
            try
            {
                InitBUS();
                LoadSubGroup();
                //LoadCustomer();

            }
            catch (Exception)
            {

            }
        }
    }
Exemplo n.º 42
0
    //private UserLoginDTO getUserLogin()
    //{
    //    if (Session["us-login"] != null)
    //    {
    //        return (UserLoginDTO)Session["us-login"];
    //    }
    //    else Response.Redirect("~");//test confict
    //    return null;
    //}
    protected void lbtSubmit_Click(object sender, EventArgs e)
    {
        DataTable table = null;
        DataTable tableStatus = null;
        int clienID = 0;
        int status = 0;
        try
        {
            String user = txtUsername.Text;
            string en_pass = Common.GetMd5Hash(txtPassword.Text.Trim());
            ConnectionData.OpenMyConnection();
            DataTable tbResult = ulBus.GetByUsernameAndPass(user, en_pass);
            if (tbResult.Rows.Count > 0)
            {
                UserLoginDTO userLogin = new UserLoginDTO();
                userLogin.UserId = int.Parse(tbResult.Rows[0]["UserId"].ToString());
                userLogin.Username = tbResult.Rows[0]["Username"].ToString();
                userLogin.Password = tbResult.Rows[0]["Password"].ToString();
                userLogin.DepartmentId = int.Parse(tbResult.Rows[0]["DepartmentId"].ToString());
                userLogin.UserType = int.Parse(tbResult.Rows[0]["UserType"].ToString());
                if (userLogin.UserType == 3)
                {
                    table = ulBus.GetClientIdSub(userLogin.UserId);
                    clienID = int.Parse(table.Rows[0]["clientId"].ToString());

                    tableStatus = ulBus.GetClientId(clienID);
                    status = int.Parse(tableStatus.Rows[0]["Status"].ToString());
                }
                else if (userLogin.UserType == 0)
                {
                    status = 0;
                }
                else if (userLogin.UserType != 0 && userLogin.UserType != 3)
                {
                    tableStatus = ulBus.GetClientId(userLogin.UserId);
                    status = int.Parse(tableStatus.Rows[0]["Status"].ToString());
                }
                if (status == 0)
                {

                    try
                    {
                        userLogin.hasSendMail = int.Parse(tbResult.Rows[0]["hasSendMail"].ToString());
                    }
                    catch (Exception)
                    {
                        userLogin.hasSendMail = 0;
                    }
                    int hasCreatedCustomer = Common.countHasCreateMailByUserId(int.Parse(tbResult.Rows[0]["UserId"].ToString()));
                    userLogin.hasCreatedCustomer = hasCreatedCustomer;

                    // Tạo session user login
                    Session["us-login"] = userLogin;
                    Session["UserName"] = userLogin.Username;
                    Session["UserId"] = userLogin.UserId;
                    // Kiểm tra user này có thuộc phân quyền nâng cao hay không
                    DataTable tblRoleDetail = rdBus.GetByDepartmentIdAndRole(-1, userLogin.DepartmentId);
                    if (tblRoleDetail.Rows.Count > 0)
                    {
                        RoleDetailDTO rdDto = new RoleDetailDTO();
                        rdDto.roleId = int.Parse(tblRoleDetail.Rows[0]["roleId"].ToString());
                        rdDto.departmentId = int.Parse(tblRoleDetail.Rows[0]["departmentId"].ToString());
                        rdDto.limitSendMail = int.Parse(tblRoleDetail.Rows[0]["limitSendMail"].ToString());
                        rdDto.limitCreateCustomer = int.Parse(tblRoleDetail.Rows[0]["limitCreateCustomer"].ToString());
                        rdDto.toDate = DateTime.Parse(tblRoleDetail.Rows[0]["toDate"].ToString());
                        // Tạo session limit
                        Session["limitWithUser"] = rdDto;
                    }
                    logs_info.Info("user login: "******"ID"] = 25;
                    if (userLogin.UserType == 0)
                        Response.Redirect("clientregister.aspx", false);
                    else
                        Response.Redirect("mail-send.aspx", false);

                }
                else if (status == -1)
                {
                    pnError.Visible = true;
                    lblMessage.Text = "Tài khoản đăng nhập chưa kích hoạt.";
                    logs.Error("user not active: " + userLogin.Username);
                }
                else
                {
                    pnError.Visible = true;
                    lblMessage.Text = "Tài khoản đăng nhập đã bị khóa.";
                    logs.Error("user locked: " + userLogin.Username);
                }

            }
            else
            {
                pnError.Visible = true;
                lblMessage.Text = "Email hoặc mật khẩu không đúng.";
                logs.Error("user worng: " + txtUsername.Text);
            }
        }
        catch (ThreadAbortException ex)
        {
            pnError.Visible = true;
            lblMessage.Text = ex.Message;
            logs.Error("user login exception: " + txtUsername.Text, ex);
        }
        finally
        {
            //ConnectionData.CloseMyConnection();
        }
    }
Exemplo n.º 43
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string message = "";
        try
        {
            if (hdfId.Value == null || hdfId.Value == "")//them moi
            {
                message = checkInput();
            }
            else
            {
                message = checkPassword();
            }
            int status = 0;
            if (message == "")
            {

                ulBus = new UserLoginBUS();
                UserLoginDTO ulDto = new UserLoginDTO();
                ulDto.Username = txtUsername.Text;
                ulDto.Password = Common.GetMd5Hash(txtPassword.Text);
                ulDto.DepartmentId = int.Parse(this.dropTypeUser.SelectedItem.Value.ToString());
                DataTable dtLogin = ulBus.GetByUserType(ulDto.DepartmentId);
                ulDto.UserType =int.Parse(dtLogin.Rows[0]["UserType"].ToString());
                ulDto.Is_Block = this.chkBlock.Checked;
                ulDto.Deleted = 0;
                ConnectionData.OpenMyConnection();
                if (hdfId.Value == null || hdfId.Value == "")//them moi
                {
                    ulBus.tblUserLogin_insert(ulDto);
                    status = 1;
                }
                else
                {

                        ulDto.UserId = int.Parse(hdfId.Value);
                        ulBus.tblUserLogin_Update(ulDto);
                        status = 2;

                }

                ConnectionData.CloseMyConnection();
                pnSuccess.Visible = true;
                pnError.Visible = false;
                LoadData();
                if (status == 1)
                {
                    lblSuccess.Text = "Thêm thành công !";
                }
                else
                    if (status == 2)
                    {
                        lblSuccess.Text = "Bạn vừa cập nhật thành công chức năng !";
                        txtUsername.Enabled = true;
                    }

            }
            else
            {
                pnSuccess.Visible = false;
                pnError.Visible = true;
                lblError.Text = message;
            }

        }
        catch (Exception ex)
        {

            logs.Error(userLogin.Username + "-Client - btnSave_Click", ex);
            pnSuccess.Visible = false;
            pnError.Visible = true;
            lblError.Text = "Kiểm tra lại dữ liệu nhập vào !";
        }
    }
Exemplo n.º 44
0
    protected void Page_Load(object sender, EventArgs e)
    {
        userLogin = getUserLogin();
        if (!IsPostBack)
        {
            try
            {
                InitBUS();
                LoadData();

            }
            catch (Exception ex)
            {

                logs.Error(userLogin.Username + "-Client - LoadData", ex);
            }
        }
    }
Exemplo n.º 45
0
 public void tblSubClient_Update(UserLoginDTO dt)
 {
     ulDao.tblSubClient_Update(dt);
 }
Exemplo n.º 46
0
    public int Register(clientdto client, clientRegisterdto clientRegister, UserLoginDTO ulDto)
    {
        SqlTransaction tran = ConnectionData._MyConnection.BeginTransaction();
        try
        {
            string sql = "insert into tblClient (clientName,address,email,phone,status)" +
                "values(@clientName,@address,@email,@phone,@status) select @@identity";
            SqlCommand cmd = new SqlCommand(sql, ConnectionData._MyConnection);
            cmd.Transaction = tran;
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@clientName", SqlDbType.NVarChar).Value = client.clientName;
            cmd.Parameters.Add("@address", SqlDbType.NVarChar).Value = client.address;
            cmd.Parameters.Add("@email", SqlDbType.NVarChar).Value = client.email;
            cmd.Parameters.Add("@phone", SqlDbType.VarChar).Value = client.phone;
            cmd.Parameters.Add("@status", SqlDbType.Int).Value = -1;
            object id = cmd.ExecuteScalar();
            clientRegister.clientId = Convert.ToInt32(id);

            sql = @"set dateformat dmy INSERT INTO [tblClientRegister]
           ([clientId]
           ,[packageId]
           ,[limitId]
           ,[subAccontCount]
           ,[emailCount]
           ,[totalFee]
           ,[registerType]
           ,[packageTimeId]
           ,[from]
           ,[to]
           ,[lastRegisterFrom]
           ,[lastRegisterTo]
           ,[lastRegisterFee]
           ,[lastRegisterFeeRemain]
           ,[registerTime]
           ,[registerDate])
         VALUES
           (@clientId
           ,@packageId
           ,@limitId
           ,@subAccontCount
           ,@emailCount
           ,@totalFee
           ,0
           ,@packageTimeId
           ,@from
           ,@to
           ,null           ,null           ,0           ,0           ,getdate()           ,getdate()) select @@identity";
            cmd = new SqlCommand(sql, ConnectionData._MyConnection);
            cmd.Transaction = tran;
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@clientId", SqlDbType.Int).Value = clientRegister.clientId;
            cmd.Parameters.Add("@packageId", SqlDbType.Int).Value = clientRegister.packageId;
            cmd.Parameters.Add("@limitId", SqlDbType.Int).Value = clientRegister.limitId;
            cmd.Parameters.Add("@subAccontCount", SqlDbType.Int).Value = clientRegister.subAccontCount;
            cmd.Parameters.Add("@emailCount", SqlDbType.Int).Value = clientRegister.emailCount;
            cmd.Parameters.Add("@totalFee", SqlDbType.Float).Value = clientRegister.totalFee;
            cmd.Parameters.Add("@packageTimeId", SqlDbType.Int).Value = clientRegister.packageTimeId;
            cmd.Parameters.Add("@from", SqlDbType.VarChar, 12).Value = clientRegister.from.ToString("dd/MM/yyyy");
            cmd.Parameters.Add("@to", SqlDbType.VarChar, 12).Value = clientRegister.to.ToString("dd/MM/yyyy");
            object registerid = cmd.ExecuteScalar();

            sql = "select * from tblPackageFunction where packageid=" + clientRegister.packageId;
            cmd = new SqlCommand(sql, ConnectionData._MyConnection);
            cmd.Transaction = tran;
            cmd.CommandType = CommandType.Text;
            DataTable T = new DataTable();
            SqlDataAdapter data = new SqlDataAdapter(cmd);

            data.Fill(T);
            sql = "insert into tblClientFunction(registerId, clientId, functionId) values(@registerId, @clientId, @functionId)";
            if (T != null)
                foreach (DataRow r in T.Rows)
                {
                        cmd = new SqlCommand(sql, ConnectionData._MyConnection);
                        cmd.Transaction = tran;
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.Add("@functionId", SqlDbType.Int).Value = r["functionId"];
                        cmd.Parameters.Add("@clientId", SqlDbType.Int).Value = clientRegister.clientId;
                        cmd.Parameters.Add("@registerId", SqlDbType.Int).Value = registerid;
                        cmd.ExecuteNonQuery();
                }

            sql = "INSERT INTO tblUserLogin(Username, Password, UserType,Is_Block,DepartmentId) " +
                         "VALUES(@Email, @Password, @UserType,@Is_Block,@UserType) select @@identity";
            cmd = new SqlCommand(sql, ConnectionData._MyConnection);
            cmd.Transaction = tran;
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = ulDto.Email;
            cmd.Parameters.Add("@Password", SqlDbType.NVarChar).Value = ulDto.Password;
            cmd.Parameters.Add("@UserType", SqlDbType.Int).Value = ulDto.UserType;
            cmd.Parameters.Add("@Is_Block", SqlDbType.Bit).Value = ulDto.Is_Block;
            id = cmd.ExecuteScalar();

            sql = "set dateformat dmy update tblClient set userid = @userid, registerid=@registerid, activedate=getdate(), expiredate='" + clientRegister.to.ToString("dd/MM/yyyy") + "' where clientid=@clientid";
            cmd = new SqlCommand(sql, ConnectionData._MyConnection);
            cmd.Transaction = tran;
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@userid", SqlDbType.Int).Value = id;
            cmd.Parameters.Add("@clientid", SqlDbType.Int).Value = clientRegister.clientId;
            cmd.Parameters.Add("@registerid", SqlDbType.Int).Value = registerid;
            int i=cmd.ExecuteNonQuery();
            tran.Commit();
            tran.Dispose();
            return i;
        }
        catch
        {
            tran.Rollback();
        }
        return 0;
    }
Exemplo n.º 47
0
 public void tblSubClient_Update(UserLoginDTO dt)
 {
     string sql = "UPDATE tblSubClient SET " +
              "Is_Block = @Is_Block " +
             " WHERE subId = @subId";
     SqlCommand cmd = new SqlCommand(sql, ConnectionData._MyConnection);
     cmd.CommandType = CommandType.Text;
     cmd.Parameters.Add("@subId", SqlDbType.Int).Value = dt.SubId;
     cmd.Parameters.Add("@subEmail", SqlDbType.NVarChar).Value = dt.Email;
     cmd.Parameters.Add("@Is_Block", SqlDbType.Bit).Value = dt.Is_Block;
     cmd.ExecuteNonQuery();
     cmd.Dispose();
 }
Exemplo n.º 48
0
 protected void Page_Load(object sender, EventArgs e)
 {
     userLogin = getUserLogin();
     if (!IsPostBack)
     {
         LoadSubClient();
         LoadGroup();
     }
 }
Exemplo n.º 49
0
    protected void Page_Load(object sender, EventArgs e)
    {
        userLogin = getUserLogin();
        if (!IsPostBack)
        {
            try
            {
                package();
                LoadData();
                hdfId.Value = null;
            }
            catch (Exception)
            {

            }
        }
    }
Exemplo n.º 50
0
    protected void Page_Load(object sender, EventArgs e)
    {
        userLogin = getUserLogin();
        if (!IsPostBack)
        {
            try
            {
                srBUS = new SendRegisterBUS();
                loadDetailReport(true);
            }
            catch (Exception ex)
            {
                pnError.Visible = true;
                lblError.Text = ex.Message;
                logs.Error(userLogin.Username+"-mailSend-load",ex);
            }

        }
        srBUS = new SendRegisterBUS();
    }
Exemplo n.º 51
0
    public void tblSubClient_insert(UserLoginDTO dt)
    {
        string sql = "INSERT INTO tblSubClient(subName,subEmail,clientId, userId,Is_Block) " +
                     "VALUES(@subName,@subEmail, @clientId, @userId,@Is_Block)";
        SqlCommand cmd = new SqlCommand(sql, ConnectionData._MyConnection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.Add("@subName", SqlDbType.NVarChar).Value = dt.Username;
        cmd.Parameters.Add("@subEmail", SqlDbType.NVarChar).Value = dt.Email;
        cmd.Parameters.Add("@clientId", SqlDbType.Int).Value = dt.ClientID;
        cmd.Parameters.Add("@userId", SqlDbType.Int).Value = dt.UserId;
        cmd.Parameters.Add("@Is_Block", SqlDbType.Bit).Value = dt.Is_Block;
        cmd.ExecuteNonQuery();
        cmd.Dispose();

        //SqlCommand cmd = new SqlCommand();
        //cmd.CommandType = CommandType.StoredProcedure;
        //cmd.CommandText = "pro_add_tblsubclient";
        //cmd.Parameters.Add("@subName", SqlDbType.NVarChar).Value = dt.Username;
        //cmd.Parameters.Add("@subEmail", SqlDbType.NVarChar).Value = dt.Email;
        //cmd.Parameters.Add("@clientId", SqlDbType.Int).Value = dt.ClientID;
        //cmd.Parameters.Add("@userId", SqlDbType.Int).Value = dt.UserId;
        //cmd.Parameters.Add("@Is_Block", SqlDbType.Bit).Value = dt.Is_Block;
        //cmd.Parameters.Add("@subId", SqlDbType.Int).Direction = ParameterDirection.Output;
        //cmd.Connection = ConnectionData._MyConnection;
        //try
        //{
        //    ConnectionData._MyConnection.Open();
        //    cmd.ExecuteNonQuery();
        //    string subId = cmd.Parameters["@subId"].Value.ToString();

        //}
        //catch (Exception ex)
        //{
        //    throw ex;
        //}
        //finally
        //{
        //    ConnectionData._MyConnection.Close();
        //    ConnectionData._MyConnection.Dispose();
        //}
    }
Exemplo n.º 52
0
 public int Insert_client(clientdto client, clientRegisterdto clientRegister, UserLoginDTO ulDto)
 {
     return dangky.Register(client, clientRegister,  ulDto);
 }
Exemplo n.º 53
0
 public void tblUserLoginSubClient_insert(UserLoginDTO dt)
 {
     ulDao.tblUserLoginSubClient_insert(dt);
 }
Exemplo n.º 54
0
 public void tblUserLogin_insert(UserLoginDTO dt)
 {
     ulDao.tblUserLogin_insert(dt);
 }
Exemplo n.º 55
0
 protected void Page_Load(object sender, EventArgs e)
 {
     userLogin = getUserLogin();
     if (!IsPostBack)
     {
         try
         {
             InitBUS();
             LoadData();
             //  loadListDepartment();
             //  drlDepartment_SelectedIndexChanged(sender, e);
         }
         catch (Exception)
         {
         }
     }
 }
Exemplo n.º 56
0
 protected void Page_Load(object sender, EventArgs e)
 {
     userLogin = getUserLogin();
     if (!IsPostBack)
     {
         try
         {
             LoadMailGroupLists();
             LoadMailConfigLists();
             LoadMailContentList();
             LoadSignatureList();
             drlMailGroup_SelectedIndexChanged(sender, e);
         }
         catch (Exception ex)
         {
             pnError.Visible = true;
             lblError.Text = ex.Message;
         }
     }
 }
Exemplo n.º 57
0
 public void tblUserLogin_Update(UserLoginDTO dt)
 {
     ulDao.tblUserLogin_Update(dt);
 }
Exemplo n.º 58
0
    protected void Page_Load(object sender, EventArgs e)
    {
        userLogin = getUserLogin();
        if (!IsPostBack)
        {
            //LoadVerifyListByUserId();
            LoadVerifyList();

        }
    }
Exemplo n.º 59
0
 protected void Page_Load(object sender, EventArgs e)
 {
     userLogin = getUserLogin();
     if (!IsPostBack)
     {
         try
         {
             loadData();
             LoadEventReport();
             LoadContentList();
         }
         catch (Exception)
         {
         }
     }
 }
Exemplo n.º 60
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        DataTable table = null;
        string message = "";
        try
        {
            if (hdfId.Value == null || hdfId.Value == "")//them moi
            {
                message = checkInput();
            }
            else
            {
                message = checkPassword();
            }
            int status = 0;
            if (message == "")
            {

                ulBus = new UserLoginBUS();
                UserLoginDTO ulDto = new UserLoginDTO();
                ulDto.Username = txtUsername.Text;
                ulDto.Password = Common.GetMd5Hash(txtPassword.Text);
                ulDto.Email = txtEmail.Text;
                ulDto.Is_Block = this.chkBlock.Checked;
                ulDto.UserType = 2;
                //tai khoan con ID =3
                ulDto.UserId = 3;
                ConnectionData.OpenMyConnection();
                if (hdfId.Value == null || hdfId.Value == "")//them moi
                {

                    if (getUserLogin().DepartmentId == 3)
                    {
                        table = ulBus.GetClientIdSub(getUserLogin().UserId);
                    }
                    else
                    {
                        table = ulBus.GetClientId(getUserLogin().UserId);
                    }

                    int clienID = int.Parse(table.Rows[0]["clientId"].ToString());
                    ulDto.ClientID = clienID;

                    int statusclient = int.Parse(table.Rows[0]["Status"].ToString());

                    DataTable countSubClient = ulBus.GetCountSubClient(ulDto.ClientID);
                    int countSub = int.Parse(countSubClient.Rows[0]["numberSub"].ToString());

                    DataTable subAccount = ulBus.GetSubAccountCount(ulDto.ClientID);
                    int SubAccount = int.Parse(subAccount.Rows[0]["subAccontCount"].ToString());

                    DateTime NgayHetHan = Convert.ToDateTime(table.Rows[0]["expireDate"].ToString());
                    string todays = DateTime.Now.ToString("yyyy-MM-dd");
                    DateTime today = Convert.ToDateTime(todays);
                    DateTime expireDay = Convert.ToDateTime(NgayHetHan);
                    DataTable checkEmail = ulBus.GetEmailByUser(txtEmail.Text.Trim());
                    if (statusclient == 2 || expireDay < today)
                    {
                        status = 3;
                    }
                    else
                    {
                        if (countSub < SubAccount)
                        {
                            if (checkEmail.Rows.Count > 0)
                            {
                                status = 5;
                            }
                            else
                            {
                                ulBus.tblUserLoginSubClient_insert(ulDto);
                                //lay UserID
                                DataTable dt = ulBus.GetUserIDByUserName(txtEmail.Text);
                                int userID = int.Parse(dt.Rows[0]["UserId"].ToString());
                                ulDto.UserId = userID;
                                ulBus.tblSubClient_insert(ulDto);
                                status = 1;
                            }
                        }
                        else
                        {
                            status = 4;
                        }
                    }

                }
                else
                {

                    ulDto.SubId = int.Parse(hdfId.Value);
                    DataTable checkEmail = ulBus.GetEmailByUser(txtEmail.Text.Trim());
                    if (checkEmail.Rows.Count > 0)
                    {
                        status = 5;
                    }
                    else
                    {
                        ulBus.tblSubClient_Update(ulDto);
                        // DataTable table1 = ulBus.GetUserIdBySubID(ulDto.SubId);
                        // int userID = int.Parse(table1.Rows[0]["UserID"].ToString());
                        DataTable tablesub = ulBus.GetBySubId(ulDto.SubId);
                        string Username = tablesub.Rows[0]["subEmail"].ToString();
                        DataTable dtIsBlock = ulBus.GetIsBlockByUserId(Username);
                        bool Is_Block_check = chkBlock.Checked;
                        ulBus.tblUserLoginSub_Update(Username, Is_Block_check);
                        status = 2;
                    }

                }

                ConnectionData.CloseMyConnection();
                pnSuccess.Visible = true;
                pnError.Visible = false;
                LoadData();
                if (status == 5)
                {
                    pnSuccess.Visible = false;
                    pnError.Visible = true;
                    lblError.Text = "Email đã được sử dụng. Vui lòng chọn email khác !";
                    this.txtEmail.Focus();
                }
                if (status == 4)
                {
                    lblError.Text = "Tạo tài khoản con vượt quá giới hạn cho phép!";
                    pnSuccess.Visible = false;
                    pnError.Visible = true;
                }
                if (status == 3)
                {
                    lblError.Text = "Không cho phép tạo tài khoản con.Liên hệ quản trị!";
                    pnSuccess.Visible = false;
                    pnError.Visible = true;
                }
                if (status == 1)
                {
                    lblSuccess.Text = "Thêm thành công !";
                }
                else
                    if (status == 2)
                    {
                        lblSuccess.Text = "Bạn vừa cập nhật thành công chức năng !";
                        txtUsername.Enabled = true;
                    }

            }
            else
            {
                pnSuccess.Visible = false;
                pnError.Visible = true;
                lblError.Text = message;
            }

        }
        catch (Exception ex)
        {
            pnSuccess.Visible = false;
            pnError.Visible = true;
            lblError.Text = "Kiểm tra lại dữ liệu nhập vào !";
            logs.Error(userLogin.Username + "subClient-Save", ex);
        }
    }