Beispiel #1
0
        public async Task <IActionResult> Authenticate([FromBody] LoginFormDto userDto)
        {
            var user = await _userService.Authenticate(userDto.Email, userDto.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[] {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(Ok(new
            {
                Id = user.Id,
                FirstName = user.FirstName,
                LastName = user.LastName,
                ProfilePictureUrl = user.ProfilePicture?.Url ?? "/images/default_avatar.png",
                Token = tokenString
            }));
        }
        public IActionResult Update(string id, [FromBody] LoginFormDto loginFormDto)
        {
            var user = _mapper.Map <User>(loginFormDto);

            user.Id = id;

            try
            {
                _userService.Update(user, loginFormDto.Password);
                return(Ok());
            } catch (AppException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
Beispiel #3
0
        public IActionResult Login(LoginFormDto userForLoginDto)
        {
            var userFromRepo = repo.findUserByUsernameAndPassword(userForLoginDto.username, userForLoginDto.password); // repo.getUserByUserName

            if (userFromRepo == null)
            {
                Console.WriteLine("not found");
                return(Unauthorized());
            }
            // add id,name into token and generate
            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.ID.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.USER_NAME)
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8
                                               .GetBytes("DOASDNAONAODFADWONNACCAONOSNCOAOC"));
            var cred            = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = cred,
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            // done

            return(Ok(new
            {
                message = "Ok",
                data = new
                {
                    token = tokenHandler.WriteToken(token),
                }
            }));;
        }
        public IActionResult Login(LoginFormDto userForLoginDto)
        {
            Guid newId = Guid.NewGuid();

            Console.WriteLine(newId);

            //Thành - sunivy - begin
            //12/12/2020
            //isLoginPass = true sẽ login bằng pass
            if (userForLoginDto.isLoginPass)
            {
                //Login có kiểm tra LDAP
                if (userForLoginDto.isLdap)
                {
                    //Check LDAP
                    KeyValuePair <int, string> check = CheckLoginLDAP(userForLoginDto.username, userForLoginDto.password);

                    if (check.Key != 0)
                    {
                        return(Unauthorized());
                    }
                    else
                    {
                        //Update pass vào DB
                        if (!_userRepository.UpdatePasswordUser(userForLoginDto.username, userForLoginDto.password))
                        {
                            return(Unauthorized());
                        }
                    }
                }
            }
            //end

            var userFromRepo = _userRepository.FindUserByUsernameAndPassword(userForLoginDto.username, userForLoginDto.password, userForLoginDto.isLoginPass);

            // repo.getUserByUserName

            if (userFromRepo == null)
            {
                Console.WriteLine("not found");
                return(Unauthorized());
            }
            Console.WriteLine(userFromRepo.REGION_ID_C.ToString());
            // add id,name into token and generate

            var endpoint = _userRepository.GetEndPonitUser(userFromRepo.ID.ToString()).Result;

            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.ID.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.USER_NAME),
                new Claim(ClaimTypes.StateOrProvince, userFromRepo.REGION_ID_C.ToString()),
                new Claim("Name", Utils.Base64Encode(userForLoginDto.username + "_" + userForLoginDto.password + "TeleSales")),
                new Claim("IsAdmin", userFromRepo.IS_ADMIN.ToString()),
                new Claim("Role", (endpoint != null ? string.Join(",", endpoint) : "")),  // lưu quyền vào token
            };

            var key             = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetValue <String>("AppIdentitySettings:SecurityKey")));
            var cred            = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddSeconds(_config.GetValue <int>("AppIdentitySettings:TokenExpireTime")),
                SigningCredentials = cred,
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            // done

            //lưu token vào cached
            _ = _userRepository.InsertUpdateToken(userFromRepo.ID.ToString(), tokenHandler.WriteToken(token)).Result;

            Dictionary <string, string> cachedToken = (Dictionary <string, string>)_cache.Get("Token");

            if (cachedToken == null)
            {
                if (setCached())
                {
                    cachedToken = (Dictionary <string, string>)_cache.Get("Token");
                }
                else
                {
                    cachedToken = new Dictionary <string, string>();
                }
            }
            if (cachedToken.ContainsKey(userFromRepo.ID.ToString()))
            {
                cachedToken[userFromRepo.ID.ToString()] = tokenHandler.WriteToken(token);
            }
            else
            {
                cachedToken.Add(userFromRepo.ID.ToString(), tokenHandler.WriteToken(token));
            }
            _cache.Set("Token", cachedToken);
            // done

            return(Ok(new
            {
                message = "Ok",
                data = new
                {
                    token = tokenHandler.WriteToken(token),
                },
                code = 200
            }));;
        }