I'm trying to make a website using asp.net mvc 4 & Entity Framework 6 & the database is SQL Server 2012. I have a column in UserPassword table where all the passwords are encrypted like this, D1-24-0F-FB-16-AA-A9-CB-50-22-18-8D-E4-AF-59-CA. I want to use these datas for login in the website. I've tried but not working.
This is my code:
Controller
public class HomeController : Controller
{
abncodbEntities db = new abncodbEntities();
[HttpPost]
public ActionResult Login(UserPassword id)
{
if (ModelState.IsValid)
{
var uservar = db.UserPasswords.Where(a => a.UserId.Equals(id.UserId) && a.Password.Equals(id.Password)).FirstOrDefault();
if (uservar != null)
{
Session["UserBOID"] = uservar.UserId.ToString();
return RedirectToAction("UserLogin");
}
}
return View(id);
}
}
View
#model ABCoLtd.Models.UserPassword
using (Html.BeginForm("Login", "Home", FormMethod.Post)) {
#Html.ValidationSummary(true)
<div class="editor-label">
<strong>Enter your ID</strong>
</div>
<div class="editor-field">
#Html.TextBoxFor(a => a.UserId)
#Html.ValidationMessageFor(a => a.UserId)
</div>
<div class="editor-label">
<strong>Password</strong>
</div>
<div class="editor-field">
#Html.TextBoxFor(a => a.Password)
#Html.ValidationMessageFor(a => a.Password)
</div><br />
<p><input type="submit" class="btn btn-info" value="Login" /></p>
}
If I only try with ID then it works but not working with password. How can I use the passwords for login? I'm new in this situation. Any help would be appreciated. Thanks.
Related
I'm new to MVC so I hope to get help regarding my question. I am making users upload images. the image path will store in the database but the image itself will store in the Content folder. The code is working fine (which means there is no error) but I don't get the wanted result. I appreciate your help. Thanks in advance.
Here is the Controller code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "EmployeeId,EmpName,EmpEmail,Poition,Nationality,Last_W_D,EmpHOD,Password,DepId,SignaturePath,DoctorCategory")] Tbl_Employee tbl_Employee, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if(file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Content/Images/Employees/") + file.FileName);
tbl_Employee.SignaturePath = file.FileName;
}
db.Tbl_Employee.Add(tbl_Employee);
db.SaveChanges();
return RedirectToAction("Index");
}
Here is the "Create view " code:
#model ClearanceFirst.Models.Tbl_Employee
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "Tbl_Employee", null, FormMethod.Post, new { enctype = "
multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Tbl_Employee</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.SignaturePath, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input id="signaturePath " title ="upload images " type="file" name="file" />
#Html.ValidationMessageFor(model => model.SignaturePath, "", new { #class = "text-danger" })
</div>
</div>
Here is the "Index view" code:
<td>
#if (!string.IsNullOrWhiteSpace(item.SignaturePath))
{
<img width = "70" height = "50"
src="~/Content/Images/Employees/#Url.Content(item.SignaturePath)"
alt= "Alternate Text"/> }
</td>
The uploaded Images will be converted to Binary format then saved to SQL Server Database table.
Check the below given links for more information, how to upload and retrieve Images from Sql Server in ASP.NET MVC,
Save and Retrieve Image from SQL Server Database in ASP.Net MVC.
Store an Image URL in database and use it in ASP.NET MVC.
I'm building a web API and I want to consume it through an MVC view. The API controller is to insert the user data and the MVC controller is to create the view. I have been looking for information and this is what I have been able to do with that information.
So, the API controller, simply inserts the data to the database through an stored procedure, I've tested with Postman and works fine:
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpPost]
public IActionResult post(Models.Request.UserModel model)
{
using (Models.AdminOrchardContext db = new Models.AdminOrchardContext())
{
Models.UserModel oUsuar = new Models.UserModel();
Models.OrchardTable tOrchard = new Models.OrchardTable();
oUsuar.Name = model.Name;
oUsuar.Email = model.Email;
tOrchard.OrchardLocation = model.OrchardLocation;
var uName = new SqlParameter("#name", oUsuar.Name);
var uEmail = new SqlParameter("#email", oUsuar.Email);
var hOrchardLocation = new SqlParameter("#OrchardLocation", tOrchard.OrchardLocation);
var idUserReg = db.Usuarios.FromSqlRaw("Exec UserAndOrchardInsert #name, #email" +
"#OrchardLocation",
new[] { uName, uEmail, hOrchardLocation});
db.SaveChanges();
}
return Ok();
}
}
The MVC controller where the view is added, from here the API is used with the user data on the view:
[HttpPost]
public IActionResult post(Models.Request.User model)
{
HttpClient hc = new HttpClient();
hc.BaseAddress = new Uri("https://localhost:44325/api/User");
var addRecToDB = hc.PostAsJsonAsync<Models.Request.User>("User", model);
addRecToDB.Wait();
ViewBag.message = "Ok!";
return View();
}
And the view:
#model Huerbog.Models.Request.User
#{
ViewData["Title"] = "post";
}
<h1>User registration</h1>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<h4>Orchard-related field</h4>
<div class="form-group">
<label asp-for="OrchardLocation" class="control-label"></label>
<input asp-for="OrchardLocation" class="form-control" />
<span asp-validation-for="OrchardLocation" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
<h4>#ViewBag.message</h4>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Now, the problem is that when I open the view, even when the API is running, on the page appears the Error 405, I don't know what or where exactly is the error.
the problem is that when I open the view, even when the API is running, on the page appears the Error 405, I don't know what or where exactly is the error.
Please note that your action post contains the [HttpPost] attribute, which constrains matching to HTTP Post request(s) only.
While you enter URL to access https://xxx/controller_name/post from browser side, browser would help make HTTP Get request to server, which cause 405 Method Not Allowed error.
To fix it, you can try to add a HttpGet post method to make the endpoint support HTTP Get method request(s), like below.
[HttpGet]
public IActionResult post()
{
return View();
}
[HttpPost]
public IActionResult post(Models.Request.User model)
{
//...
I am Getting null value in action method when i am pass data from angular js to action method. i debug and see it hit to the AddCutomer method but data is null(the server responded with a status of 500 (Internal Server Error). can anyone help me to fix this issue
Admin.js
var app = angular.module("adminmdl", [])
app.controller("admincontroller", function ($scope, AdminService) {
$scope.Action = 'Add';
GetAllCustomer();
function GetAllCustomer() {
var getcust = AdminService.getCustomer();
getcust.then(function (cust) {
$scope.customers = cust.data;
}, function () {
alert('Error');
});
}
$scope.data = {
cus_code: '',
cus_name: ''
}
$scope.savecu = function () {
AdminService.saveCustomerDdetails($scope.cusmodel).then(function (d) {
$scope.msg = "Insert Successfully";
});
}
})
.service('AdminService', function ($http) {
this.getCustomer = function () {
return $http.get('GetCustomer');
}
this.saveCustomerDdetails = function (customer) {
return $http.post('/AddCutomer', customer);
}
})
ASP.NET MVC
[HttpPost]
public JsonResult AddCutomer(Customer customer) {
te.Customers.Add(customer);
te.SaveChanges();
string message = "Success";
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
html code
<form class="form-horizontal" method="post" ng-submit="savecu()" name="basic_validate" id="basic_validate" novalidate="novalidate">
<div class="control-group">
<label class="control-label">Customer Code</label>
<div class="controls">
<input type="text" ng-model="cusmodel.Customercode" name="required" id="required" >
</div>
</div>
<div class="control-group">
<label class="control-label">Customer Name</label>
<div class="controls">
<input type="text" ng-model="cusmodel.Customername" name="name" id="name" >
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Save" ng-click="savecu()" class="btn btn-success">
<input type="submit" value="Clear" class="btn btn-success" />
</div>
</div>
<div class="control-group">
<div class="controls">
<p style="color:green">{{msg}}</p>
</div>
</div>
#*<div class="form-actions">
</div>*#
</form>
Ok, so this is your autogenerated class
public partial class Customer
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.??Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Customer()
{
this.projects = new HashSet<project>();
}
public string cus_code { get; set; }
public string cus_name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.??Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<project> projects { get; set; }
}
The first issue I see is that your client object that you post to the server doesn't match the class definition.
Change the ng-models to cusmodel.cus_code and cusmodel.cus_name
<div class="control-group">
<label class="control-label">Customer Code</label>
<div class="controls">
<input type="text" ng-model="cusmodel.cus_code" name="required" id="required" >
</div>
</div>
<div class="control-group">
<label class="control-label">Customer Name</label>
<div class="controls">
<input type="text" ng-model="cusmodel.cus_name" name="name" id="name" >
</div>
</div>
The names in the scope model need to match the class specification else the json deserializer don't know what to do here.
Try to make a new post when these changes are added and see if the values of the cus_code and cus_name is populated.
If this doesn't work I would use a data transfer object to handle the communication with the client instead. Populating autogenerated classes from EF(or what orm you use) from the client can be a mess.
Add this class:
public class CustomerDTO
{
public string cus_code { get; set; }
public string cus_name { get; set; }
}
And use it in the controller method
[HttpPost]
public JsonResult AddCutomer(CustomerDTO customer) {
var cust = new Customer{ cus_code = customer.cus_code, cus_name = customer.cus_name };
te.Customers.Add(cust);
te.SaveChanges();
string message = "Success";
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
I am trying to migrate my demo project to Angular as I am learning the same. But I faced a dilemma as whether to opt for a razor view form validation while adding or rather updating some info on the client side
or to opt for Angular JS ?
So In Angular How would I achieve the same.
Suppose I have a _AddDetails.cshtml partial view :
#model MvcApplication4.Models.Student
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend><strong>Create a record</strong></legend>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DepartmentID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DepartmentID)
#Html.ValidationMessageFor(model => model.DepartmentID)
</div>
<p>
<input type="submit" class="createDetails" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
and in MVC I have opted for FluentValidation of the model.
The model looks like :
[FluentValidation.Attributes.Validator(typeof(StudentViewModelValidator))]
public class Student
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int StudentId { get; set; }
public String LastName { get; set; }
public String FirstName { get; set; }
public String UserName { get; set; }
public String Password { get; set; }
[ForeignKey("Department")]
public int DepartmentID { get; set; }
//Department Navigational Property
public Department Department { get; set; }
}
And the validation looks like :
public class StudentViewModelValidator : AbstractValidator<Student>
{
public StudentViewModelValidator()
{
RuleFor(m => m.FirstName)
.NotEmpty().WithMessage("First Name is required.")
.Matches(#"^\D*$").WithMessage("Numbers are not allowed in First Name");
RuleFor(m => m.LastName)
.NotEmpty().WithMessage("Last Name is required.")
.Matches(#"^\D*$").WithMessage("Numbers are not allowed in Last Name");
RuleFor(m => m.UserName)
.NotEmpty().WithMessage("User Name is required.")
.Matches(#"^[a-zA-Z0-9\.\$]*$").WithMessage("Only . and $ are allowed special characters in a user name");
RuleFor(m => m.Password)
.NotEmpty().WithMessage("Password is required.")
.Length(4, 10).WithMessage("Password should be 4 to 10 characters long")
.Matches(#"^(?=(\D*\d){2,})(?=([^a-zA-Z]*[a-zA-Z]))(?=[^\.\$\~\&]*[\.\$\~\&]).*").WithMessage("Password should contain at least 2 digits,a letter and at least a special character in it");
}
But in angular if I re-build my view instead of this razor template how would I achieve these sort of complex regex validations ?
I know I have something like
ng-required
ng-minlength
ng-maxlength
But how would I achieve like the above razor validations?
Use can use ng-pattern for regex
<script>
angular.module('ngPatternExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.regex = '\\d+';
}]);
</script>
<div ng-controller="ExampleController">
<form name="form">
<label for="regex">Set a pattern (regex string): </label>
<input type="text" ng-model="regex" id="regex" />
<br>
<label for="input">This input is restricted by the current pattern: </label>
<input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
<hr>
input valid? = <code>{{form.input.$valid}}</code><br>
model = <code>{{model}}</code>
</form>
</div>
Reference :
https://docs.angularjs.org/api/ng/directive/ngPattern
I implemented the validation in my MVC project that uses angular, so I used the ng-pattern, I had a problem trying to include some special chars as valid for the user name: "#", "_" and "-".
The only way I succeed was to add them as separate repeatable chars at the end of my pattern:
ng-pattern="/^[a-zA-Z0-9.]*[#('_')]*[#('-')]*[#('#')]*$/"
I hope this works for you.
I have created a login function. At the moment when correct login details are entered it logs in the employee and if inaccurate details are entered shows error message. Issue is if a employee enters a correct username but wrong case it still logs in the employee. For example, if there is a employee in the database with username "admin", if I enter username as "ADMIN" or "Admin" with correct password in login, it will still log in the employee. My code is as follows:
employeesController:
<?php
class EmployeesController extends AppController {
//some code here
public function login()
{
$username=$this->request->data['username'];
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
$passwordHasher = new SimplePasswordHasher();
$password = $passwordHasher->hash($this->request->data['password']);
$msg = $this->Employee->authenticateUser($username,$password);
if($msg)
{
foreach ($msg as $userdetails)
{
$usertype=$userdetails['Employee']['access_level'];//either admin or staff
}
//set session variables to limit authority
$this->Session->write(array('User' => array(
'usertype' => $usertype
)));
$this->render("../Pages/index1");
$this->layout = '../Pages/index1';
}
else{
$this->set('error',$username);
$this->render("../Pages/home"); //login page is the home page
$this->layout = '../Pages/home';
}
}
}
home.ctp:
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["username"].value;
var y=document.forms["myForm"]["password"].value;
if (x==null || x=="")
{
alert("Please Enter Username")
return false;
}
if (y==null || y=="")
{
alert("Please Enter Password")
return false;
}
}
</script>
</head>
<div class="users form">
<br>
<br>
<br>
<form name="myForm" action="Employees/login" onsubmit="return validateForm()" method="post" >
<?php
if (isset($error)) {
echo "<p style='color:red;font-size: 20px''>Username or Password is invalid. Please try again.</p>";
}?>
<p>Enter Username:
<input type="text" name="username" placeholder="username" style="height: 25px;width: 160px;"/></p>
<br><br>
<p>Enter Password:
<input type="password" name="password" placeholder="password" style="height: 25px;width: 160px;"/></p>
<br>
<input type="submit" style="height:35px;width:100px;font-size: 18px; align:center;" value="Sign in">
</form>
</div>
Can someone please help? I want only the exact username to be able to log in.
regardless the framework you are using this problem depends on th charset of your DB.
Problably you are using an *_ci charset (case insensitive).
Also *_cs (case sensitive) charset exists if you really need it.