I'm trying to learn out Cro (and Perl6 simultaneously) ;)
My study app is based on the documentation of Cro. I added some authentication which does work, but the user session gets forgotten immediately.
You can check out the code at https://gitlab.com/ecocode/beaverapp
go to the login pasge and login with "user" and "pwd". You get rerouted to / (which indicates the login succeeded), but the message there is "Current user: -". So the session gets lost.
The relevant part of Routes.pm6 :
class UserSession does Cro::HTTP::Auth {
has $.username is rw;
method logged-in() {
defined $!username;
}
}
my $routes = route {
subset LoggedIn of UserSession where *.logged-in;
get -> UserSession $s {
content 'text/html', "Current user: {$s.logged-in ?? $s.username !! '-'}";
}
get -> LoggedIn $user, 'users-only' {
content 'text/html', "Secret page just for *YOU*, $user.username()";
}
get -> 'login' {
content 'text/html', q:to/HTML/;
<form method="POST" action="/login">
<div>
Username: <input type="text" name="username" />
</div>
<div>
Password: <input type="password" name="password" />
</div>
<input type="submit" value="Log In" />
</form>
HTML
}
post -> UserSession $user, 'login' {
request-body -> (:$username, :$password, *%) {
if valid-user-pass($username, $password) {
$user.username = $username;
redirect '/', :see-other;
}
else {
content 'text/html', "Bad username/password";
}
}
}
sub valid-user-pass($username, $password) {
# Call a database or similar here
return $username eq 'user' && $password eq 'pwd';
}
}
sub routes(Beaverapp $beaverapp) is export {
route {
# Apply middleware, then delegate to the routes.
before Cro::HTTP::Session::InMemory[UserSession].new;
delegate <*> => $routes;
}
}
I think the problem is due to the middleware session management not working. How should I correct this? Or maybe the problem is due to something else?
The behavior you saw was indeed caused by a bug in cookie-treatment inside of HTTP/2 stack.
As for now, the bug is fixed and the code in OP post works.
After discussion on cro irc channel, this problem only appears when using https 2. So the code above is correct.
Related
HomeController.cs:
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(LoginInfo login)
{
if (Request.Form["Submit"] != null)
{
string Username = login.Username;
string Password = login.Password;
ViewBag.Massage = "";
if (Username == "Admin" && Password == "123")
{
ViewBag.Massage = "Login Successfull";
return RedirectToAction("MSISDN","UnSub");
}
else
{
ViewBag.Massage = "Please Enter Valid Login Information";
}
}
return View();
}
Views/Home/Index.cshtml
<form name="myForm" action="/Home/Index" method="post">
<div align="center">
<div style="color:red">#ViewBag.Massage</div>
<br>
<label for="Username">Username:</label>
<input type="text" name="Username" id="Username">
<label for="Password">Password:</label>
<input type="password" name="Password" id="Password">
<br>
<input type="submit" name="Submit"value="Submit">
</div>
</form>
This code is works perfectly in my localhost. But when I publishe my project to IIS Server it is not working. It is returning -
Server Error: 404 File or Directory Not Found.
May be it conflicts with my physical path and requested path. How to resolve this problem?? :(
The action's url in the form tag may be wrong :
If the url for display and post the data is the same, you can remove action="/Home/Index"
If you want to specify the url, please use action="#Url.Action("Index")"
It will automatically resolve the Url.
My Code is working properly after using an tilde (~) sign before action.
For example:
action="~/Home/Index"
After using this sign my code works properly. It reduce the conflicts between virtual path and physical path.
Hi how do you post the login error message within the originating page where the user was attempting to login ?
Below I was able to stay on the current page if user login successfully but for login error it will obviously just go to the logonprocess page and display the error message.
Sorry that I remove a lot of validation below as the codes can really be very long.
Index.php
<?php
//set the session cookie parameter
ini_set("session.save_path", "sessionData");
session_start();
?>
<?php
if (!isset($_SESSION['uName'])) { ?>
<form method="post" action="logonProcess.php">
<div>Username <input type="text" name="userName" placeholder="Username"></div>
<div>Password <input type="password" name="pwd" placeholder="Password"></div>
<div><input type="submit" value="Logon"></div>
</form>
<?php } else { }?>
<?php
if (isset($_SESSION['uName'])) {
$username = $_SESSION['uName'];
echo "<p>Welcome $username</p>\n";
?>
Logout</br></br>
LogonProcess.php
$loginerror = array();
if (empty($username)) {
$loginerror[] = "You have not entered all of the required fields";
}
elseif (strlen($passWD) < 8) {
$loginerror[] = "You have not entered all of the required fields";
}
if (!empty($loginerror))
for ($a=0;$a<count($loginerror);$a++)
{
echo "$loginerror[$a] <br />\n";
}
else
if (mysqli_stmt_fetch($stmt))
{
if (password_verify($passWD, $passWDHash))
{
$_SESSION['uName'] = $username;
echo "<p>Login successful</p>";
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
else
{
echo "<p>Please try to login again</p>";
}
why dont you put ur login error in $_SESSION["login_error"] and check in ur origin page if the session exits show the error then destroy the session after it.
I want delete my model via post , but I always get Invalid Request
this is my view
<?php
echo CHtml::link(CHtml::encode('Delete image'), array('gambar/delete', 'id' => $data->id), array(
'submit' => array('data/delete', 'id' => $data->id),
'class' => 'delete', 'confirm' => 'This will remove the image. Are you sure?'
)
);
?>
and this is my action in GambarController
public function actionDelete() {
if (Yii::app()->request->isPostRequest) {
// we only allow deletion via POST request
$this->loadModel()->delete();
if (!isset($_GET['ajax']))
$this->redirect(array('index'));
}
else
throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
}
But I always get Invalid Request, I have read some forums, but I cannot get it. Anyone can help me ?
In most cases you can not use link (<a>) to POST. Instead, use the <form> like this
<form action="<?php echo $this->createUrl('/gambar/delete/'.$model->id);?>" method="post">
<button
type="submit"
name="id"
value="<?php echo $model->id?>"
onclick="if (!confirm('Are you sure to delete this image?')) return false;">
<i class="icon-white icon-trash"></i> Delete
</button>
</form>
You are using CHtml::link, this will generate an html <a> tag. When you click on a <a>, your browser send HTTP GET request(not POST request) to the server. So if(Yii::app()->request->isPostRequest) is always false and therefore you see Invalid request error. You should remove this condition from the action. Also, $this->loadModel()->delete() is invalid, because loadModel get an id as parameter. So $this->loadModel($_GET['id'])->delete() is correct.
Use the below code
$this->loadModel(primarykey, 'TableName')->delete();
Should work!
I believe I followed the steps in the book exactly, but cannot get the user to be logged in even if I supply the credentials in the array manually.
Could someone take a look below and see where I went wrong?
There is a table called users which was created using Migrations earlier and a row with the email = 'test#test.com' and password = 'test'.
Thanks so much.
routes.php
Route::any('login', 'auth#login');
controllers/auth.php
class Auth_Controller extends Base_Controller
{
public function get_login()
{
return View::make('auth.login');
}
public function post_login()
{
$credentials = array(
'username' => Input::get('email'),
'password' => Input::get('password')
);
if(Auth::attempt($credentials))
{
return "User has been logged in.";
}
else
{
//return Redirect::back()->with_input();
return "User has not been logged in.";
}
}
}
auth/login.blade.php
{{ Form::open() }}
Email: {{ Form::text('email', Input::old('email')) }} <br />
Password: {{ Form::password('password') }} <br />
{{ Form::submit('Login') }}
{{ Form::close() }}
config/auth.php
'driver' => 'eloquent',
'username' => 'email',
'password' => 'password',
'model' => 'User',
'table' => 'users',
models/user.php
class User extends Eloquent
{
}
AndrewB from the Laravel forum answered this:
Ok, the built in authentication expects the password to be hashed -
you can create a hash using Hash::make('mypassword') and put the
result into your database, then you should be able to login.
#AndrewB, that did it. The example in the book did not use Hash, but
when I added your suggestion to the post_update function to edit the
user, that worked.
THANKS.
I see you are using restful controllers "get_login() & post_login()" but you've not declared it as restful. You'll need to add the property to your "user" controller
class Auth_Controller extends Base_Controller
{
public $restful = true;
...
You can also add it to the base controller
If you are working from the same tutorial as i am "Laravel Starter by Shawn McCool" then he mentions this on page no 19
class Base_Controller extends Controller
{
public $restful = true;
....
My (copy & paste) code works b.t.w. :-)
Make sure field username actually stores email address.
I have a problem in getting the logged in user in my spring-extjs application.I am using spring security 2.0.4.Here are the details of what i have tried.
Controller class:
#RequestMapping(value="/StaffingApplication/index.action", method = RequestMethod.GET)
public String printUser(ModelMap model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
System.out.println(name);
model.addAttribute("username", name);
return "index.jsp";
}
login.js file
var login = new Ext.FormPanel({
labelWidth:80,
url:'j_spring_security_check',
frame:true,
title:'Please Login',
defaultType:'textfield',
width:300,
height:130,
monitorValid:true,
// Specific attributes for the text fields for username / password.
// The "name" attribute defines the name of variables sent to the server.
items:[{
fieldLabel:'Username',
name:'j_username',
allowBlank:false
},{
fieldLabel:'Password',
name:'j_password',
inputType:'password',
allowBlank:false
}],
// All the magic happens after the user clicks the button
buttons:[{
text:'Login',
formBind: true,
// Function that fires when user clicks the button
handler:function(){
login.getForm().submit({
method:'POST',
// Functions that fire (success or failure) when the server responds.
// The server would actually respond with valid JSON,
// something like: response.write "{ success: true}" or
// response.write "{ success: false, errors: { reason: 'Login failed. Try again.' }}"
// depending on the logic contained within your server script.
// If a success occurs, the user is notified with an alert messagebox,
// and when they click "OK", they are redirected to whatever page
// you define as redirect.
success:function(){
Ext.Msg.alert('Status', 'Login Successful!', function(btn, text){
if (btn == 'ok'){
window.location = 'index.action';
}
});
},
// Failure function, see comment above re: success and failure.
// You can see here, if login fails, it throws a messagebox
// at the user telling him / her as much.
failure:function(form, action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Login Failed!', obj.errors.reason);
}else{
Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText);
//window.location='loginFailure.html'+action.response.responseText;
}
login.getForm().reset();
}
});
}
}]
});
On my jsp page I access it like this.
<div id="header" class="header">Options Staffing Application
<div style="" id="user-status">
<a href='<c:url value="j_spring_security_logout"/>'>Logout</a>
<h3>Username : ${username}</h3>
</div>
</div>
But I just get a blank in place of username.
When I try to print it in the controller I get the value printed,but doesn't seem to be displayed on the jsp page.Went throgh other threads but did not help.Any help would be appreciated
Thanks for the time
Sachin
You don't need to put the username into an object model because you can access it from a jsp just like the way you do in the controller class:
<h3>Username <%=SecurityContextHolder.getContext().getAuthentication().getName(); =></h3>
Or even better:
<h3>Username <sec:authentication property="name" /></h3>
But i'm not sure if you can use that taglib in Spring Security 2