public static AdminLoginDto GetAdminDetails(AdminLoginDto admin)
        {
            AdminLoginDal adminLoginDal = new AdminLoginDal();
            AdminLoginDto adminDetails  = adminLoginDal.GetAdminLogin(admin);

            return(adminDetails);
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> AdminLogin(AdminLoginDto adminLoginDto)
        {
            var adminFromRepo = await _authRepo.AdminLogin(adminLoginDto.Email.ToLower(), adminLoginDto.Password);

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

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

            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),
                username = adminFromRepo.FirstName,
                role = adminFromRepo.Role
            }));
        }
Ejemplo n.º 3
0
        public ActionResult Index(AdminLoginModel adminLoginModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(adminLoginModel));
            }
            AdminLoginDto admin = new AdminLoginDto()
            {
                UserName = adminLoginModel.UserName, Password = adminLoginModel.Password
            };

            admin = AdminAuthenticationRepository.GetAdminDetails(admin);
            if (admin.AdminId > 0)
            {
                FormsAuthentication.SetAuthCookie(adminLoginModel.UserName, false);
                var    authTicket      = new FormsAuthenticationTicket(1, admin.UserName, DateTime.Now, DateTime.Now.AddMinutes(20), false, admin.UserRole);
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                var    authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                HttpContext.Response.Cookies.Add(authCookie);
                TempData["AdminDetails"] = admin;
                TempData.Keep();
                Session["AdminId"] = admin.AdminId;
                return(RedirectToAction("DashBoard", "Admin"));
            }

            else
            {
                ViewBag.LoginError = "Invalid Login Attempt";
                return(View());
            }
        }
Ejemplo n.º 4
0
        public async Task <ResponseModel> AdminLogin(AdminLoginDto dto)
        {
            if (!this.DbContext.TAccount.Where(a => a.Name == dto.Model.UserName).Select(a => new { a.Id }).Any())
            {
                dto.Result.ResultCode = (int)AccountResultCode.UserNotExist;
                dto.Result.Message    = "用户不存在";
                return(dto.Result);
            }

            //查询管理员账号信息
            var accounts = this.DbContext.TAccount.Where(a => a.Type == AccountType.Admin)
                           .Where(a => a.Name == dto.Model.UserName)
                           .Join(this.DbContext.TAdmin, m => m.Id, f => f.AccountId, (m, f) =>
                                 new
            {
                m.Id,
                m.Password,
                m.Name,
                m.Type,
                f.JobNumber,
            }
                                 );

            var account = await accounts.FirstOrDefaultAsync();

            if (!dto.Model.Password.Equals(account.Password))
            {
                dto.Result.ResultCode = (int)AccountResultCode.PasswordError;
                dto.Result.Message    = "密码错误";
                return(dto.Result);
            }

            //更新管理最后一次登陆IP与时间
            var admin = await this.DbContext.TAdmin.FindAsync(account.Id);

            admin.LastLoginIp   = dto.LoginIP;
            admin.LastLoginTime = DateTime.UtcNow;
            admin.SetUpdater(admin.AccountId);
            this.DbContext.TAdmin.Update(admin);

            //写登陆日志
            var loginLog = new TAdminLoginLog
            {
                AccountId = admin.AccountId,
                LoginIp   = dto.LoginIP,
            };

            loginLog.SetCreator(admin.AccountId);
            loginLog.SetUpdater(admin.AccountId);
            await this.DbContext.AddOneAsync(loginLog);

            if (await this.DbContext.SaveChangesAsync() <= 0)
            {
                return(dto.Result);
            }

            dto.Model.UserId      = account.Id;
            dto.Result.ResultCode = (int)ResultCode.Successful;
            return(dto.Result);
        }
Ejemplo n.º 5
0
        private async Task <Admin> AuthenticateUserAsync(AdminLoginDto adminLogin)
        {
            var user = await _adminRepository
                       .GetAsync(a => a.Email == adminLogin.Email && a.Password == adminLogin.Password);

            if (user != null)
            {
                return(user);
            }

            return(null);
        }
        public async Task <IActionResult> Login([FromBody] AdminLoginDto adminLogin)
        {
            var response = await _accountService.Login(adminLogin);

            if (response != null)
            {
                SetRefreshTokenCookie(response.RefreshToken);
                return(Ok(response));
            }

            return(Unauthorized());
        }
Ejemplo n.º 7
0
        public JsonResult Login(AdminLoginDto dto, string returnUrl, bool remember = false)
        {
            var result = _adminLoginService.Login(dto, out var adminUser);

            if (!result.Success)
            {
                return(ToJsonResult(result));
            }

            UserAuth.SignInAdmin(adminUser.Id, adminUser.Name, adminUser.Email, remember);
            return(ToJsonResult(
                       new Result().SetRedirect(string.IsNullOrEmpty(returnUrl) ? Url.Action("Index", "Home") : returnUrl)));
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> Login([FromBody] AdminDto adminDto)
        {
            Admin admin = await _service.LoginAsync(adminDto);

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

            AdminLoginDto adminLoginDto = _mapper.Map <AdminLoginDto>(admin);
            string        tokenString   = _service.BuildToken(adminLoginDto);

            return(new OkObjectResult(tokenString));
        }
Ejemplo n.º 9
0
        public ActionResult Login(AdminLoginDto _model)
        {
            var _password = FormsAuthentication.HashPasswordForStoringInConfigFile(_model.Password, "MD5");

            if (Services.Login.IsLogin(_model.UserName, _password))
            {
                FormsAuthentication.SetAuthCookie(_model.UserName, true);
                return(Redirect("/Admin/Anasayfa"));
            }
            else
            {
                ViewBag.Error = false;
            }

            return(View());
        }
Ejemplo n.º 10
0
        public async Task <AuthenticateResponseDto> Login(AdminLoginDto adminLogin)
        {
            var user = await AuthenticateUserAsync(adminLogin);

            if (user != null)
            {
                var jwtToken     = GenerateJSONWebToken(user);
                var refreshToken = GenerateRefreshToken(user);
                user.RefreshTokens.Add(refreshToken);
                await _adminRepository.UpdateAsync(user);

                return(new AuthenticateResponseDto(user, jwtToken, refreshToken.Token));
            }

            return(null);
        }
Ejemplo n.º 11
0
 public ActionResult Index(AdminLoginDto adminDto)
 {
     if (authService.AdminLogin(adminDto))
     {
         //yönlendrime işlemleri
         FormsAuthentication.SetAuthCookie(adminDto.AdminUsername, false);
         Session["AdminUsername"] = adminDto.AdminUsername;
         return(RedirectToAction("Index", "Heading"));
     }
     else
     {
         //Hata Mesajı döndür
         ViewData["ErrorMessage"] = "Kullanıcı Adı veya Parola Yanlış!";
         return(View());
     }
 }
Ejemplo n.º 12
0
 public bool AdminLogin(AdminLoginDto adminDto)
 {
     using (var crypto = new System.Security.Cryptography.HMACSHA512())
     {
         var userNameHash = crypto.ComputeHash(Encoding.UTF8.GetBytes(adminDto.AdminUsername));
         var user         = _adminService.GetList();
         foreach (var item in user)
         {
             if (HashingHelper.AdminVerifyPasswordHash(adminDto.AdminUsername, adminDto.AdminPassword, item.AdminUserName, item.AdminPasswordHash, item.AdminPasswordSalt))
             {
                 return(true);
             }
         }
         return(false);
     }
 }
Ejemplo n.º 13
0
        // POST api/admins/token
        public IActionResult Login(AdminLoginDto LoginInfo)
        {
            //Model validation
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var token = adminManager.GetToken(LoginInfo);
                return(Ok(token));
            }
            catch (CustomDbException e)
            {
                return(BadRequest(e.Message));
            }
        }
Ejemplo n.º 14
0
        public string BuildToken(AdminLoginDto adminLoginDto)
        {
            Claim[] claims = new Claim[] {
                new Claim(ClaimTypes.NameIdentifier, adminLoginDto.AdminId.ToString()),
                new Claim(ClaimTypes.Name, adminLoginDto.Username)
            };

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                _config["Jwt:Issuer"],
                _config["Jwt:Issuer"],
                claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Ejemplo n.º 15
0
        public Result Login(AdminLoginDto dto, out AdminUser adminUser)
        {
            adminUser = null;

            var validator = new AdminLoginValidator();
            var result    = validator.ValidateResult(dto);

            if (!result.Success)
            {
                return(result);
            }

            adminUser = _adminUserRepository.AsNoTracking
                        .FirstOrDefault(w => w.IsActive && w.Email == dto.Email);

            return(adminUser == null?
                   SendFailedLoginResponse() :
                       VerifyPassword(dto.Password, adminUser));
        }
Ejemplo n.º 16
0
        public string GetToken(AdminLoginDto loginInfo)
        {
            var adminUser = repo.FindUser(loginInfo.UserName);

            //username existed or not
            if (adminUser == null)
            {
                throw new CustomDbException("UserName not existed.");
            }

            //validate password
            if (!new HashHelper(configuration)
                .ValidateHash(loginInfo.Password, adminUser.Password))
            {
                throw new CustomDbException("Wrong password.");
            }

            //build token
            return(BuildToken(adminUser));
        }
Ejemplo n.º 17
0
        public IActionResult AdminLogin([FromBody] AdminLoginDto loginDto)
        {
            //User Authentication
            if (string.IsNullOrWhiteSpace(loginDto.Username) || string.IsNullOrWhiteSpace(loginDto.Password))
            {
                return(BadRequest("Email or Password can not be empty"));
            }

            //因为Admin用户只有一个,也不提供注册功能,想想还是不用存数据库了
            var username = configuration["AdminUser:UserName"];
            var password = configuration["AdminUser:Password"];

            if (!username.Equals(loginDto.Username) || !password.Equals(loginDto.Password))
            {
                return(Unauthorized());
            }

            //比对通过即可发Token。
            var token = Jwt.GenerateJWT(configuration, username, "Admin");

            return(Ok(token));
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> AdminLogin([FromBody] AdminLoginDto loginCreds)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var result = await _repo.AdminLogin(loginCreds.Name, loginCreds.Password);

            if (result.IsSucces)
            {
                var returnDto = new AdminReturnDto()
                {
                    Credentials = result.Content,
                    Token       = result.Message
                };

                return(Ok(returnDto));
            }

            return(Unauthorized(loginCreds));
        }
Ejemplo n.º 19
0
        public async Task <AdminLoginResultDto> AdminLogin(AdminLoginDto adminLoginDto)
        {
            // 判断是否为空
            adminLoginDto.ISNullOrEmpty();
            var result = await _context
                         .GetFirstOrDefault(a =>
                                            a.AdminName.Equals(adminLoginDto.AdminName) &&
                                            a.AdminPwd.Equals(adminLoginDto.AdminPwd));

            if (result != null)
            {
                return new AdminLoginResultDto()
                       {
                           AdminId = result.Id, ResultInfo = "Bearer " + JwtService.GetToken(adminLoginDto.AdminName)
                       }
            }
            ;
            else
            {
                // 账号或密码错误
                throw new Exception("Incorrect username or password.");
            }
        }
        public AdminLoginDto GetAdminLogin(AdminLoginDto adminData)
        {
            AdminLoginDto adminLoginDto = new AdminLoginDto();
            SqlCommand    cmd           = new SqlCommand("GetAdminDetails", con);

            cmd.Parameters.AddWithValue("@UserName", adminData.UserName);
            cmd.Parameters.AddWithValue("@Password", adminData.Password);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                adminLoginDto.AdminId  = Convert.ToInt32(dr["AdminId"]);
                adminLoginDto.Name     = Convert.ToString(dr["Name"]);
                adminLoginDto.EmailId  = Convert.ToString(dr["EmailId"]);
                adminLoginDto.ProfPic  = Convert.ToString(dr["ProfPic"]);
                adminLoginDto.UserName = Convert.ToString(dr["UserName"]);
                adminLoginDto.Password = Convert.ToString(dr["Password"]);
                adminLoginDto.UserRole = Convert.ToString(dr["UserRole"]);
            }
            return(adminLoginDto);
        }
Ejemplo n.º 21
0
        public async Task <IActionResult> LogIn(AdminLoginDto adminLoginDto)
        {
            var adminInfo = await _adminService.Get(1);

            var admin = adminInfo.Data.Admin;

            using var md5 = MD5.Create();
            var result1   = md5.ComputeHash(Encoding.ASCII.GetBytes(adminLoginDto.Password));
            var strResult = BitConverter.ToString(result1);

            if (admin.Email == adminLoginDto.Email && admin.PasswordHash == strResult.Replace("-", ""))
            {
                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, adminLoginDto.Email)
                };
                var             identity  = new ClaimsIdentity(claims, "login");
                ClaimsPrincipal principal = new ClaimsPrincipal(identity);
                await HttpContext.SignInAsync(principal);

                return(RedirectToAction("Index", "Home", new { area = "Admin" }));
            }
            return(View(adminLoginDto));
        }
        public object KingLionSecLogin([FromBody] AdminLoginDto data)
        {
            bool isLoginSuccess = Authentication.AuthenticateAdmin(data.UserID, data.Password);

            return(new { LoginSuccess = isLoginSuccess });
        }
Ejemplo n.º 23
0
 public ActionResult Index(AdminLoginDto loginDto)
 {
     authService.AdminRegister(loginDto.AdminName, loginDto.AdminUsername, loginDto.AdminPassword, loginDto.AdminRoleId);
     return(RedirectToAction("Index", "Login"));
 }