Vaadin LoginOverlay - authentication

I am very new to both java and vaadin. Hope to be able to get some good tips on how I can improve my code.
I would like to rewrite the code below to use Vaadin´s -> LoginOverlay instead of the code below.
As I said, I'm trying to learn so I have used the code for this example: https://www.youtube.com/watch?v=oMKks5AjaSQ&t=1158s
However, LoginOverlay seems to be a better way to display its login part through. As in this example: https://www.youtube.com/watch?v=pteip-kZm4M
So my question is how can you write the code below as a LoginOverlay.
public class LoginView extends Div {
public LoginView(AuthService authService) {
setId("login-view");
var username = new TextField("Username");
var password = new PasswordField("Password");
add(
new H1("Welcome"),
username,
password,
new Button("Login", event -> {
try {
authService.authenticate(username.getValue(), password.getValue());
UI.getCurrent().navigate("home");
} catch (AuthService.AuthException e) {
Notification.show("Wrong credentials.");
}
}),
new RouterLink("Register", RegisterView.class)
);
}
}
I have only come this far to convert the code.
A clarification of the new part of the code. The code does not work. The part with loginOverlay.addLoginListener (event -> probably needs to be written in a different way.
I'm using IntelliJ 2020.3.4 if that is of any help.
public class LoginView2 extends Composite<LoginOverlay> {
public LoginView2(AuthService authService) {
setId("login-view");
LoginOverlay loginOverlay = getContent();
loginOverlay.setTitle("Welcom");
loginOverlay.setDescription("Manage your business tasks");
loginOverlay.setOpened(true);
loginOverlay.addLoginListener(event -> {try {
if(authService.authenticate(username.getValue(), password.getValue());
UI.getCurrent().navigate("home");
} catch (AuthService.AuthException e) {
Notification.show("Wrong credentials.");
}
}),
new RouterLink("Register", RegisterView.class);
}
}
}
}
Super grateful for all the help you can give.
Many thanks to everyone who makes stackoverflow so amazing.

Copy-pasting code snippets with little idea about what the code does is a recipe for disaster, especially when it comes to security.
You have all kinds of errors in your code: misplaced braces, using variables that do not exist, and a RouterLink far from where it belongs.
I understand you've got to start somewhere. I would recommend starting from code that actually compiles, and then gradually adding things, testing what you have so far at every step.
Here are some tips for your LoginView2:
Remove the whole loginOverlay.addLoginListener(...) code, including the authService.authenticate call and the RouterLink. Make sure that you can run the application at this point, and that you can see the login overlay.
Add back the login listener, but for now just show a notification in it. Test that you can run the application, and that if you click Login, your notification is displayed.
loginOverlay.addLoginListener(event -> {
Notification.show("This is working");
});
Implement the authentication. You have a call to authService.authenticate(...) inside an if-statement, but the method does not return anything. Instead, it throws an exception if the authentication fails, hence the try-catch. This means that inside the try { ... } block, any code you put after the authService.authenticate(...) call is only executed if it did not throw an exception, i.e. if the authentication was successful.
There are no username or password variables. The first YouTube video had defined these variables in the form of text fields. With the login overlay, it creates those fields for you, so how do you get the corresponding values from it?

Related

static method in react native bug(callback)

I will try my best to explain the problem i have.
here is a sample code
auth.js
static authenticate(email,password,callbackIsLogged)
{
//some logic
if(passwordCorrect)
{
callbackIsLogged(true);
}
else
{
callbackIsLogged(false);
}
}
login.js
loginButtonClicked()
{
Authcontroller.authenticate(email,password,function(loginState)
{
if(loginState)
{
alert('correect');
//proceed withlogin.
}
else
{
alert('error');
}
});
}
the problem i have is weired.
lets look at a sample scenario where this bug happens.
if i login with correct username and password for the first time when the app opens everything goes according to plan.
But if i enter the incorrect password at the first time and the second time enter the correct password the callback function will get called twice with boolean value true and false.
It seems like the static function somehow hold the previous callbacks and execute them.
hope you undestood my question. how to fix this.
thanks.

Programmatically execute Gatling tests

I want to use something like Cucumber JVM to drive performance tests written for Gatling.
Ideally the Cucumber features would somehow build a scenario dynamically - probably reusing predefined chain objects similar to the method described in the "Advanced Tutorial", e.g.
val scn = scenario("Scenario Name").exec(Search.search("foo"), Browse.browse, Edit.edit("foo", "bar")
I've looked at how the Maven plugin executes the scripts, and I've also seen mention of using an App trait but I can't find any documentation for the later and it strikes me that somebody else will have wanted to do this before...
Can anybody point (a Gatling noob) in the direction of some documentation or example code of how to achieve this?
EDIT 20150515
So to explain a little more:
I have created a trait which is intended to build up a sequence of, I think, ChainBuilders that are triggered by Cucumber steps:
trait GatlingDsl extends ScalaDsl with EN {
private val gatlingActions = new ArrayBuffer[GatlingBehaviour]
def withGatling(action: GatlingBehaviour): Unit = {
gatlingActions += action
}
}
A GatlingBehaviour would look something like:
object Google {
class Home extends GatlingBehaviour {
def execute: ChainBuilder =
exec(http("Google Home")
.get("/")
)
}
class Search extends GatlingBehaviour {...}
class FindResult extends GatlingBehaviour {...}
}
And inside the StepDef class:
class GoogleStepDefinitions extends GatlingDsl {
Given( """^the Google search page is displayed$""") { () =>
println("Loading www.google.com")
withGatling(Home())
}
When( """^I search for the term "(.*)"$""") { (searchTerm: String) =>
println("Searching for '" + searchTerm + "'...")
withGatling(Search(searchTerm))
}
Then( """^"(.*)" appears in the search results$""") { (expectedResult: String) =>
println("Found " + expectedResult)
withGatling(FindResult(expectedResult))
}
}
The idea being that I can then execute the whole sequence of actions via something like:
val scn = Scenario(cucumberScenario).exec(gatlingActions)
setup(scn.inject(atOnceUsers(1)).protocols(httpConf))
and then check the reports or catch an exception if the test fails, e.g. response time too long.
It seems that no matter how I use the 'exec' method it tries to instantly execute it there and then, not waiting for the scenario.
Also I don't know if this is the best approach to take, we'd like to build some reusable blocks for our Gatling tests that can be constructed via Cucumber's Given/When/Then style. Is there a better or already existing approach?
Sadly, it's not currently feasible to have Gatling directly start a Simulation instance.
Not that's it's not technically feasible, but you're just the first person to try to do this.
Currently, Gatling is usually in charge of compiling and can only be passed the name of the class to load, not an instance itself.
You can maybe start by forking io.gatling.app.Gatling and io.gatling.core.runner.Runner, and then provide a PR to support this new behavior. The former is the main entry point, and the latter the one can instanciate and run the simulation.
I recently ran into a similar situation, and did not want to fork gatling. And while this solved my immediate problem, it only partially solves what you are trying to do, but hopefully someone else will find this useful.
There is an alternative. Gatling is written in Java and Scala so you can call Gatling.main directly and pass it the arguments you need to run the Gatling Simulation you want. The problem is, the main explicitly calls System.exit so you have to also use a custom security manager to prevent it from actually exiting.
You need to know two things:
the class (with the full package) of the Simulation you want to run
example: com.package.your.Simulation1
the path where the binaries are compiled.
The code to run a Simulation:
protected void fire(String gatlingGun, String binaries){
SecurityManager sm = System.getSecurityManager();
System.setSecurityManager(new GatlingSecurityManager());
String[] args = {"--simulation", gatlingGun,
"--results-folder", "gatling-results",
"--binaries-folder", binaries};
try {
io.gatling.app.Gatling.main(args);
}catch(SecurityException se){
LOG.debug("gatling test finished.");
}
System.setSecurityManager(sm);
}
The simple security manager i used:
public class GatlingSecurityManager extends SecurityManager {
#Override
public void checkExit(int status){
throw new SecurityException("Tried to exit.");
}
#Override
public void checkPermission(Permission perm) {
return;
}
}
The problem is then getting the information you want out of the simulation after it has been run.

Should a class be able to catch an exception from a class that it doesn't know about?

I wrote some code in an MVC Framework that looks something like:
class Controller_Test extends Controller
{
public function action_index()
{
$obj = new MyObject();
$errors = array();
try
{
$results = $obj->doSomething();
}
catch(MyObject_Exception $e)
{
$e->getErrors();
}
catch(Exception $e)
{
$errors[] = $e->getMessage();
}
}
My friend argues that the Controller should know nothing about MyObject, and therefore I should not catch MyObject_Exception.
He argues that the code should do something like this instead:
class Controller_Test extends Controller
{
public function action_index()
{
$obj = new MyObject();
$errors = array();
if($obj->doSomething())
{
$results = $obj->getResults();
}
else
{
$errors = $obj->getErrors();
}
}
I definitely understand his approach, but feel as though state management can lead to unintended side effects.
What is the right or preferred approach?
Edit: mistakenly put $obj->getErrors() in MyObject_Exception catch clause instead of $e->getErrors();
The debate about exceptions vs. returned error codes is a long and bloody one.
His argument breaks down in that, by using a getErrors() function, you are learning information about the object. If that is your reason for using a boolean return to indicate success, then you are wrong. In order for the Controller to handle the error properly, it has to know about the object it was touching and what the specific error was. Was it a network error? Memory error? It has to know in some way or another.
I prefer the exception model because it's cleaner and allows me to handle more errors in a more controlled fashion. It also provides a clear cut way for the data relating to an exception to be passed.
However, I disagree with your use of a function like getErrors(). Any data pertaining to the exception that would help me handle it should be included with the exception. I should not have to go hunting into the object again to get information about what went wrong.
Did the network connection timeout? The exception should contain the host/port it tried to connect to, how long it waited, and any data from the lower networking levels.
Let's do this in example (in psuedo c#):
public class NetworkController {
Socket MySocket = null;
public void EstablishConnection() {
try {
this.MySocket = new Socket("1.1.1.1",90);
this.MySocket.Open();
} catch(SocketTimeoutException ex) {
//Attempt a Single Reconnect
}
catch(InvalidHostNameException ex) {
Log("InvalidHostname");
Exit();
}
}
}
Using his method:
public class NetworkController {
Socket MySocket = null;
public Boolean EstablishConnection() {
this.MySocket = new Socket("1.1.1.1",90);
if(this.MySocket.Open()) {
return true;
} else {
switch(this.MySocket.getError()) {
case "timeout":
// Reattempt
break;
case "badhost":
Log("InvalidHostname");
break;
}
}
}
}
Ultimately, you need to know what happened to the object to know how to respond to it, and there is no sense in using some convoluted if statement set or switch-case to determine that. Use the exceptions and love them.
EDIT: I accidentally the last half of a sentence.
In general, I would say that what's important is whether the controller understands the meaning of the exception and can handle it properly. In many cases (if not most), the controller will not know how to properly handle the exception, and so should not catch and handle it.
On the other hand, the controller might reasonably be permitted to understand some specific exception like a "DatabaseUnavailableException", even if it has no idea how or why MyObject used a database. The controller might be permitted to retry the call to MyObject a certain number of times, all without knowing about how MyObject is implemented.
First of all controller is not meant for handling the underlying exceptions thrown by classes.
Even if one occurs controller should halt saying something wrong at underlying error.
This way we make sure that controller does really and only do the job of flow control.
The other classes which give controller some output should be error free unless the error is very much controller specific.

Metro c++ async programming and UI updating. My technique?

The problem: I'm crashing when I want to render my incoming data which was retrieved asynchronously.
The app starts and displays some dialog boxes using XAML. Once the user fills in their data and clicks the login button, the XAML class has in instance of a worker class that does the HTTP stuff for me (asynchronously using IXMLHTTPRequest2). When the app has successfully logged in to the web server, my .then() block fires and I make a callback to my main xaml class to do some rendering of the assets.
I am always getting crashes in the delegate though (the main XAML class), which leads me to believe that I cannot use this approach (pure virtual class and callbacks) to update my UI. I think I am inadvertently trying to do something illegal from an incorrect thread which is a byproduct of the async calls.
Is there a better or different way that I should be notifying the main XAML class that it is time for it to update it's UI? I am coming from an iOS world where I could use NotificationCenter.
Now, I saw that Microsoft has it's own Delegate type of thing here: http://msdn.microsoft.com/en-us/library/windows/apps/hh755798.aspx
Do you think that if I used this approach instead of my own callbacks that it would no longer crash?
Let me know if you need more clarification or what not.
Here is the jist of the code:
public interface class ISmileServiceEvents
{
public: // required methods
virtual void UpdateUI(bool isValid) abstract;
};
// In main XAML.cpp which inherits from an ISmileServiceEvents
void buttonClick(...){
_myUser->LoginAndGetAssets(txtEmail->Text, txtPass->Password);
}
void UpdateUI(String^ data) // implements ISmileServiceEvents
{
// This is where I would render my assets if I could.
// Cannot legally do much here. Always crashes.
// Follow the rest of the code to get here.
}
// In MyUser.cpp
void LoginAndGetAssets(String^ email, String^ password){
Uri^ uri = ref new URI(MY_SERVER + "login.json");
String^ inJSON = "some json input data here"; // serialized email and password with other data
// make the HTTP request to login, then notify XAML that it has data to render.
_myService->HTTPPostAsync(uri, json).then([](String^ outputJson){
String^ assets = MyParser::Parse(outputJSON);
// The Login has returned and we have our json output data
if(_delegate)
{
_delegate->UpdateUI(assets);
}
});
}
// In MyService.cpp
task<String^> MyService::HTTPPostAsync(Uri^ uri, String^ json)
{
return _httpRequest.PostAsync(uri,
json->Data(),
_cancellationTokenSource.get_token()).then([this](task<std::wstring> response)
{
try
{
if(_httpRequest.GetStatusCode() != 200) SM_LOG_WARNING("Status code=", _httpRequest.GetStatusCode());
String^ j = ref new String(response.get().c_str());
return j;
}
catch (Exception^ ex) .......;
return ref new String(L"");
}, task_continuation_context::use_current());
}
Edit: BTW, the error I get when I go to update the UI is:
"An invalid parameter was passed to a function that considers invalid parameters fatal."
In this case I am just trying to execute in my callback is
txtBox->Text = data;
It appears you are updating the UI thread from the wrong context. You can use task_continuation_context::use_arbitrary() to allow you to update the UI. See the "Controlling the Execution Thread" example in this document (the discussion of marshaling is at the bottom).
So, it turns out that when you have a continuation, if you don't specify a context after the lambda function, that it defaults to use_arbitrary(). This is in contradiction to what I learned in an MS video.
However by adding use_currrent() to all of the .then blocks that have anything to do with the GUI, my error goes away and everything is able to render properly.
My GUI calls a service which generates some tasks and then calls to an HTTP class that does asynchronous stuff too. Way back in the HTTP classes I use use_arbitrary() so that it can run on secondary threads. This works fine. Just be sure to use use_current() on anything that has to do with the GUI.
Now that you have my answer, if you look at the original code you will see that it already contains use_current(). This is true, but I left out a wrapping function for simplicity of the example. That is where I needed to add use_current().

Silverlight 4 Asynchronous Issue

I am creating an application in Silverlight 4. The first screen the user comes in contact with is the Login screen (Login.xaml). I have written the following code in Login.xaml.cs file.
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
//first validate if the user is authorised for this application
if (this.ValidateEntry())
{
if (UserAuthenticationBL.AuthenticateUser(txtUserName.Text.Trim(), txtPassword.Password.Trim()))
{
//since the user is authenticated we will show the dashboard screen
this.Content = new MainPage();
}
else
{
this.ShowErrorMessage("Invalid username or password");
txtUserName.Focus();
}
}
}
My problem is that the code gets executed before i get the data in the AuthenticateUser method. The code immediately comes down to the "Invalid username or password" and the list is loaded after all the execution on the xaml page has finished.
I know there is something going wrong with the Asynchronous thingi...and i also know i need to put an event to know when the loading has completed........
but i dont know how to go about it!!!
can someone please put some light on this issue...
thank you.
If I understood it right, your AuthenticateUser method is running async, right?
You have to define a callback to the AuthenticateUserComplete event and run the method in the button submit event. In the callback write this if/else clause, then it will be called once the asynchronous method was completed.
Just one question, why are you doing asynchronously if your behavior should be synchronous? (You have to get the answer before deciding what to do).
This http://msdn.microsoft.com/en-us/library/aa719598%28VS.71%29.aspx
may be helpful :)
Oscar