Using selenium with Dynamic values - selenium

I am working with Selenium RC.
I am giving the data manually to selenium.Like below
selenium.type("id=username","myName");
selenium.type("id=password","myPassword");
selenium.click("id=login");
But, my doubt is is there any way to get the data dynamically? Here I am giving my Name directly into selenium.type();
Is there any way to retrieve username and password from other place like textfile or excel file?
Any help?

Short answer - YES.
Longer answer - You need to program it. So it is not possible using Selenium IDE, but you can use Selenium Webdriver. I am doing this in Java, so I will post you little snippets of my code, how do i do it.
1) I have special Java Class to hold the user information:
public class EUAUser {
private String username;
private String password;
private boolean isUsed
public EUAUser(String uname, String pwd){
this.username = uname;
this.password = pwd;
isUsed = false;
}
public String getPassword(){
return password;
}
public String getUsername(){
return username;
}
public void lockUser(){
isUsed = true;
}
}
2) Then I have UserPool to hold all users. So far because I need only 5 different users, I do it by quick and dirty approach:
public class UserPool {
private List<EUAUser> userList = new ArrayList<EUAUser>();
public UserPool(){
userList.add(new EUAUser("firstUser","a"));
userList.add(new EUAUser("MyUsername", "a"));
userList.add(new EUAUser("TestUser", "a"));
userList.add(new EUAUser("TSTUser2", "a"));
}
public EUAUser getNextUser() throws RuntimeException {
for(EUAUser user: userList){
if (!user.isUsed()){
user.lockUser();
return user;
}
}
throw new RuntimeException("No free user found.");
}
3) In tests I have something like this
UserPool pool = new UserPool();
EUAUser user = pool.getNextUser();
selenium.type("id=username", user.getUserName());
selenium.type("id=password", user.getPassword());
selenium.click("id=login");
The above code does
Add all known users to the UserPool
Retreive one free user from the pool
logs him into the app under username and password
In my case its really quick and dirty approach, but you can have list of users in file and load them into the UserPool using fileReader or something. Just giving you idea how you can do this ;)

Related

Spring AOP doesn't always intercept a method

I have a user service. The service has the ability to reset the password.
#Service
public final class UserService {
private final UserMapper userMapper;
#Autowired
public UserService(final UserMapper userMapper) {
this.userMapper = userMapper;
}
#Transactional
public String restorePassword(final String loginOrEmail) throws IllegalArgumentException {
User user = userMapper.findByUsername(loginOrEmail);
if (user == null) {
user = userMapper.findByEmail(loginOrEmail);
if (user == null) throw new IllegalArgumentException("User not found");
}
final String newPassword = PasswordGenerator.generate(2, 2, 2, 4);
returnPasswordAfterRestore(newPassword, user);
//Later, the password will salt and be encrypted before entering the database.
userMapper.setPassword(newPassword, user.getUserId());
return user.getEmail();
}
public void returnPasswordAfterRestore(final String password, final User user) {
System.out.println("------------------------Method run!------------------------");
}
I need to get the generated password and send it to the user. For this I use Spring AOP.
#Before("execution(* com.example.aop.service.UserService.returnPasswordAfterRestore(..))&&args(password, user)")
public void beforeReturnPasswordAfterRestore(String password, User user) {
System.out.println("-------------------------------" + password);
System.out.println("-------------------------------" + user.getUsername() + " mail:" + user.getEmail());
}
When I make an explicit call to the returnPasswordAfterRestore () method, the aspect fulfills correctly and intercepts the parameters, this confirms the debug mode.
userService.returnPasswordAfterRestore("newPass", user);
But when I make a call to the restorePassword () method, which contains a call to the returnPasswordAfterRestore () method, the aspect does not work.
userService.restorePassword(user.getUsername());
How do I solve this problem? Or how can I get the generated password out of a method without saving it to an external variable?

do we need sessions in WebRTC?

I am creating a sample project for learning purpose(later on I will be working on project based on webrtc and kurento), I am using Kurento media server with it, I have modified the tutorial of the kurento server and made one sample out of it.
In all of the samples for Kurento Server they are using a UserRegistry.java where they are storing objects of UserSession as shown below:
public class UserSession {
private static final Logger log = LoggerFactory.getLogger(UserSession.class);
private final String name;
private final WebSocketSession session;
private String sdpOffer;
private String callingTo;
private String callingFrom;
private WebRtcEndpoint webRtcEndpoint;
private WebRtcEndpoint playingWebRtcEndpoint;
private final List<IceCandidate> candidateList = new ArrayList<>();
public UserSession(WebSocketSession session, String name) {
this.session = session;
this.name = name;
}
public void sendMessage(JsonObject message) throws IOException {
log.debug("Sending message from user '{}': {}", name, message);
session.sendMessage(new TextMessage(message.toString()));
}
public String getSessionId() {
return session.getId();
}
public void setWebRtcEndpoint(WebRtcEndpoint webRtcEndpoint) {
this.webRtcEndpoint = webRtcEndpoint;
if (this.webRtcEndpoint != null) {
for (IceCandidate e : candidateList) {
this.webRtcEndpoint.addIceCandidate(e);
}
this.candidateList.clear();
}
}
public void addCandidate(IceCandidate candidate) {
if (this.webRtcEndpoint != null) {
this.webRtcEndpoint.addIceCandidate(candidate);
} else {
candidateList.add(candidate);
}
if (this.playingWebRtcEndpoint != null) {
this.playingWebRtcEndpoint.addIceCandidate(candidate);
}
}
public void clear() {
this.webRtcEndpoint = null;
this.candidateList.clear();
}
}
I have two questions on this:
Why do we need session object?
What are the alternatives(if there are any) to manage session?
Let me give some more background on 2nd question. I found out that I can run the Kurento-JavaScript-Client(I need to convert it to browser version and then I can use it.) on the client side only (That way I won't require a backend server i.e. nodejs or tomcat - this is my assumption). So in this case how would I manage session or I can totally remove the UserRegistry concept and use some other way.
Thanks & Regards
You need to store sessions to implement signalling between the clients and the application server. See for example here. The signalling diagram describes the messages required to start/stop/etc the WebRTC video communication.
If you are planing to get rid of the application server (i.e. move to JavaScript client completely) you can take a look to a publish/subscribe API such as PubNub.

Customize login in Grails Spring Security plugin

I have an application where the login should include an organization number, so the login needs to be username + password + organization number.
Sample case: If the username + password matches with an existing user, I need to check if that user has the organization id. If not, the login should fail.
I saw that the login form from spring security plugin submits to /app/j_spring_security_check but couldn't find where that is actually implemented.
Also I'm not sure if touching that is the right way of implementing this custom login.
My question is where / how to customize the login action? (to make it fail on the case I described above).
We can do this by overriding the filter UserNamePasswordAuthenticationFilter and provide our custom attemptAuthentication.
So, go to DefaultSecurityConfig.groovy file (inside plugins). See tree diagram below:
target
|-work
|-plugins
|-spring-security-core-2.0-RC5
|-conf
|-DefaultSecurityConfig.groovy
In DefaultSecurityConfig.groovy under apf closure we specify filterProcessUrl which we can override in grails application's Config.groovy like we do for other properties (e.g. rejectIfNoRule)
grails.plugin.springsecurity.apf.filterProcessesUrl="your url"
Now we understood how it checks for authentication.Let's customise it own way by overriding the method attemptAuthentication of filter named UsernamePasswordAuthenticationFilter. For example, see below(also, go through the inline comments added there)
package org.springframework.security.web.authentication;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.util.Assert;
public class CustomUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "j_username";
public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "j_password";
/** #deprecated */
#Deprecated
public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";
private String usernameParameter = "j_username";
private String passwordParameter = "j_password";
private String organisationParameter = 'j_organisation'
private boolean postOnly = true;
public UsernamePasswordAuthenticationFilter() {
super("/j_spring_security_check");
}
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if(this.postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
} else {
String username = this.obtainUsername(request);
String password = this.obtainPassword(request);
String password = this.obtainOrganisation(request);
//regular implementation in spring security plugin /**
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
this.setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
**/
//Your custom implementation goes here(Authenticate on the basis of organisation as well). Here you need to customise authenticate as per your requirement so that it checks for organisation as well.
}
protected String obtainOrganisation(HttpServletRequest request) {
return request.getParameter(this.organisationParameter);
}
protected String obtainPassword(HttpServletRequest request) {
return request.getParameter(this.passwordParameter);
}
protected String obtainUsername(HttpServletRequest request) {
return request.getParameter(this.usernameParameter);
}
protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
}
public void setUsernameParameter(String usernameParameter) {
Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
this.usernameParameter = usernameParameter;
}
public void setPasswordParameter(String passwordParameter) {
Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
this.passwordParameter = passwordParameter;
}
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
public final String getUsernameParameter() {
return this.usernameParameter;
}
public final String getPasswordParameter() {
return this.passwordParameter;
}
}
Hence, it's more of a overriding task in terms of spring security.
To get more clearer idea about same read this nice link for java
and
for grails read this
Hope it helps.
These blogs gives a more detailed idea of the same requirements.

Require password when unistall an app in android

Hey i want when user is trying to un-install an app ,there comes password to unlock. Im following this code :
android: require password when uninstall app
but there comes an error in manifest "android:description="#string/descript""
Kindly help me.im badly stuck in it.there's no answer availble on google too
it would not help on 4.3 or higher but I am posting a link where you can find the solution and reason of why you can not do it.
Here is the link. Hope it would help you in understanding the real milestone in this context.
try the following code in your service
public static final String UNINSTALLER ="com.android.packageinstaller.UninstallerActivity";
private ActivityManager activityManager = null;
private ExecutorService executorService;
#Override
public void onCreate() {
super.onCreate();
executorService = Executors.newSingleThreadExecutor();
activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
LockerThread thread = new LockerThread();
executorService.submit(thread);
}
private void protactApp(String packname) {
Intent pwdIntent = null;
pwdIntent = new Intent("uninstaller.receiver");
sendBroadcast(pwdIntent);
}
class LockerThread implements Runnable {
private String lastname;
public LockerThread() {
}
#Override
public void run() {
ComponentName act = activityManager.getRunningTasks(1).get(0).topActivity;
String packname = act.getPackageName();
if (act.getClassName().equals(UNINSTALLER)) {
Log.d("Tag", "package to be uninstalled");
protactApp(UNINSTALLER);
}
}
and from receiver you can get action while uninstall the app so whatever screen you prepare for password or pattern that you can start before uninstall like applock application

Spring Security Password Authentication

need some help or direction using Spring's security 3.1.x.
I am storing an encrypted password in MySql database. Which password is defined as a varchar(60) column.
The first time running the web app, I generated the password with the following code snippet:
String p = "12345";
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(p);
I then took the String encodedPassword and pasted into the database column. I kept the code in my authentication-manager (snippet follows), and logged encodedPassword to the server log.
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider user-service-ref="usersDAO">
<security:password-encoder ref="encoder" />
</security:authentication-provider>
</security:authentication-manager>
<bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
My problem is that authentication fails with exception: Bad credentials when BCryptPasswordEncoder.matches() runs. The stored password is not matching the generated hash from the form input. The same text password that was used in the initial hash generation was used.
Each time I re-run the login entering the same text, the logged encodedPassword is different. Debugging I can see where the entity is being returned from the database correctly, so I don't think that is an issue. The issue seems to me that I'm not doing/setting something correctly in order to generate the same hash each time the text
password is entered.
EDIT:
Adding usersDAO.
import org.springframework.security.core.userdetails.UserDetailsService;
public interface UsersDAO extends Dao<Users>, UserDetailsService
{
Users getByUsername(String username);
}
EDIT:
adding implementation.
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#Repository("usersDAO")
public class UsersDAO_DB extends AbstractHibernateDao<Users> implements UsersDAO
{
final Logger log = LoggerFactory.getLogger(this.getClass());
#Override
public Users getByUsername(String username)
{
String p = "12345";
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(p);
log.debug("HELLOZ ----> " + encodedPassword);
notNull(username, "username can't be null");
return (Users) getSession()
.getNamedQuery("users.byUsername")
.setParameter("username", username)
.uniqueResult();
}
#Override
#Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
notNull(username, "username can't be null");
Users users = getByUsername(username);
if (users == null) {
throw new UsernameNotFoundException("No user with username " + username);
}
return users;
}
#Override
public void create(Users t)
{
// TODO Auto-generated method stub
}
#Override
public void update(Users t)
{
// TODO Auto-generated method stub
}
#Override
public void delete(Users t)
{
// TODO Auto-generated method stub
}
}
Any ideas?
This was a newbie error here following a couple of different tutorials.
In the bean I had defined my security encoder as a:
org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
To generate a test cryptic password I used the following code:
String p = "12345";
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(p);
log.debug("HELLOZ ----> " + encodedPassword);
which was mixing the org.springframework.security.crypto.password.PasswordEncoder and the org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder. See the above code defining passwordEncoder.
Once I changed it to:
String p = "12345";
BCryptPasswordEncoder pe= new BCryptPasswordEncoder();
String encPassword =pe.encode(p);
log.debug("HELLB ----> " + encPassword);
copied the output to my database and retested everything worked fine.
Each time I re-run the login entering the same text, the logged encodedPassword is different".
Where is that logging coming from? Spring Security won't log incoming passwords and if you are using BCrypt it shouldn't be re-encoding them from scratch anywhere.
It sounds like you may be re-encoding the submitted password yourself, possibly in your usersDAO which isn't shown.
If not, please post your complete configuration and the logging output you're talking about.