when iam trying to fetch the records with this query findByUserIdAndPassword(userId, password); using MongoRepository
but iam getting null all the time any suggestions?
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginValidation(#RequestParam String userId,#RequestParam String password) {
System.out.println("un"+userId);
System.out.println("password"+password);
Optional<TicketUserDto> ticketuser=ticketUserDao.findByUserIdAndPassword(userId, password);
}
Image of code:
Related
I am consuming Gitlab's API, for some endpoints you have two variable e.g https://gitlab.example.com/api/v4/projects/:id/members/:user_id
projectId and userId are variables I want to add to the url.
I am trying to use more than one uriVariables in the restTemplate exchange().
I have been doing this when i have one variable
#Override
public User getUser(String userId){
ResponseEntity<User> respEntity = restTemplate.exchange(userURL, HttpMethod.GET,getHeader(), User.class, userId );
User user = respEntity.getBody();
return user;
}
userURL=https://gitlab.com/api/v4/users/{userid}
Now doing this for two variables
#Override
public User getUserFromProject(String userId, String projectId){
ResponseEntity<User> respEntity = restTemplate.exchange(URL, HttpMethod.GET,getHeader(), User.class, projectId,userId );
User user = respEntity.getBody();
return user;
}
URL=https://gitlab.com/api/v4/projects/{projectId}/members/{userId}
Throws this Error
org.springframework.web.client.HttpClientErrorException$BadRequest:
400 Bad Request at
org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:79)
~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
Thanks.
NewAccountDAOImpl
it is getting particular record id, username and password
according to that it should retrieve the records
#Transactional
#Modifying
public boolean checkLogin(int id, String username, String password){
System.out.println("In Check login"+ id);
System.out.println("In Check login"+ username);
System.out.println("In Check login"+ password);
Session session = sessionFactory.openSession();
boolean userFound = false;
//Query using Hibernate Query Language
//tring SQL_QUERY =" from NewAccount as n where n.id=? and n.username=? and password=?";
String SQL_Query=" from NewAccount where id=:id";
Query query = session.createQuery(SQL_Query);
query.setParameter("id",id).uniqueResult();
//query.setParameter(0,id);
//query.setParameter(1,username);
//query.setParameter(2,password);
List list = query.list();
if ((list != null) && (list.size() > 0)) {
userFound= true;
}
session.close();
return userFound;
}
controller class
getting information from bankbalance form like id,username, password.
i added them to checkLogin method parameters it returns boolean valeue
#RequestMapping(value = "/balanceSave", method = RequestMethod.GET)
public ModelAndView saveBk(ModelAndView model, HttpServletRequest req,
HttpServletResponse res, #ModelAttribute NewAccount newaccount) {
int id=Integer.parseInt(req.getParameter("id"));
String username=req.getParameter("username");
String password=req.getParameter("password");
boolean userExists = newaccountService.checkLogin( id, username, password);
if(userExists ){
model.addObject("newaccount", newaccount);
return new ModelAndView("redirect:viewBalanceMoney");
}
return new ModelAndView("BalanceForm");
}
here i am sending list data to a jsp page viewbalanc
// view newaccount balance money
#RequestMapping(value = "/viewBalanceMoney", method = RequestMethod.GET)
public ModelAndView viewBalanceMoney(ModelAndView model) {
// public NewAccount getNewAccount(int newaccountid);
List<NewAccount> listnewaccount = newaccountService.getAllNewAccounts();
model.addObject("listnewaccount", listnewaccount);
model.setViewName("viewBalanc");
return model;
}
image1 shows balance form
it send input to the controller method
image 2 shows retrieved records, but i need particular id record information
image2
enter image description here
You can do this using #PathVariable and invoke the method for that accountId.
#RequestMapping(value = "/viewBalanceMoney/{newAccountId}", method = RequestMethod.GET)
public ModelAndView viewBalanceMoney(#PathVariable("newAccountId") Integer newaccountid,
ModelAndView model) {
//write code for fetching data for newaccountid
}
I am working on a login system - and was using previously get methods. When I run the application the ajax request seems correct - but the server side parameters coming in are null?
old code...
-- server side
#SuppressWarnings("unchecked")
#RequestMapping(value = "/login", method = RequestMethod.GET)
#CrossOrigin(origins = {"*"})
public ResponseEntity<?> login(
#RequestParam(value="email", required=false, defaultValue="email") String email,
#RequestParam(value="password", required=false, defaultValue="password") String password,
HttpServletRequest request
) throws Exception {
-- front side
export function fetchAuthentication(data) {
let url = 'http://localhost:8080/login?email=ruperttest2#hotmail.com&password=1234';
return function (dispatch) {
axios.get(url)
.then(function (response) {
dispatch(authSuccess(response));
})
.catch(function (error) {
dispatch(authFail(error));
});
}
}
new code..
-- server side
#SuppressWarnings("unchecked")
#RequestMapping(value = "/login", method = RequestMethod.POST)
#CrossOrigin(origins = {"*"})
public ResponseEntity<?> login(
#PathVariable(value="email", required=false) String email,
#PathVariable(value="password", required=false) String password,
HttpServletRequest request
) throws Exception {
System.out.println("email email>>>"+email);
-- front side
export function fetchAuthentication(data) {
let url = 'http://localhost:8080/login';
return function (dispatch) {
axios.post(url, data)
.then(function (response) {
if(response.status === "success"){
dispatch(authSuccess(response));
}
else{
// fail - user not found for example
dispatch(authFail(response));
}
})
.catch(function (error) {
dispatch(authFail(error));
});
}
}
You can make the input parameters required=true just to make sure you are doing fine in client side.
So a have a blueprint code of a web app which allows different accounts with logins to upload simple files. However, there are security flaws that allow non-admin accounts to enter database configurations and direct object referencing (download files of other accounts by URL tampering). I was recommended a solution whereby I check if the owner of the uploaded file is the same one trying to download it. But doing that in a spring #controller posed a few problems. If you look at my get statement to get a specific file, you see that I got the file object and the account object. Then I just check if the name is the same of file owner. But how do I "return" something in a controller while in an "if" statement?
#Controller
public class FileController {
#Autowired
private FileRepository fileRepository;
#Autowired
private AccountRepository accountRepository;
#RequestMapping(value = "/files", method = RequestMethod.GET)
public String list(Authentication authentication, Model model) {
model.addAttribute("files", accountRepository.findByUsername(authentication.getName()).getFileObjects());
return "files";
}
#RequestMapping(value = "/files/{id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> viewFile(#PathVariable Long id) {
//1. get object or name account name
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();
//2. check if the file account is of the same name
FileObject fo = fileRepository.findOne(id);
if((fo.getAccount().getUsername()).equals(currentPrincipalName)) {
System.out.println("WHAT AM I SUPPOSED TO DO!?");
}
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType(fo.getContentType()));
headers.add("Content-Disposition", "attachment; filename=" + fo.getName());
headers.setContentLength(fo.getContentLength());
return new ResponseEntity<>(fo.getContent(), headers, HttpStatus.CREATED);
}
#RequestMapping(value = "/files", method = RequestMethod.POST)
public String addFile(Authentication authentication, #RequestParam("file") MultipartFile file) throws IOException {
Account account = accountRepository.findByUsername(authentication.getName());
FileObject fileObject = new FileObject();
fileObject.setContentType(file.getContentType());
fileObject.setContent(file.getBytes());
fileObject.setName(file.getOriginalFilename());
fileObject.setContentLength(file.getSize());
fileObject.setAccount(account);
fileRepository.save(fileObject);
return "redirect:/files";
}
#RequestMapping(value = "/files/{id}", method = RequestMethod.DELETE)
public String delete(#PathVariable Long id) {
fileRepository.delete(id);
return "redirect:/files";
}
}
I'm very new to Mockito and Junit. I'm working on creating test case for forgot password workflow. Below is the code for controller and test. Could anyone tell me how should I test on bindingresult?
#RequestMapping(value = "/user/public/forgotPassword", method = RequestMethod.POST)
public ModelAndView sendforgetPasswordLink(#ModelAttribute ForgetPasswordBean forgetPasswordBean,BindingResult result, HttpSession session) {
BreadCrumbBuilder.addLinktoBreadCrumb(session, new Link(Constants.FORGET_PASSWORD_TITLE, "/user/public/forgotPassword", Constants.GROUP_USER, 0));
Map<String, String> breadCrumbs = HomePageController.setupInitialBreadCrumbs(session);
breadCrumbs.put(Constants.FORGET_PASSWORD_TITLE, "/user/public/forgotPassword");
session.setAttribute(SessionAttributes.BREAD_CRUMBS,breadCrumbs);
ModelAndView mav = new ModelAndView();
mav.addObject("displayTitle", Constants.FORGET_PASSWORD_TITLE);
PublicUser user = publicUserService.findPublicUserByEmail(forgetPasswordBean.getEmail().toLowerCase());
if(user == null) {
result.reject("email", "An account does not exist for this email.");
mav.setViewName("publicuser/forgetPassword.jsp");
return mav;
}
String randomId = java.util.UUID.randomUUID().toString();
user.setTempId(randomId);
mailService.sendForgetPasswordLink(user);
publicUserService.savePublicUser(user);
String msg = "Password reset instructions have been sent to your email.";
mav.addObject("msg", msg);
mav.setViewName("message.jsp");
return mav;
}
This is test I created so far
#Test
public void TestForgetPasswordForNoUserFound() throws Exception {
final String input_email = "abc#test.com";
ForgetPasswordBean forgetPasswordBean = new ForgetPasswordBean();
forgetPasswordBean.setEmail(input_email);
PublicUser daoUser = new PublicUser();
daoUser.setEmail(input_email);
when(mockPublicUserService.findPublicUserByEmail(input_email)).thenReturn(null);
when(mockBindingResult.hasErrors()).thenReturn(true);
final ModelAndView modelAndView = controller.sendforgetPasswordLink(forgetPasswordBean, mockBindingResult, mockHttpSession);
ModelMap modelMap = modelAndView.getModelMap();
assertEquals("An account does not exist for this email.", modelMap.get(mockBindingResult));
assertEquals("publicuser/forgetPassword.jsp", modelAndView.getViewName());
assertModelAttributeValue(modelAndView, "displayTitle", Constants.FORGET_PASSWORD_TITLE);
}
What you can do is verify behavior of your BindingResult by checking that the reject method was called.
Basically instead of
assertEquals("An account does not exist for this email.", modelMap.get(mockBindingResult));
You can do the following
Mockito.verify(mockBindingResult).reject("email", "An account does not exist for this email.");
And that way you can verify that the method was called.