grails spring security custom user registration page - grails

I'm trying to create an app that uses Spring security core 2.0 and I'm trying to create a custom registration page. I think that my problem is in my register.gsp because everytime I try to register a new user it redirects to http://localhost:8080/home/register which is completely blank. Further evidence that this might be the case is that I included several println()s in my register action that should fire off depending on where the registration fails but none of them fire off at any time. Also, there are no users created in dbconsole. Please take a look at my gsp:
<html>
<head>
<meta name="layout" content="front"/>
<title>MSK | Register</title>
<style>
...
</style>
</head>
<body>
<div class="jumbotron">
<form action="${postUrl ?: '/home/register'}" method="POST" id="registerForm" class="cssform" autocomplete="off">
<h2 class="form-signin-heading">Please register</h2>
<label for="username" class="sr-only">Username</label>
<input style="margin-bottom: 10px" type="text" id="username" class="form-control" placeholder="Username" name="${usernameParameter ?: 'j_username'}"/>
<label for="email" class="sr-only">Email</label>
<input style="margin-bottom: 10px" type="email" id="email" class="form-control" placeholder="Email" name="${emailParameter ?: 'email'}"/>
<label for="fName" class="sr-only">First Name</label>
<input style="margin-bottom: 10px" type="text" id="FName" class="form-control" placeholder="First Name" name="${fNameParameter ?: 'fName'}"/>
<label for="lName" class="sr-only">Last Name</label>
<input style="margin-bottom: 10px" type="text" id="lName" class="form-control" placeholder="Last Name" name="${lNameParameter ?: 'lName'}"/>
<label for="password" class="sr-only">Password</label>
<input style="margin-bottom: 10px" type="password" id="password" class="form-control" placeholder="Password" name="${passwordParameter ?: 'j_password'}"/>
<label for="confirmPassword" class="sr-only">Confirm Password</label>
<input style="margin-bottom: 10px" type="password" id="confirmPassword" class="form-control" placeholder="Confirm Password" name="${passwordCParameter ?: 'confirmPassword'}"/>
<g:actionSubmit style="margin-top: 20px" class="btn btn-lg btn-success btn-block" action="register" value="create"/>
<button style="margin-top: 20px" class="btn btn-lg btn-success btn-block" type="submit">Register</button>
</form>
</div>
</body>
Here is the controller and action, if that helps:
package com.mypackage
class HomeController {
def springSecurityService
//many actions
def register(){
switch(request.getMethod()){
case 'POST':
withForm {
if(params.username && params.email && params.fName && params.lName && params.password && params.confirmPassword){
if(params.password == params.confirmPassword){
def userRole = new Role(authority: 'ROLE_USER', name: 'User').save(flush: true)
def newUser = User.findByUsername(params.id)
if(!newUser){
newUser.username = params.username
newUser.email = params.email
newUser.fName = params.fName
newUser.lName = params.lName
newUser.password = params.password
newUser.enabled = true
newUser.accountExpired = false
newUser.accountLocked = false
newUser.passwordExpired = false
newUser.authorities ?: userRole
if(loginService.register(newUser)){
flash.message = "Your account has been created. Welcome " + newUser.fName
flash.message_type = 'success'
redirect(controller: 'login', action: 'auth')
}else{
flash.message = "Unable to create your account. Please try again later"
flash.message_type = 'danger'
redirect(action: 'register')
println("saving user")
}
}else{
flash.message = "That username has already been taken. Please choose a new username."
flash.message_type = 'danger'
println("checking username")
}
}else{
flash.message = "Your passwords don't match. Please try again"
flash.message_type = 'danger'
println("matching passwords")
}
}else {
flash.message = "Please fill out all required fields"
flash.message_type = 'danger'
println("filling out fields")
}
}
break;
case 'GET':
break;
println("POSTing form")
}
}
And here's the loginService's code too:
com.mypackage
//imports
#Transactional
class LoginService {
def register(newUser){
try{
def userRole = new Role(authority: 'ROLE_USER', name: 'User').save(flush: true)
newUser.save(flush: true, failOnError: true)
UserRole.create(newUser, userRole, true)
return true
}catch(all){
all.printStackTrace()
return false
}
}
}
My apologies if all the code isn't properly indented, I basically copied and pasted out of my actual project. Any help will be appreciated, thank you!

you can use the spring-security-ui plugin
use command-object, which validate the password
use resources, that means do a post to /user, that will call the save action

Related

'IndexModel' does not contain a public instance or extension definition for 'GetEnumerator'

Let me preface by saying that I am new to C# and CSHTML. I created a data entry form that is supposed to post the info submitted into a SQL DB and show the list of data in a new page. I'm stuck on the following error. Any Help would be greatly appreciated
CS1579 foreach statement cannot operate on variables of type 'IndexModel' because 'IndexModel' does not contain a public instance or extension definition for 'GetEnumerator'
#page
#model sUAS_WebApp.Pages.IndexModel
#{
ViewData["Title"] = "sUAS Request Form";
}
#if (Model.errorMessage.Length > 0)
{
<div class='alert alert-warning alert-dismissible fade show' role='alert'>
<strong>#Model.errorMessage</strong>
<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='close'></button>
</div>
}
#foreach (var data in Model)
{
<form method="POST">
<div class="container" style="border: 1px solid lightgrey;">
<div class="col-100">
<div class="row">
<div class="row">
<div class="col-50">
<label for="Date">Date</label>
<input type="text" id="Date" name="Date" class="form-control" placeholder="01-JAN-2022" value="#data.sRequest.Date" />
<div class="row">
<div class="col-50">
<label for="RD">RD#</label>
<input type="text" id="RD" name="RD" class="form-control" placeholder="AB000000" value="#data.sRequest.RD" />
</div>
<div class="col-50">
<label for="EV">EV#</label>
<input type="text" id="EV" name="EV" class="form-control" placeholder="00000" value="#data.sRequest.EV" />
</div>
</div>
</div>
</div>
<label for="Requestor">Requestor</label>
<input type="text" id="Requestor" name="Requestor" class="form-control col-95" placeholder="Name / Star" value="#data.sRequest.Requestor" />
<label for="Location">Location</label>
<input type="text" id="Location" name="Location" class="form-control col-95" placeholder="542 W. 15th Street" value="#data.sRequest.Location" />
<div class="row">
<div class="col-50">
<label for="Unit_Piloting_Drone">Unit Piloting Drone</label>
<select id="Unit_Piloting_Drone" class="form-control" name="Unit_Piloting_Drone" value="#data.sRequest.Unit_Piloting_Drone">
<option value="select1"> </option>
<option value="techlab">TechLab</option>
<option value="maiu">auditor</option>
<option value="other">Forensics</option>
</select>
</div>
<div class="col-50">
<label for="Upload">Upload</label>
<select id="Upload" class="form-control" name="Upload" value="#data.sRequest.Upload">
<option value="select2"> </option>
<option value="UpYes">Yes</option>
<option value="UpNo">No</option>
</select>
</div>
<div class="col-50">
<label for="Evidence_com_ID">ID</label>
<input type="text" id="ID" name="ID" class="form-control" placeholder="Evidence.com ID" value="#data.sRequest.ID" />
</div>
<div class="col-50">
<label for="Refused">Refused</label>
<select id="Refused" class="form-control" name="Refused" value="#data.sRequest.Refused">
<option value="select3"> </option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
</div>
<label for="Call_Recieved_By"> Call Received By</label>
<input type="text" id="Call_Recieved_By" name="Call_Recieved_By" class="form-control" placeholder="Name / Star" value="#data.sRequest.Call_Recieved_By" />
<div class="col-95">
<label for="Refusal_Circumstances">Refusal Circumstances</label>
<textarea id="Refusal_Circumstances" name="Refusal_Circumstances" class="form-control" placeholder="Wind Gusts Over 30mph" style="height:200px" value="#data.sRequest.Refusal_Circumstances"></textarea>
</div>
<input type="submit" value="Submit" class="btn">
</div>
</div>
</div>
</form>
}
#if (Model.successMessage.Length > 0)
{
<div class='alert alert-warning alert-dismissible fade show' role='alert'>
<strong>#Model.successMessage</strong>
<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='close'></button>
</div>
}
<br />
<br />
<br />
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Data.SqlClient;
namespace sUAS_WebApp.Pages
{
public class IndexModel : PageModel
{
public sUASData sRequest = new sUASData();
public String errorMessage = "";
public String successMessage = "";
public void OnGet()
{
}
public void OnPost()
{
sRequest.Date = Request.Form["Date"];
sRequest.RD = Request.Form["RD"];
sRequest.EV = Request.Form["EV"];
sRequest.Requestor = Request.Form["Requestor"];
sRequest.Location = Request.Form["Location"];
sRequest.Call_Recieved_By = Request.Form["Call_Recieved_By"];
sRequest.Unit_Piloting_Drone = Request.Form["Unit_Piloting_Drone"];
sRequest.Refused = Request.Form["Refused"];
sRequest.Refusal_Circumstances = Request.Form["Refusal_Circumstances"];
sRequest.Upload = Request.Form["Upload"];
sRequest.ID = Request.Form["ID"];
if ((sRequest.Date.Length == 0 || sRequest.Requestor.Length == 0 || sRequest.Location.Length == 0 || sRequest.Call_Recieved_By.Length == 0 || sRequest.Unit_Piloting_Drone.Length == 0 || sRequest.Refused.Length == 0 || sRequest.Upload.Length == 0))
{
errorMessage = "Please fill in all required fields";
return;
}
//save the new request to the database
try
{
String connectionString = "Data Source=.\\sqlexpress;Initial Catalog=sUASDatabase;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "INSERT INTO sUAS" +
"(Date, RD, EV, Requestor, Location, Call_Recieved_By, Unit_Piloting_Drone, Refused, Refusal_Circumstances, Upload, ID) VALUES " +
"(#Date, #RD, #EV, #Requestor, #Location, #Call_Recieved_By, #Unit_Piloting_Drone, #Refused, #Refusal_Circumstances, #Upload, #ID);";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#Date", sRequest.Date);
command.Parameters.AddWithValue("#RD", sRequest.RD);
command.Parameters.AddWithValue("#EV", sRequest.EV);
command.Parameters.AddWithValue("#Requestor", sRequest.Requestor);
command.Parameters.AddWithValue("#Location", sRequest.Location);
command.Parameters.AddWithValue("#Call_Recieved_By", sRequest.Call_Recieved_By);
command.Parameters.AddWithValue("#Unit_Piloting_Drone", sRequest.Unit_Piloting_Drone);
command.Parameters.AddWithValue("#Refused", sRequest.Refused);
command.Parameters.AddWithValue("#Refusal_Circumstances", sRequest.Refusal_Circumstances);
command.Parameters.AddWithValue("#Upload", sRequest.Upload);
command.Parameters.AddWithValue("#ID", sRequest.ID);
command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
errorMessage = ex.Message;
return;
}
sRequest.Date = ""; sRequest.Requestor = ""; sRequest.Location = ""; sRequest.Call_Recieved_By = ""; sRequest.Unit_Piloting_Drone = ""; sRequest.Refused = ""; sRequest.Upload = "";
successMessage = "Request Successfully Entered";
Response.Redirect("/RequestData");
}
}
}
Thanks

groovy.lang.MissingMethodException new1.EmployeeController.findByUsername()

I was trying to make a signup page, which takes the username and password as from the user and stores it in my database, but the problem here is, the data is not going to the database only
you can see the image here
[https://drive.google.com/file/d/0B9gjSzsLSnClR1VvU0RUa3liRWs/view?usp=sharing][1]
save method look likes this
#Transactional
def save(){
if(params == null){
redirect(action:"index")
flash.message=''
return
}
def employee = findByUsername(params.username);
System.out.println(employee.username);
if(employee!=null){
flash.message="username already exist"
render(view:"signup")
}
else{
def newEmp = new Employee();
newEmp.username=params.username
newEmp.password=params.password
if(newEmp.save(flush:true)){
flash.message="Employee created"
render(view:"index")
}
else{
flash.message="Please enter valid data"
render(view:"signup")
}
if(newEmp.save(flush:true)) {
flash.message = "User Created. Please Login"
render(view:"index")
} else {
flash.message = "Please enter valid data";
render(view:"signup")
}
}
}
View page look like this
<form id="signupform" action="./save" method="POST" class="form-horizontal" role="form">
<g:if test="${flash.message}">
<div class="alert alert-danger" role="alert">${flash.message}</div>
</g:if>
<div class="form-group">
<label for="username" class="col-md-3 control-label">Username</label>
<div class="col-md-9">
<input type="text" class="form-control" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-md-3 control-label">Password</label>
<div class="col-md-9">
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<!-- Button -->
<div class="col-md-offset-3 col-md-9 text-center">
<button id="btn-signup" type="submit" class="btn btn-info"><i class="icon-hand-right"></i>Sign Up</button>
</div>
</div>
</form>
Replace this:
def employee = findByUsername(params.username);
with:
def employee = Employee.findByUsername(params.username);
All dynamic finder methods must be called statically on the type you expect them to return

button cannot trigger in mvc 4

I am having some trouble in ASP.NET MVC4 - When I click the Login button it's not hitting my controller and not logging in
This is the code on my .cshtml
#using System.Linq
<body>
<div class="container">
#using (Html.BeginForm("Login", "Login", FormMethod.Post, new { #Class = "form-signin", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "Login failed. Check your login details.")
<img class="img-responsive" src="~/Images/PI%20Logo.jpg" />
#Html.TextBoxFor(m => m.userName, new {#Class = "form-control", #Id = "user", #placeholder = "Username"})
#Html.ValidationMessageFor(m => m.userName)
#Html.PasswordFor(p => p.passwd, new {#Class = "form-control", #Id = "pass", #placeholder = "Password"})
#Html.ValidationMessageFor(m => m.passwd)
<!--<input class="form-control" id="username" placeholder="Username" type="text" />
<input class="form-control" id="Password1" placeholder="Password" type="password" /> -->
<input id="submit" class="btn btn-lg btn-primary btn-block" type="button" value="LOGIN" />
}
</div>
<script src="~/Scripts/jquery-1.11.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
</body>
and this is my controller
public class LoginController : Controller
{
//
// GET: /Login/
public ActionResult Login()
{
return View();
}
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Login(Login login)
{
AccountManagement am = new AccountManagement();
var xrm = new XrmServiceContext("Xrm");
SystemUser sysUser = xrm.SystemUserSet.Where(x => x.DomainName == "hc\\" + login.userName && x.IsDisabled == false).FirstOrDefault();
if (am.ValidateCredentials(login.userName, login.passwd) == "True" && sysUser != null)
{
Session["username"] = login.userName;
return RedirectToAction("MainHome", "MainMenu");//Request.CreateResponse(HttpStatusCode.OK, new { Message = "Success", User = sysUser });
}
else
{
ModelState.AddModelError("", "Login data is incorrect!");//Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Username or Password Invalid");
}
return View(login);
}
}
What's wrong with my code - i'm so confused, because many tutorial made simple login like this but it's work
Change button type to submit
<input id="submit" class="btn btn-lg btn-primary btn-block" type="submit" value="LOGIN" />
Difference between input type Button & submit
<input type="button" />
buttons will not submit a form - they don't do anything by default. They're generally used in conjunction with JavaScript as part of an AJAX application.
<input type="submit">
buttons will submit the form they are in when the user clicks on them, unless you specify otherwise with JavaScript.

How do I link to database for verifying the username in forget password option

<input type="submit" value="Submit" onclick="" />
Trying to implement the 'Forgot Password' option, on this submit button, the username entered must check in to the database and return a message if :-
If username exists in DB, return message saying password has been reset and sent to your your registered email id.
This username does not exist.
How do I call the DB?
Using MVC4 Razor engine.
Thanks.
Code is here:-
#{
ViewBag.Title = "Forgot Password";
}
<h2>Forgot Password</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<fieldset>
<legend>Forgot Password Form</legend>
<ol>
<li>
#Html.Label("User Name", new { #for = "UserName" })
#Html.TextBox("UserName")
<span style="color:red;">#TempData["Message"]</span>
</li>
</ol>
<input type="submit" value="Submit" onclick="" />
</fieldset>
You can call your controller's action method using below code .
<input type="button" value="Reset Password" onclick="location.href='<%: Url.Action("Action", "Controller") %>'" />
Or you can send your UserName value on form submit.
// #using (Html.BeginForm("Hello","Home",FormMethod.Post))
#using (Html.BeginForm("Action","Controller"))
{
#Html.AntiForgeryToken()
<fieldset>
<legend>Forgot Password Form</legend>
<ol>
<li>
#Html.Label("User Name", new { #for = "UserName" })
#Html.TextBox("UserName")
<span style="color:red;">#TempData["Message"]</span>
</li>
</ol>
//<input type="submit" value="Submit" onclick="" />
<input type="submit" name="Check" value="Reset Password" />
</fieldset>
Controller :
public ActionResult Action(string name)
{
string dd = UserName.ToString();
// Do your call to db or other validation .
return View();
}

How to display wrong username password on login form ?

I am developing the MVC application.
I have designed the login form.
when user enters the proper username and password then, it redirect to next page, but when user put wrong username or password I want to display the message on the login form, how to do it.
This is the code of method in controller...
[HttpPost]
public ActionResult LoginUser(FormCollection oFormCollection)
{
string userName = oFormCollection["username"];
string password = oFormCollection["password"];
bool IsAccountPerson = false;
var validEmployee = (from e in db.Employees
where e.UserName == userName && e.Password == password
select e).ToList();
if (validEmployee.Count() == 1)
{
foreach (var v in validEmployee)
{
oEmployee = v;
Session["LoggedEmployee"] = oEmployee;
Session["loggedEmpId"] = oEmployee.Id;
if (oEmployee.DesignationType == "Account")
{
IsAccountPerson = true;
}
else
{
IsAccountPerson = false;
}
}
if(IsAccountPerson)
return RedirectToAction("PaymentAdviceListForAccounts", "Account");
else
return RedirectToAction("Index", "PaymentAdvice");
}
else
return PartialView("Index");
}
and this is my view Code....
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="#Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
<title></title>
</head>
#using (Html.BeginForm("LoginUser","Login",FormMethod.Post))
{
#*<div style="margin:15% 20% 20% 30%; width:35%;min-height:25%;border:1px #ACACAC solid;">*#
<div class="container-fluid" style="padding-left:0px; margin-top:165px; margin-left:140px;">
<div class ="span3">
<label style="font-size:15px; color:#666666; margin-top:5px;">Username</label>
</div>
<div class ="span6">
<input type="text" id="username" name="username" style="height:20px; width:100%;" />
</div>
<div class ="span3">
<label style="font-size:15px;color:#666666; margin-top:5px; ">Password</label>
</div>
<div class ="span6">
<input type="password" id="password" name="password" style="height:20px; width:100%;"/>
</div>
<div class="span6" style="padding-left:15px;">
<input type="submit" name="submit" value="Login" class="btn btn-primary" style="margin-right:10px; height:30px; font-size:14px; width:55px;" />
<input type="button" name="Login" value="Cancel" class="btn btn-primary" style="margin-right:20px; height:30px; font-size:14px; width:55px; padding-left:5px; padding-right:5px;" />
</div>
</div>
</div>
</div>
</div>
}
</body>
</html>
create new model or use TempData.
here is the example using TempData.
http://www.devcurry.com/2012/05/what-is-aspnet-mvc-tempdata.html

Resources