Encryption method for cuba platform - java

Cuba has its own backend system to add users.
Now I need to write a user registration in the front-end.
The Cuba version I am using is 6.9
I know that this version of encryption is SHA1 : https://doc.cuba-platform.com/manual-6.9/login.html
Now my question is : I don't know how to set the encrypted password to the database.
I create an entity through the Metadata
User user = metadata.create(User.class);
user.setPassword(passWord);

I'm not sure that's the best option but I used the following code:
#Inject
protected PasswordEncryption passwordEncryption;
...
user.setPassword(passwordEncryption.getPasswordHash(user.getId(), password));

I think you just need to create html file with this code:
<div class="span6">
<h3>Login</h3>
<div th:if="${(param.error != null)}">
<p>Invalid username / password</p>
</div>
<form id="f" name="f" method="POST" action="login">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<div>
<div>
<label style="width: 80px" for="login">Login</label>
<input type="text" id="login" name="login" value=""/>
</div>
<div>
<label style="width: 80px" for="password">Password</label>
<input type="password" id="password" name="password" value=""/>
</div>
</div>
<button type="submit">Login</button>
</form>
</div>
and then Request it from Controller:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Model model) {
if (PortalSessionProvider.getUserSession().isAuthenticated()) {
LoadContext l = new LoadContext(User.class);
l.setQueryString("select u from sec$User u");
model.addAttribute("users", dataService.loadList(l));
}
return "index";
}

Related

SpringBoot/SpringSecurity logged in user can't update their details, no error being got but update not happening in database

I am trying to allow currently logged in user of my spring application update their current details but it is not persisting to the database, I am getting no errors and have tried to debug but have gotten no success.. please take a look.
Service class:
#Transactional
public User updateAccount(User userInForm){
System.out.println("Fetching user with id: " + userInForm.getId());
Optional<User> optionalUser = repo.findById(userInForm.getId());
if(!optionalUser.isPresent()){
System.out.println("User not found.");
return null;
}
User userInDB = optionalUser.get();
System.out.println("User fetched: " + userInDB);
userInDB.setFirstName(userInForm.getFirstName());
userInDB.setLastName(userInForm.getLastName());
System.out.println("Saving updated user: " + userInDB);
User savedUser = repo.save(userInDB);
System.out.println("User saved: " + savedUser);
return savedUser;
}
Controller class:
#PostMapping("/myAccount/update")
public String updateAccount(User user, RedirectAttributes redirectAttributes, Principal principal){
System.out.println("Updating user details...");
user = repo.findByEmail(principal.getName());
User updatedUser = service.updateAccount(user);
if (updatedUser == null) {
System.out.println("Error updating user details.");
} else {
redirectAttributes.addFlashAttribute("message", "Details Updated!");
return "redirect:/myAccount";
}
return "redirect:/myAccount";
}
Front end:
<h1 style="color:green">Welcome <b>[[${#request.userPrincipal.principal.fullName}]]</b></h1>
<h2 style="color:green">My Details</h2>
<div th:if="${message}" class ="alert alert-success text-center">
[[${message}]]
</div>
<form th:action="#{/myAccount/update}" th:object="${user}"
method="post" style="max-width: 600px; margin: 0 auto;">
<div class="m-3">
<div class="form-group row">
<label class="col-4 col-form-label">E-mail: </label>
<div class="col-8">
<input type="email" th:field="*{email}" class="form-control" readonly="readonly" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Password: </label>
<div class="col-8">
<input type="password" th:field="*{password}" placeholder="Leave blank if you don't want to change!" class="form-control"
minlength="6" maxlength="10"/>
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">First Name: </label>
<div class="col-8">
<input type="text" th:field="*{firstName}" class="form-control"
required minlength="2" maxlength="20"/>
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Last Name: </label>
<div class="col-8">
<input type="text" th:field="*{lastName}" class="form-control"
required minlength="2" maxlength="20" />
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Update Details</button>
</div>
</div>
</form>
Printed statements in console:
Updating user details...
Fetching user with id: 1
User fetched: com.example.Model.User#330603d0
Saving updated user: com.example.Model.User#330603d0
User saved: com.example.Model.User#330603d0
You are reassigning the user object received from the request to some other value. Check the below lines from the controller method
user = repo.findByEmail(principal.getName()); // this line reassigning the user object from the request to that of the one in database.
User updatedUser = service.updateAccount(user);
Because of this, user details are getting updated but with the existing data.

How to use getParts in java to get only image parts?

I'm trying to upload a file to cloudinary. I'm stucked at how to only get parts of image from the form. It keeps on throwing exception: Invalid image file. If I remove all text inputs in the form, the uploading is successful. I guess that happens because the form also has text inside. Please help me solve this. I'm really grateful for your support.
Here is my code:
Form.jsp:
<form role="form" action="<c:url value="/admin/product/update"/>" method="post" enctype="multipart/form-data">
<input name="id" value="${product.id}" hidden="">
<div class="form-group">
<label>Name:</label> <input class="form-control" value="${product.name}" name="name" />
</div>
<div class="form-group">
<label>Price:</label> <input class="form-control" value="${product.price}" type="number" name="price" />
</div>
<div class="form-group">
<label>Quantity:</label> <input class="form-control" value="${product.quantity}" type="number" name="quantity" />
</div>
<div class="form-group">
<label>Image:</label> <input class="form-control" value="${product.image}" name="image" />
</div>
<div class="form-group">
<label>Description </label> <br>
<textarea rows="4" cols="50" name="description" value="${product.description}" ></textarea>
</div>
<div class="form-group">
<label>Category</label>
<div class="checkbox">
<select name="catid">
<c:forEach items="${categorylist}" var="c">
<option value="${c.id}">${c.name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label>image</label> <input type="file" name="image" value="${product.image }" />
</div>
Servlet.java
BeanUtils.populate(product, request.getParameterMap());
//if (catid != product.getCategory().getId()) {
// Category category = new Category();
category = dao2.getCategoryByID(catid);
product.setCategory(category);
Map result = null;
Collection<Part> fileParts = request.getParts();
for (Part part : fileParts) {
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
String url = String.valueOf(result.get("url"));
product.setImage(url);
if (result == null) {
throw new RuntimeException("Loi upload");
}
}
dao.update(product);
The Cloudinary upload method supports uploading media files from the sources like a local path, a remote URL, a private storage URL (S3 or Google Cloud storage), a base64 data URI, or an FTP URL.
Based on your code, it seems that you are only supplying the filename of the image.
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
You would need to update the code to input the local path of the image.

Update operation is not performing -Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]

I'm trying to develop an application in spring boot + thymeleaf, and I'm able to retrieve the logged in user details in the profile tab from the MySQL database, but when I try to change one or two field details (update) and hit the update button it is showing me an error message - Fri Sep 04 20:39:47 IST 2020
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'POST' not supported
see my controller code (I'm using #RestController annotated on top of the class)-
#RequestMapping(value = "/profile", method = RequestMethod.PUT)
public ModelAndView updateProfile(#ModelAttribute Customer customer, HttpSession session) {
ModelAndView model = new ModelAndView();
Customer exist = cRepo.findByCustEmail(customer.getCustEmail());
if(exist != null) {
if(exist.getCustEmail().equals(session.getAttribute("emailsession"))) {
cRepo.save(customer);
model.addObject("msg", "User Details has been successfully updated!!");
model.setViewName("profile");
}
}else {
model.addObject("exist", "Please enter correct email address!");
String email = (String) session.getAttribute("emailsession");
Customer cust = cRepo.findByCustEmail(email);
model.addObject("customer", cust);
model.setViewName("profile");
}
return model;
}
Thymleaf code (html) -
<div align="center" class="alert alert-success" th:if="${msg}" th:utext="${msg}"></div>
<div align="center" class="alert alert-danger" th:if="${exist}" th:utext="${exist}"></div>
<!-- Modal HTML -->
<div id="myModal">
<div class="modal-dialog modal-login">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Profile Details</h4>
</div>
<div class="modal-body">
<form name="myForm" th:action="#{/profile}" th:object="${customer}" method="post">
<div class="form-group">
<i class="fa fa-id-card"></i>
<input name="id" type="text" class="form-control" placeholder="Enter Id" th:field="${customer.custId}" disabled="true" required="required" />
</div>
<div class="form-group">
<i class="fa fa-user"></i>
<input name="name" type="text" class="form-control" placeholder="Enter Name" th:field="${customer.custName}" required="required" />
</div>
<div class="form-group">
<i class="fa fa-envelope"></i>
<input name="email" type="email" class="form-control" placeholder="Enter Email" th:field="${customer.custEmail}" required="required" />
</div>
<div class="form-group">
<i class="fa fa-lock"></i>
<input name="password" type="text" class="form-control" placeholder="Enter Password" th:field="${customer.custPassword}" required="required" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-block btn-lg" value="Update" />
</div>
</form>
</div>
</div>
</div>
</div>
I want when user login and visit he/she should be able to check his/her profile(which I'm able to do working code) and when the user wants to update few fields(1-2 based on choice) and hit update he/she should be able to update the details (not create new user or record) because when I use #Controller on top of class then this code work and create new user instead update.
Your controller is annotated with #RequestMapping(value = "/profile", method = RequestMethod.PUT) which makes it a PUT endpoint. However, your request is clearly a POST. If we look at your html form it contains method="post". HTML forms only support GET and POST as valid methods so you need to update your endpoint to be a POST endpoint.
tldr;
RequestMapping(value = "/profile", method = RequestMethod.PUT)
to
RequestMapping(value = "/profile", method = RequestMethod.POST)
You request mapping in is POST but Controller has set to accept request as PUT.
<form name="myForm" th:action="#{/profile}" th:object="${customer}" **method="post"**>
#RequestMapping(value = "/profile", method = **RequestMethod.PUT**)
Just keep these in similar way both should be same.
Please check what I find and resolve this.
#RequestMapping(value = "/profile" ,method = RequestMethod.POST)
public ModelAndView updateProfile(#ModelAttribute Customer customer, HttpSession session) {
ModelAndView model = new ModelAndView();
Customer exist = cRepo.findByCustEmail(customer.getCustEmail());
if(exist != null) {
if(exist.getCustEmail().equals(session.getAttribute("emailsession"))) {
**exist.setCustId(exist.getCustId());
exist.setCustName(customer.getCustName());
exist.setCustEmail(customer.getCustEmail());
exist.setCustPassword(customer.getCustPassword());**
cRepo.save(exist);
model.addObject("msg", "User Details has been successfully updated!!");
model.addObject("customer", exist);
model.setViewName("profile");
}
}else {
model.addObject("exist", "Please enter correct email address!");
String email = (String) session.getAttribute("emailsession");
Customer cust = cRepo.findByCustEmail(email);
model.addObject("customer", cust);
model.setViewName("profile");
}
return model;
}

Java/Spring/MultipartFile File-upload with AngularJS:DefaultHandlerExceptionResolver: MultipartFile param not present" Controller is getting the file

Spring-controller is getting the MultipartFile, but its still throwing
"DefaultHandlerExceptionResolver:186 - Handler execution resulted in exception: Required MultipartFile parameter 'txnFile' is not present"
This is causing AngularJS client call to fail with 400.
JAVA-Spring-Controller:
#RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
public #ResponseBody Response uploadMultipleFileHandler(
#RequestParam("fileType") String fileType,
#RequestParam("fileEtx") String fileEtx,
#RequestParam("country") String country,
#RequestParam("network") String network,
#RequestParam("version") String version,
#RequestParam("txnDate") String txnDateStr,
#RequestParam("txnFile") MultipartFile txnFile,
#RequestParam("exceptionFile") MultipartFile exceptionFile){
Response response= null;
try {
Here, txnFile and exceptionFile is not null. Code runs file as well. But it still throws "DefaultHandlerExceptionResolver:186 - Handler execution resulted in exception: Required MultipartFile parameter 'txnFile' is not present"
Java-Spring-Config:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1000000" />
</bean>
HTML-AngularJS-Form:
<form method="POST" action="http://localhost:8080/recon-validation-tool/ctrl/core/uploadMultipleFile" enctype="multipart/form-data">
<fieldset>
<legend>Select Txn file:</legend>
<div class="form-group">
<label for="">Txn-file:</label>
<input type="file" file-model="txnFile"/>
</div>
</fieldset>
<fieldset>
<legend>Select Exec file:</legend>
<div class="form-group">
<label for="">Exec file:</label>
<input type="file" file-model="exceptionFile"/>
</div>
</fieldset>
<fieldset>
<legend>Please enter carrier details:</legend>
<div class="form-group">
<label for="txnDate">Date:</label>
<input type="date" name="txnDate" ng-model="formData.txnDate" value="2017-05-30">
</div>
<div class="form-group">
<label for="fileType">Type:</label>
<input type="text" name="fileType" ng-model="formData.fileType">
</div>
<div class="form-group">
<label for="fileEtx">Ext:</label>
<input type="text" name="fileEtx" ng-model="formData.fileEtx">
</div>
<div class="form-group">
<label for="country">country:</label>
<input type="text" name="country" ng-model="formData.country">
</div>
<div class="form-group">
<label for="country">network:</label>
<input type="text" name="network" ng-model="formData.network">
</div>
<div class="form-group">
<label for="version">version:</label>
<input type="text" name="version" ng-model="formData.version">
</div>
</fieldset>
<br>
<button ng-click="uploadFile()">Validate</button>
</form>
AngularJS-Controller:
controllerM.controller('HomeController', function($scope, $http, $location, $rootScope){
$scope.formData= {};
$scope.formData.fileEtx= "";
$scope.formData.fileType= "";
$scope.formData.country= "";
$scope.formData.network= "";
$scope.formData.version= "";
$scope.formData.txnDate= "";
$scope.uploadFile = function(){
var data = new FormData();
data.append('fileEtx', $scope.formData.fileEtx);
data.append('fileType', $scope.formData.fileType);
data.append('country', $scope.formData.country);
data.append('network', $scope.formData.network);
data.append('version', $scope.formData.version);
data.append('txnDate', $scope.formData.txnDate);
data.append('txnFile', $scope.txnFile);
data.append('exceptionFile', $scope.exceptionFile);
var uploadUrl = "http://localhost:8080/recon-validation-tool/ctrl/core/uploadMultipleFile";
$http.post(uploadUrl, data, {
headers: {'Content-Type': undefined},
transformRequest: angular.identity
})
.success(function(resp){
console.log(resp);
})
.error(function(resp){
console.log(resp);
});
};
});

How to navigate between html & jsp pages in spring

I have a Html page called kind.html inside the WEB-INF directory and an other jsp page called registration.jsp inside the WEB-INF folder. I need to put this registration.jsp page inside the WEB-INF directory so it cannot be accessible if a user attempts to get access to it by typing its URL. So my problem is how can i navigate from kind.html to registration.jsp with link called home I am newbie in this Thank you.
below is my code snippet and png file
kind.html..............................................
<li class='active'><a href='kind.html'><span>Home</span></a></li>
<li class='has-sub'><span>Register</span>
.............................registrationcontroller........................................
#RequestMapping(value="/registration",method = RequestMethod.POST)
public #ResponseBody
String firstRegistration(HttpServletRequest req,
HttpServletResponse response) {
response.setContentType("text/html");
RegistrationModel registrationModel = new RegistrationModel();
registrationModel.setFirstName(req.getParameter("first_name"));
System.out.println("controller " + req.getParameter("first_name") );
registrationModel.setLastName(req.getParameter("last_name"));
registrationModel.setPassword(req.getParameter("password"));
registrationModel.setEmailID(req.getParameter("email"));
System.out.println("controller email " + req.getParameter("email"));
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
try {
Date date = format.parse(req.getParameter("BirthDate"));
registrationModel.setDOB(date);
} catch (Exception e) {
e.printStackTrace();
}
String phoneno=req.getParameter("phoneNo");
Integer phoneNo = Integer.parseInt(phoneno);
System.out.println("phone no ...."+phoneNo);
registrationModel.setPhoneNo(phoneNo);
registrationModel.setGender(req.getParameter("gender"));
String age=req.getParameter("Age");
Long AGE = Long.parseLong(age);
registrationModel.setAge(AGE);
registrationModel.setAvtar(req.getParameter("Avtar"));
System.out.println("avtar"+ req.getParameter("Avtar"));
Address address = new Address();
address.setAddressline(req.getParameter("Full-Address"));
address.setCity(req.getParameter("city"));
address.setLandmark(req.getParameter("landmark"));
address.setState(req.getParameter("state"));
String zipCode =req.getParameter("Zipcode");
Long zipcode = Long.parseLong(zipCode);
address.setZipcode(zipcode);
registrationModel.setAddress(address);
registrationService.resgistration(registrationModel);
return "registration.jsp";
}
..........................registration.jsp.........................................................
<form action="registration" method="post">
<fieldset>
<legend>Register Form</legend>
<div>
<input type="text" name="first_name" placeholder="First Name" />
</div>
<div>
<input type="text" name="last_name" placeholder="Last Name" />
</div>
<div>
<input type="password" name="password" placeholder="Password" />
</div>
<div>
<input type="text" name="email" placeholder="Email" />
</div>
<div>
<input type="text" name="BirthDate" placeholder="BirthDate" />
</div>
<div>
<input type="number" name="Age" placeholder="Age" />
</div>
<div>
<select name="gender">
<option value="select">i am..</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select><br> <br>
</div>
<div>
<input type="number" name="phoneNo" placeholder="PhoneNo" />
</div>
<div>
<input type="text" name="Full-Address"
placeholder="Full-Address" />
</div>
<div>
<input type="text" name="landmark" placeholder="landmark" />
</div>
<div>
<input type="text" name="city" placeholder="city" />
</div>
<div>
<input type="text" name="state" placeholder="state" />
</div>
<div>
<input type="number" name="Zipcode" placeholder="Zipcode" />
</div>
<div>
<input type="file" name="Avtar" placeholder="Avtar" />
</div>
<input type="submit" name="submit" value="Send" />
</fieldset>
</form>![folder structure of project][2]
1st to call your pages html is static so you can use mvc resources "" for it, for jsp you have to use ViewResolver for jstl use InternalResourceViewResolver in its configuration as :
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
then in your controller use
return "registration";
also you will need method to handle GET request and change below line
<li class='has-sub'><span>Register</span>
if you are using Spring boot you will find these configuration automated.

Categories

Resources