I have simple login form without registration, because I create Admin login, who create new users. So admin login, and create new user, which can then login with that specific username and password.
So I create this controller:
public ActionResult CreateNew(Models.Users user)
{
if (ModelState.IsValid)
{
try
{
using (var dataU = new userDbEntities())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(user.Password);
var sysUser = dataU.UsersTables.Create();
sysUser.username = user.Username;
sysUser.password = encrpPass;
sysUser.passwordSalt = crypto.Salt;
sysUser.TimeZoneId = user.TimeZoneName;
sysUser.Customer = user.Customer;
dataU.UsersTables.Add(sysUser);
dataU.SaveChanges();
return RedirectToAction("Registration", "LoginAdmin");
}
}
catch (Exception ex)
{
string error = ex.Message;
}
}
return View(user);
}
Problem is, that I can create users with same username (this is not ok!), so how to check if user with that name exists and returns, this username already exists...
thanks...
count the number of user that has the same username and add the user if the count is 0.
for example
var count = dataU.UsersTables.Count(u=>u.UserName == usernameyouwanttocheck);
if(count==0)
{
//add user
}
else
{
//alert user saying user exists
}
if I were you I would make repository and create a function that checks if the user exists or not and call that function from controller.
By help of Biplov13 I create this, which is working:
public ActionResult CreateNew(Models.Users user)
{
if (ModelState.IsValid)
{
try
{
using (var dataU = new userDbEntities())
{
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(user.Password);
var sysUser = dataU.UsersTables.Create();
sysUser.username = user.Username;
sysUser.password = encrpPass;
sysUser.passwordSalt = crypto.Salt;
sysUser.TimeZoneId = user.TimeZoneName;
sysUser.Customer = user.Customer;
var count = dataU.UsersTables.Count(u => u.username == user.Username);
if (count == 0)
{
dataU.UsersTables.Add(sysUser);
dataU.SaveChanges();
return RedirectToAction("Registracija", "LoginAdmin");
}
else
{
// something to do if user exist...
}
}
}
}
catch (Exception ex)
{
string error = ex.Message;
}
}
return View(user);
}
Related
Current Umbraco Version - Umbraco version 7.5.3
We have an Umbraco Project that uses a Custom Membership Provider to authenticate members (front-end) to certain protected page(s). This membership provider has worked fine until we had to upgrade the system that our members are authenticated via. After upgrading the external system our Membership Provider now has a strange issue that I'm struggling to resolve. The issue is as follows:
1 - User attempts to login with their correct details (via Umbraco Login Form) and receives an 'Incorrect Username & Password Error'
2 - User then uses our 'Reset Password' functionality, which sends them a 'PIN' that they enter into an Umbraco Form. If the PIN matches, they're then presented with a Form to enter a new Password.
3 - The user is now able to log via the newly created Username & Password (into Umbraco Protected Areas).
4 - Now, the user goes to our External system and enters their username and password (created via the Umbraco Form). This also logs them in successfully. (This seems to change the password of the user?)
5 - User now tries to re-login to Umbraco Protected Page but again receives an incorrect Username & Password.
6 - However the Username and Password still works on the external system.
After some research we have come to the conclusion that our external system now seems to use a different Encryption method that Umbraco isn't compatible with?
I'm really struggling to figure out how/why this is now happening and what I need to change to ensure that the passwords both match and that the members can access the protected pages.
Here is what I believe is running the Login/Password Reset Logic:
namespace Profile.Controllers
{
[PluginController("Profile")]
public class SecurityController : SurfaceController
{
public string RandomString(int length)
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[length];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
return new String(stringChars);
}
[ChildActionOnly]
public ActionResult SecurityForm()
{
var model = new SecurityModel();
return PartialView("SecurityForm", model);
}
[HttpPost]
public ActionResult UpdateUsername(SecurityModel viewModel, FormCollection form)
{
iboAdmin.InitializeSystem();
try
{
CContactUser user = CContactUser.LoginByWebLogin(User.Identity.Name);
user.ChangeWebLogin(viewModel.ChangeUsername.NewUsername, viewModel.ChangeUsername.Password);
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
if (ModelState.IsValid)
{
TempData["SuccessMessage"] = "Your username has been changed successfully";
return RedirectToCurrentUmbracoPage();
}
else
{
return CurrentUmbracoPage();
}
}
[HttpPost]
public ActionResult UpdatePassword(SecurityModel viewModel, FormCollection form)
{
bool legacyCode = false;
try
{
if (legacyCode)
{
iboAdmin.InitializeSystem();
CContactUser user = CContactUser.LoginByWebLogin(User.Identity.Name);
user.ChangePassword(viewModel.ChangePassword.CurrentPassword, viewModel.ChangePassword.NewPassword);
}
else
{
if (!iboAdmin.IsSystemInitialized)
{
iboAdmin.InitializeSystem();
}
CContactUser user = CContactUser.LoginByWebLogin(User.Identity.Name);
var contact = new CContact(CStaffUser.GetDefaultStaffUser(), user.ContactId);
contact.UserSecurity.ChangePassword(viewModel.ChangePassword.CurrentPassword, User.Identity.Name, viewModel.ChangePassword.NewPassword);
contact.Save();
if (contact.ErrorsCount > 0)
ModelState.AddModelError("", "An error occured when setting the password: " + contact.Errors.PrimaryErrorMessage);
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
if (ModelState.IsValid)
{
TempData["SuccessMessage"] = "Your password has been changed successfully";
return RedirectToCurrentUmbracoPage();
}
else
{
return CurrentUmbracoPage();
}
}
[HttpPost]
public ActionResult LoginReminder(string Email)
{
iboAdmin.InitializeSystem();
try
{
CContactUser user = CContactUser.LoginByWebLogin("manager");
CContact contact = CContact.GetContacts(user, "", "AND Name.EMAIL = #email", new SqlParameter[] { new SqlParameter("email", Email) }).First();
string ksamHelpline = (ConfigurationManager.AppSettings.AllKeys.Contains("KSAMHelpline") ? ConfigurationManager.AppSettings["KSAMHelpline"] : "01625 664500");
if (contact == null)
{
throw new Exception("There are no users on our system with that e-mail address registered. Please contact the administration office on " + ksamHelpline + " to access your account.");
}
string userName = contact.UserSecurity.WebLoginId;
if(string.IsNullOrEmpty(userName))
{
throw new Exception("A username has not been found for your email address. Please contact the administration office on " + ksamHelpline + ".");
}
else
{
SmtpClient smtpClient = new SmtpClient();
MailMessage mail = new MailMessage();
string messageBody = System.IO.File.ReadAllText(Server.MapPath("~/emails/LoginReminder.html"));
HtmlDocument htmldoc = new HtmlDocument();
htmldoc.LoadHtml(messageBody);
mail.To.Add(new MailAddress(contact.EmailAddress));
mail.Subject = htmldoc.DocumentNode.SelectSingleNode("//head/title").InnerText;
messageBody = messageBody.Replace("[USERNAME]", userName);
mail.Body = messageBody.Replace("[FIRST_NAME]", contact.FirstName);
mail.IsBodyHtml = true;
smtpClient.Send(mail);
TempData["SuccessMessage"] = "A reminder e-mail containing your username has been sent to " + Email;
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
if (ModelState.IsValid)
{
return RedirectToCurrentUmbracoPage();
}
else
{
return CurrentUmbracoPage();
}
}
[HttpPost]
public ActionResult PasswordResetRequest(string username)
{
Session["ResetUser"] = "";
iboAdmin.InitializeSystem();
try
{
CContactUser user = CContactUser.LoginByWebLogin(username);
CContact contact = new CContact(user,user.ContactId);
if (contact.EmailAddress == "")
{
throw new Exception("There is no email address registered to that username. Please contact the administration office to access your account.");
}
Session["PIN"] = RandomString(5);
Session["ResetUser"] = username;
TempData["PINSent"] = true;
SmtpClient smtpClient = new SmtpClient();
MailMessage mail = new MailMessage();
string messageBody = System.IO.File.ReadAllText(Server.MapPath("~/emails/ResetPasswordPin.html"));
HtmlDocument htmldoc = new HtmlDocument();
htmldoc.LoadHtml(messageBody);
mail.To.Add(new MailAddress(contact.EmailAddress));
mail.Subject = htmldoc.DocumentNode.SelectSingleNode("//head/title").InnerText;
mail.Body = messageBody.Replace("[PIN]", Session["PIN"].ToString());
mail.IsBodyHtml = true;
smtpClient.Send(mail);
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
if (ModelState.IsValid)
{
return RedirectToCurrentUmbracoPage();
}
else
{
return CurrentUmbracoPage();
}
}
[HttpPost]
public ActionResult PasswordResetVerify(string PIN)
{
iboAdmin.InitializeSystem();
try
{
if (Session["PIN"].ToString() == PIN)
{
TempData["Verified"] = true;
}
else
{
throw new Exception("Verification codes do not match");
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
if (ModelState.IsValid)
{
return RedirectToCurrentUmbracoPage();
}
else
{
return CurrentUmbracoPage();
}
}
[HttpPost]
public ActionResult PasswordReset(string password)
{
iboAdmin.InitializeSystem();
try
{
CContact contact;
bool legacyCode = false, success = false;
if (legacyCode)
{
CContactUser user = CContactUser.LoginByWebLogin(Session["ResetUser"].ToString());
user.ChangePassword(password, "REMOVED", "REMOVED");
contact = new CContact(user, user.ContactId);
}
else
{
// Jeremy suggested code v1.
//
/*if (!iboAdmin.IsSystemInitialized)
{
iboAdmin.InitializeSystem();
}
CContactUser user = CContactUser.LoginByWebLogin(Session["ResetUser"].ToString());
contact = new CContact(user, user.ContactId);
contact.UserSecurity.ChangePassword(password, "REMOVED", "REMOVED");
contact.Save();
if (contact.ErrorsCount > 0)
ModelState.AddModelError("", "An error occured when setting the password: " + contact.Errors.PrimaryErrorMessage);*/
// Jeremy suggested code v2.
//
if (!iboAdmin.IsSystemInitialized)
{
iboAdmin.InitializeSystem();
}
CContactUser user = CContactUser.LoginByWebLogin(Session["ResetUser"].ToString());
contact = new CContact(CStaffUser.GetDefaultStaffUser(), user.ContactId);
var membershipUser = Membership.GetUser(contact.UserSecurity.WebLoginId, false);
string oldPassword = membershipUser.ResetPassword();
success = membershipUser.ChangePassword(oldPassword, password);
}
SmtpClient smtpClient = new SmtpClient();
MailMessage mail = new MailMessage();
string messageBody = System.IO.File.ReadAllText(Server.MapPath("~/emails/ResetPasswordSuccess.html"));
HtmlDocument htmldoc = new HtmlDocument();
htmldoc.LoadHtml(messageBody);
mail.To.Add(new MailAddress(contact.EmailAddress));
mail.Subject = htmldoc.DocumentNode.SelectSingleNode("//head/title").InnerText;
mail.Body = messageBody.Replace("[FIRST_NAME]", contact.FirstName);
mail.IsBodyHtml = true;
smtpClient.Send(mail);
TempData["Success"] = true;
TempData["SuccessMessage"] = "Your password has been reset successfully.";
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
if (ModelState.IsValid)
{
return RedirectToCurrentUmbracoPage();
}
else
{
return CurrentUmbracoPage();
}
}
}
}
Resolved.
Just needed to add:
hashAlgorithmType="SHA256"
Into Web Config.
I am trying to check if a booking record exists, then show its details. Otherwise return to Bookparking page but else part isn't working and shows Object reference not set to an instance of an object because there is no such field with the Session[""]
Controller:
public ActionResult Viewparking()
{
if (IsUserLoggedIn(Session, Request) == false)
{
return RedirectToAction("login");
}
else
{
String id = Session["username"].ToString();
ViewBag.userid = id;
var checkbooking = db.tb_booking.Where(s => s.username == id).FirstOrDefault();
if (checkbooking != null)
{
var show = db.tb_booking.Where(e => e.username == id).FirstOrDefault();
}
else
{ //ViewBag.f = "You have no booking yet!!";
return RedirectToAction("Bookparking", "user");
}
return View();
}
}
As Gabriel noted, you have not null checked the value from the session. Code would be something like this:
public ActionResult Viewparking()
{
if (IsUserLoggedIn(Session, Request) == false)
{
return RedirectToAction("login");
}
else
{
String id = Session["username"]?.ToString();
if (id != null)
{
ViewBag.userid = id;
var checkbooking = db.tb_booking.FirstOrDefault(s => s.username == id);
if (checkbooking != null)
{ // TODO: checkbooking is currently unused, except to check if you can fetch it.
return View();
}
}
// If you reach this code, then either id is null, or the booking was not found
return RedirectToAction("Bookparking", "user");
}
}
I want to implement my custom authorization, I wonder what is wrong with my code even I got the user credentials correctly it still redirects me to my Login Method, please see the code below
Edit: I have successfully implemented the Authorize Attribute with Roles, for future readers please see code below
Login Controller
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login (AdminViewModels.Login viewModel, string returnURL)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
PasswordHasher passwordVerify = new PasswordHasher();
var query = (from acc in db.accounts.Where(x => x.username == viewModel.Username)
select new { acc.username, acc.password}).FirstOrDefault();
if (query != null)
{
if (ModelState.IsValid)
{
var result = passwordVerify.VerifyHashedPassword(query.password, viewModel.Password);
switch (result)
{
case PasswordVerificationResult.Success:
//set forms ticket to be use in global.asax
SetupFormsAuthTicket(viewModel.Username, viewModel.rememeberMe);
return RedirectToLocal(returnURL);
case PasswordVerificationResult.Failed:
ModelState.AddModelError("", "Wrong Username or Password");
return View(viewModel);
}
}
}
return View(viewModel);
}
Forms Auth Ticket
private account SetupFormsAuthTicket(string userName, bool persistanceFlag)
{
account user = new account();
var userId = user.id;
var userData = userId.ToString(CultureInfo.InvariantCulture);
var authTicket = new FormsAuthenticationTicket(1, //version
userName, // user name
DateTime.Now, //creation
DateTime.Now.AddMinutes(20), //Expiration
persistanceFlag, //Persistent
userData);
var encTicket = FormsAuthentication.Encrypt(authTicket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
return user;
}
Global.asax
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
//take out user name from cookies
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string[] roles = null;
trainingEntities db = new trainingEntities();
//query database to get user roles
var query = (from acc in db.account_roles where acc.account.username == username select acc.role.role_name).ToArray();
roles = query;
//Let us set the Pricipal with our user specific details
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles);
}
catch (Exception)
{
//somehting went wrong
}
}
}
}
Now you can use [Authorize(Roles = "Admin")]
to any action method or on top of controller
I have successfully implemented the Authorize Attribute with Roles, for future readers please see code below.
Login Controller
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login (AdminViewModels.Login viewModel, string returnURL)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
PasswordHasher passwordVerify = new PasswordHasher();
var query = (from acc in db.accounts.Where(x => x.username == viewModel.Username)
select new { acc.username, acc.password}).FirstOrDefault();
if (query != null)
{
if (ModelState.IsValid)
{
var result = passwordVerify.VerifyHashedPassword(query.password, viewModel.Password);
switch (result)
{
case PasswordVerificationResult.Success:
//set forms ticket to be use in global.asax
SetupFormsAuthTicket(viewModel.Username, viewModel.rememeberMe);
return RedirectToLocal(returnURL);
case PasswordVerificationResult.Failed:
ModelState.AddModelError("", "Wrong Username or Password");
return View(viewModel);
}
}
}
return View(viewModel);
}
FormsAuthTicket
private account SetupFormsAuthTicket(string userName, bool persistanceFlag)
{
account user = new account();
var userId = user.id;
var userData = userId.ToString(CultureInfo.InvariantCulture);
var authTicket = new FormsAuthenticationTicket(1, //version
userName, // user name
DateTime.Now, //creation
DateTime.Now.AddMinutes(20), //Expiration
persistanceFlag, //Persistent
userData);
var encTicket = FormsAuthentication.Encrypt(authTicket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
return user;
}
Global.asax
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
//take out user name from cookies
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string[] roles = null;
trainingEntities db = new trainingEntities();
//query database to get user roles
var query = (from acc in db.account_roles where acc.account.username == username select acc.role.role_name).ToArray();
roles = query;
//Let us set the Pricipal with our user specific details
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles);
}
catch (Exception)
{
//somehting went wrong
}
}
}
}
Now you can use [Authorize(Roles = "Admin")]
to any action method or on top of controller
as I see in ControllerLogin attribute it is now being applied in a variable, when it should be applied to a method or a class
[CustomAuthorization(UserRole="Admin")]
// GET: Manage
private trainingEntities db = new trainingEntities();
public ActionResult Index()
{
return View();
}
Private trainingEntities dB = new TrainingEntities();
[CustomAuthorization(UserRole="Admin")]
Public ActionResult Index()
{
//yourcode
}
I have a need to override authorize attribute.
Basically if its an ajax request and the user is not logged in or is not in specified roles then i want to return a JSON. The JSON will tell the caller the reason as not logged in or not in role and needs to return the redirect to url. In case of not signed it, it also needs to give back ReturnUrl.
If its not an ajax request then i want the default processing by Authorize attribute to kick in.
We are using forms authentication and the sign in url and error pages are specified in the web.config file.
Following is my take at it but i am not getting the following right
missing roles processing in case of an ajax request
in case of not an ajax request (else block), i am redirecting the user to the sign in page. i want the default autorize attribute to kickin in this case
I just need the push in the right direction... tutorial or a blog pointer is all i need to learn and accomplish this....
public class AuthorizePartnerProgramsAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
HttpContext httpContext = HttpContext.Current;
var url = new UrlHelper(filterContext.RequestContext);
var request = filterContext.HttpContext.Request;
if (request.IsAuthenticated == false)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
if (request.Url != null)
filterContext.Result = CommonUtilities.AddJsonUtf8Encoding(new JsonResult { Data = new { error = true, singinerror = true, message = "Sign in required!", returnUrl = request.UrlReferrer.AbsolutePath.ToString() } });
else
filterContext.Result = CommonUtilities.AddJsonUtf8Encoding(new JsonResult { Data = new { error = true, singinerror = true, message = "Sign in required!" } });
}
else
{
if (request.UrlReferrer != null)
{
filterContext.Result = new RedirectResult(url.Action("Index", "SignIn", new { Area = "Account", ReturnUrl = filterContext.RequestContext.HttpContext.Request.UrlReferrer.AbsolutePath.ToString() }));
}
else
{
filterContext.Result = new RedirectResult(url.Action("Index", "SignIn", new { Area = "Account"}));
}
}
}
}
}
Here is my second stab at it. I think i am now more confused than before and need help setting it up properly
public class AuthorizeCustomAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var request = filterContext.RequestContext.HttpContext.Request;
if (request.IsAjaxRequest())
{
var url = new UrlHelper(filterContext.RequestContext);
var urlReferer = request.UrlReferrer != null
? request.UrlReferrer.ToString()
: String.Empty;
var signInUrl = url.Action("Index", "SignIn", new { Area = "Account", ReturnUrl = urlReferer });
var accessDeniedUrl = url.Action("PageAccessDenied", "Error", new { Area = "" });
if (!request.IsAuthenticated)
{
//not authenticated
filterContext.Result =
CommonUtilities.AddJsonUtf8Encoding(new JsonResult
{
Data =
new {error = true, singinerror = true, message = "Sign in required!", url = signInUrl},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
});
}
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.Request.IsAjaxRequest())
{
//Use [AuthorizeCustom(Roles="MyRole1,MyRole2")]
//or [AuthorizeCustom]
//roles may not have been applied here
//checking authentication will be done by the HandleUnauthorizedRequest?????
//if no roles are specified then it is true = so give access to the resource
//user may have multiple roles or single role assigned, check and if not in role then return json back.
//....
}
else
{
return base.AuthorizeCore(httpContext);
}
}
}
This helped me setting up mine
http://www.dotnet-tricks.com/Tutorial/mvc/G54G220114-Custom-Authentication-and-Authorization-in-ASP.NET-MVC.html
use
[AuthorizeCustom(Roles = RoleNames.Admin)]
Here is the full working attribute for me without any cleanup.
public class AuthorizeCustomAttribute : AuthorizeAttribute
{
#region CONSTANTS
public const string SectionStemFuture = "StemFuture";
#endregion
#region PROPERTIES
private string Section { get; set; }
#endregion
#region Constructor
public AuthorizeCustomAttribute()
{
Section = String.Empty;
}
public AuthorizeCustomAttribute(string section)
{
Section = section;
}
#endregion
#region Overrides
public override void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
var url = new UrlHelper(filterContext.RequestContext);
/*
var urlReferer = request.UrlReferrer != null
? request.UrlReferrer.ToString()
: String.Empty;
*/
var urlReferer = request.Url.PathAndQuery;
var signInUrl = url.Action("Index", "SignIn", new { Area = "Account", ReturnUrl = urlReferer });
var accessDeniedUrl = url.Action("PageAccessDenied", "Error", new { Area = "" });
//overwrite the default sign in URL according to the section
if (!String.IsNullOrWhiteSpace(Section))
{
switch (Section)
{
case SectionStemFuture:
signInUrl = url.Action("Index", "StemFutureHome", new { Area = "StemFuture", ReturnUrl = urlReferer });
break;
}
}
if (!request.IsAuthenticated)
{
//not authenticated
if (request.IsAjaxRequest())
{
filterContext.Result =
CommonUtilities.AddJsonUtf8Encoding(new JsonResult
{
Data =
new {error = true, signinerror = true, message = "Sign in required", url = signInUrl},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
});
}
else
{
//this is not an ajax request
if (!String.IsNullOrWhiteSpace(Section))
{
filterContext.Result = new RedirectResult(signInUrl);
}
else
{
//let the base authorization take care of it
base.OnAuthorization(filterContext);
}
}
}
else if (!String.IsNullOrWhiteSpace(base.Roles))
{
var isRoleError = true;
var rolesAllowed = base.Roles.Split(',');
//authenticated and we have some roles to check against
var user = filterContext.HttpContext.User;
if (user != null && rolesAllowed.Any())
{
foreach (var role in rolesAllowed)
{
if (user.IsInRole(role))
{
isRoleError = false;
}
}
}
if (isRoleError)
{
if (request.IsAjaxRequest())
{
filterContext.Result =
CommonUtilities.AddJsonUtf8Encoding(new JsonResult
{
Data =
new
{
error = true,
signinerror = true,
message = "Access denied",
url = accessDeniedUrl
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
});
}
else
{
//here we will need to pass to the access denied
filterContext.Result = new RedirectResult(accessDeniedUrl);
}
}
}
}
#endregion
}
I am trying to insert datas to Appointment table of my database. I did registration part of my project which works well. There are 2 tables, Patient and Appointment. After Login patients can make an appointment. Patient number comes like this
MyUser.PatientNo = Guid.NewGuid().GetHashCode();
For appointment date and description comes from textbox. And I want to insert PatientNo from Patient table to Appointment table. For me it looks done but when I choose date and write description but I got error on this line app.PatientNo = patient.PatientNo;
An exception of type 'System.NullReferenceException' occurred in DentAppSys.dll but was not handled in user code
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Make(Models.AppModel User)
{
if (Session["UserEmail"] != null)
{
using (var db = new MaindbModelDataContext())
{
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
var app = new Appointment();
app.Date = User.Date;
app.Description = User.Description;
app.Status = "true";
app.PatientNo = patient.PatientNo;
db.Appointments.InsertOnSubmit(app);
db.SubmitChanges();
return RedirectToAction("Make", "Appointment");
}
}
else
{
return RedirectToAction("Index", "User");
}
}
}
}
and this is registration part which is working well
public ActionResult RegAndLogin(Models.RegAndLog User)
{
if (User.RegisterModel != null)
{
if (ModelState.IsValid)
{
using (var db = new MaindbModelDataContext())
{
var Person = db.Patients.FirstOrDefault(u => u.Email == User.RegisterModel.Email);
if (Person == null)
{
string Hash = BCrypt.Net.BCrypt.HashPassword(User.RegisterModel.Password);
var MyUser = new Patient();
MyUser.Name = User.RegisterModel.Firstname;
MyUser.Surname = User.RegisterModel.Lastname;
MyUser.Birthday = User.RegisterModel.Birthday;
MyUser.Email = User.RegisterModel.Email;
MyUser.Password = Hash;
MyUser.PatientNo = Guid.NewGuid().GetHashCode();
db.Patients.InsertOnSubmit(MyUser);
db.SubmitChanges();
Session["UserEmail"] = User.RegisterModel.Email;
return RedirectToAction("Index", "Patient", User.RegisterModel);
}
else
{
ModelState.AddModelError("", "There is a user with this Email. Please enter another Email !!!");
return View();
}
}
}
else
{
ModelState.AddModelError("", "Data is incorrect !!!");
}
}
else
{
if (ModelState.IsValid && IsValid(User.LoginModel.Email, User.LoginModel.Password))
{
var TempUser = new Models.RegisterModel();
Session["UserEmail"] = User.LoginModel.Email;
using (var db = new MaindbModelDataContext())
{
var person = db.Patients.FirstOrDefault(u => u.Email == User.LoginModel.Email);
TempUser.Firstname = person.Name;
TempUser.Lastname = person.Surname;
//TempUser.RegisterModel.Birthday = (DateTime)person.BirthDate;
TempUser.Email = person.Email;
}
return RedirectToAction("Index", "Patient", TempUser);
}
else
{
ModelState.AddModelError("", "Check your E-mail or Password then try again !!!");
}
}
return View();
If you're getting a null exception on the line
app.PatientNo = patient.PatientNo;
It will be because either app or patient are null at when it's executed. I would suspect patient.
Check that patient is found correctly at the line
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
if it isn't found patient will be null.