angular2 material - md-error and username does not exists from a server call - angular2-forms

This is my login form. If a user puts in a wrong username and does not exists on the server then how do I use md-error to display message?
E.g.
Here is the json I get back for auth from a submit:
{is_username: false, status: false}
Here is how I set up my form:
this.myForm = fb.group({
username: ['',[Validators.required]],
password: ['',[Validators.required]]
})
Here is my HTML:
<md-input-container>
<input mdInput type="email" placeholder="Username" [(ngModel)]="username" formControlName="username" style="width: 300px;outline: none;">
<md-error *ngIf="myForm.get('username').hasError('required')">Username is required</md-error>
<md-error *ngIf="myForm.get('username').hasError('username_exists')">Username does exist</md-error>
</md-input-container>
So..how do I trigger a md-error message if is_username is false?

I've been doing server side validation like this.
<md-input-container>
<input mdInput type="email" placeholder="Username" [(ngModel)]="username" formControlName="username" style="width: 300px;outline: none;">
<md-error *ngIf="myForm.get('username').hasError('required')">Username is required</md-error>
<md-error *ngIf="myForm.controls['username'].hasError('username_exists')">{{myForm.controls['username'].errors['username_exists']}}</md-error>
</md-input-container>
Then, set the error after you get the response from the server.
https://angular.io/api/forms/AbstractControl#setErrors
this.myForm.controls['username'].setErrors({
'username_exists': 'Username does exist'
});
I typically return validation error messages from the server as well, which could be used here.

Related

Capybara::ElementNotFound: Unable to find field "Key name"

I've read the similar questions to this but they don't solve my issue. I'm new with js testing so I think I might be doing something wrong.
The form produces this HTML
<form class="new_category_item_key" id="new_category_item_key" action="/guides/dungeon-boss/categories?category_id=heroes" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="b7wiF07zYh/Nl727M3y0Uk1TbroMJFuGqTK6fYNlNted/5G4Wmz4BZLb7IazzyP5md/wWRb1D28ePhrzt2uMSA==" />
<label for="category_item_key_name">Key name</label>
<input type="text" name="category_item_key[name]" id="category_item_key_name" />
<select name="category_item_key[key_type]" id="category_item_key_key_type"><option value="1">Value</option>
<option value="2">Text</option>
<option value="3">Image</option></select>
<input type="submit" name="commit" value="Add New Key" />
</form>
and I have the following integration test on the form
setup do
#user = users(:michael)
#user1 = users(:archer)
#guide = Guide.find(1)
#mod_relationship = game_mods_relationships(:mod1)
#category = Category.find(1)
Capybara.current_driver = Capybara.javascript_driver # :selenium by default
end
test "adding keys mod success then fail" do
log_in_as(#user)
get edit_guide_category_path(#guide, #category)
assert_template 'categories/edit'
assert_difference 'CategoryItemKey.count', 1 do
fill_in 'Key name', with: "diablo"
click_button "commit"
end
end
when I run the test I get the following error
Capybara::ElementNotFound: Capybara::ElementNotFound: Unable to find field "Key name"
Looking at the HTML I can see the field is there. If I try using the inputs id it still fails, if I remove the fill in line then it says it cant find the button to click which is also there. I assume its getting the right page because get edit_guide_category_path(#guide, #category) works for the other tests (but they are non js tests and don't use selenium).
Its probably something simple but I cant get it.
You're mixing up two different libraries -- You can't use get with Capybara, you use visit(url) to go to the page. You also shouldn't normally be asserting templates in a feature test, thats for lower level tests.

Using Rails to automatically enter username and password on a third party site

I have access to an ASP.Net site, secured behind a simple username and password authentication, that I'd like my rails app to access and display the contents.
How do I tell my rails app enter the Username, Password and then Submit?
The input elements in question are shown below...
Username:
<input name="ctl00$ContentPlaceHolder1$txtUserName" type="text" id="ctl00_ContentPlaceHolder1_txtUserName">
Password:
<input name="ctl00$ContentPlaceHolder1$txtPassword" type="password" id="ctl00_ContentPlaceHolder1_txtPassword">
Submit:
<input type="submit" name="ctl00$ContentPlaceHolder1$btnLogIn" value="Log In" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ContentPlaceHolder1$btnLogIn", "", true, "", "", false, false))" id="ctl00_ContentPlaceHolder1_btnLogIn">

j_spring_security_check redirect

I upgraded my application from 2.2.3 to 2.4.3. Now when I click submit on the login page, I see that the POST request to j_spring_security_check has status code 302.
Is there something I need to do after upgrading? I've tried running grails clean-all but that did not help.
I'm using this version: compile ':spring-security-core:2.0-RC3'
settings in config.groovy
grails.plugins.springsecurity.userLookup.userDomainClassName = 'com.aerstone.scanner.security.User'
grails.plugins.springsecurity.userLookup.authorityJoinClassName = 'com.aerstone.scanner.security.UserRole'
grails.plugins.springsecurity.authority.className = 'com.aerstone.scanner.security.Role'
GSP
<form action="${postUrl}" method="POST" id="loginForm" autocomplete="off">
<input type='text' name='j_username' id='username' placeholder="Username"/>
<input type='password' name='j_password' id='password' placeholder="Password"/>
<input type="submit" class="btn" value="Sign in" id="submit"/>
</form>
I had the same issue after an upgrade.
I changed the action of the login form by:
<form action='${ request.contextPath }/j_spring_security_check' method="POST">
Hope that helps
please note that the name had change in the config to be:
grails.plugin.springsecurity....
Notice 'plugin' vs 'plugins'. I've passed this problem but I'm getting invalid credentials all the time.

phpCAS::isAuthenticated returning false after login in different service

I've configured the CAS login page so that it accepts the username and password as GET parameters and if these are provided, it submits the login form automatically. This looks as the CAS login page is not even touched during authentication from the website.
The website is using phpCAS version 1.3.2 to communicate with CAS. If I log in directly through the form, It works as expected: the browser gets redirected back from CAS correctly and isAuthenticated() returns true. However if I log in to a different service beforehand, isAuthenticated() returns false. If I'm not mistaken this is because I have to do an actual check with CAS if the auth is fine, therefore I've also tried checkAuthentication(), but I get the following errors:
[error] [client 192.168.12.120] PHP Fatal error: Uncaught exception 'CAS_AuthenticationException' in /home/dev/www/CAS-1.3.2/CAS/Client.php:2248
Stack trace:
#0 /home/dev/www/CAS-1.3.2/CAS/Client.php(1227): CAS_Client->_validatePGT('https://192.168...', '????<cas:servic...', Object(DOMElement))
#1 /home/dev/www/CAS-1.3.2/CAS/Client.php(1131): CAS_Client->isAuthenticated()
#2 /home/dev/www/CAS-1.3.2/CAS.php(1078): CAS_Client->checkAuthentication()
#3 /home/dev/www/redir.php(39): phpCAS::checkAuthentication()
#4 {main}
thrown in /home/dev/www/CAS-1.3.2/CAS/Client.php on line 2248, referer: https://192.168.10.144:8181/cas/login?username=myUser&password=testpassword&auto=true&service=https%3A%2F%2F192.168.12.120%2Fredir.php
CAS server log
phpCAS debug log
PHP Code:
<?php
function pageURL() {
$PROTOCOL = "http";
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$PROTOCOL = "https";
}
$url = "$PROTOCOL://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url = strtok($url, '?');
return $url;
}
// Configuration
$phpcas_path = "CAS-1.3.2";
$cas_host = "192.168.10.144";
$cas_port = 8181;
$cas_context = "/cas";
// Load the CAS lib
require_once $phpcas_path . "/CAS.php";
// Enable debugging
phpCAS::setDebug ();
// Initialize phpCAS
phpCAS::proxy ( CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context );
phpCAS::setNoCasServerValidation ();
// check CAS authentication
$auth = phpCAS::checkAuthentication();
// logout if desired
if (isset ( $_REQUEST ['logout'] )) {
phpCAS::logout ();
}
$serviceUrl = "https://192.168.10.144:8181/accessrights/";
?>
<html>
<head>
<title>CAS form login</title>
</head>
<body>
<?php if ($auth) {
phpCAS::serviceWeb($serviceUrl, $err_code, $accessrights);
?>
<p>Hello <strong><?php echo phpCAS::getUser(); ?></strong>! You have been authenticated with CAS. Your access rights are: <?php echo $accessrights; ?></p>
<?php } else { ?>
<h3>User login</h3>
<div>Enter your username and password here in order to log in on the website:</div>
<!-- ###LOGIN_FORM### -->
<form method="GET" action="https://192.168.10.144:8181/cas/">
<p>Username : <input type="text" name="username" /></p>
<p>Password : <input type="password" name="password" /></p>
<p>Remember me : <input type="checkbox" name="rememberMe" value="true" /></p>
<p><input type="submit" value="Login !" /></p>
<input type="hidden" name="auto" value="true" />
<input type="hidden" name="service" value="<?php echo pageURL(); ?>" />
</form>
<!-- ###LOGIN_FORM### -->
<?php } ?>
</body>
</html>
I see that checkAuthentication() fails to retrieve a Proxy Granting Ticket, but I have no clue about the reason. Any ideas? I also have a page with forceAuthentication(), and it works flawlessly.
According to your server's log, CAS is trying to callback your application via "https://xxx.xx.xx.xx/redir.php" but his encounter an SSL issue "TicketCreationException: error.authentication.credentials.bad"

Node.js/Express form post req.body not working

I'm using express and having trouble getting form data from the bodyParser. No matter what I do it always comes up as an empty object. Here is my express generated app.js code (the only thing I added was the app.post route at the bottom):
var express = require('express');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', function(req, res){
res.sendfile('./public/index.html');
});
app.post('/', function(req, res){
console.log(req.body);
res.sendfile('./public/index.html');
});
app.listen(3010);
Here is my HTML form:
<!doctype html>
<html>
<body>
<form id="myform" action="/" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" id="mytext" />
<input type="submit" id="mysubmit" />
</form>
</body>
</html>
When I submit the form, req.body is an empty object {}
Its worth noting that this happens even if I remove the enctype attribute from the form tag
...Is there something I am missing/doing wrong?
I am using node v0.4.11 and express v2.4.6
<form id="myform" action="/" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="I_appear_in_req_body" id="mytext" />
<input type="submit" id="mysubmit" />
</form>
The body of a HTTP post is a key/value hash of all the form controls with a name attribute, and the value is the value of the control.
You need to give names to all your inputs.
It also due to content type. please see console.log(req) object.
'content-type': 'application/json; charset=UTF-8’ // valid.
'content-type': 'application/JSON; charset=UTF-8’ // invalid & req.body would empty object {}.
To check content type by console.log(req.is('json')) // return true/false
I think 'charset=UTF-8' is negligible in above.
If your form looks like this
<form action="/", method="post">
<label for="for_name">Name: </label>
<input id="for_name" type="text" name="user_name"/>
<button type="submit">Submit</button>
</form>
And if you are using the following line of code
app.use(express.json());
then the req.body will be empty because it only parses req with content-type application/json but the default value of request originating from element is application/x-www-form-urlencoded. Hence the following line of code will solve the issue
app.use(express.urlencoded({ extended: true }));
My first StackOverflow contribution. Yay!!

Resources