I am new to MVC. I am facing below problem.
I wrote all logic in model.In Web.config I mention path of file (No Connection string).
I am adding [Authorize] attribute. After login, it is navigating to Home page. When I navigate gift create page again redirect to login page (Recursive).
FYI: Temporarily I am using session variable to solve problem.
This is my code
[HttpPost]
[ActionName("Create")]
[Authorize]
public ActionResult CreateGift(GiftModel gif)
{
if (Session["UserType"] != null)
{
if (Session["UserType"].ToString() == "1")
return RedirectToAction("Index", "home");
}
else
{
return RedirectToAction("Login", "User");
}
string path = System.Configuration.ConfigurationManager.AppSettings["Path"];
if (ModelState.IsValid)
{
Gift InsertCoupon = new Gift(path);
InsertCoupon.InsertGift(gif);
return RedirectToAction("GiftList");
}
return View();
}
In Web.config
<add key="Path" value="D:\"/>
Login Page
public ActionResult Login(LoginModel user)
{
string path = System.Configuration.ConfigurationManager.AppSettings["Path"];
if(ModelState.IsValid)
{
Users LoginUser = new Users(path);
UserModel uM = new UserModel();
uM.Password = user.Password;
uM.User_Email_ID = user.User_Email_ID;
uM.Name = user.Name;
string res = LoginUser.LoginUser(uM);
uM = LoginUser.GetUserFrom_Email(user.User_Email_ID);
if (res != "")
ViewBag.Msg = res;
else
{
Session["username"] = uM.Name;
Session["E_Mail"] = uM.User_Email_ID;
Session["UserType"] = uM.User_Type;
if (uM.User_Type == 0)
return RedirectToAction("AdminHome", "Admin");
else
return RedirectToAction("Index", "Home");
}
}
return View();
}
Related
How to make login session in ASP.NET MVC? For example, when the system detects admin, it will go to page A, and when the system detects customer, it will go to page B. This is my current code, it is auto generate by Visual Studio with some adjustment from me. I would like to use below codes, but it is confusing on how to add login session
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
But in my previous project, I used this concept.
[HttpPost]
public ActionResult Login(User user)
{
if (ModelState.IsValidField("Email") && ModelState.IsValidField("Password"))
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["StoreContext"].ConnectionString);
SqlCommand cmd = new SqlCommand("spGetLoginData", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email", user.Email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
Object objUserid = dt.Rows[0]["UserId"];
Object objName = dt.Rows[0]["Name"];
Object objICpass = dt.Rows[0]["ICpass"];
Object objEmail = dt.Rows[0]["Email"];
Object objPassword = dt.Rows[0]["Password"];
Object objRole = dt.Rows[0]["Role"];
Object objDateRegistered = dt.Rows[0]["DateRegistered"];
string passwordEntered = user.Password;
string passwordFromDb = objPassword.ToString();
PBKDF2Hash PwdHash = new PBKDF2Hash(passwordEntered, passwordFromDb);
bool passwordCheck = PwdHash.PasswordCheck;
if (passwordCheck == true)
{
Session["UserId"] = objUserid.ToString();
Session["Name"] = objName.ToString();
Session["ICPass"] = objICpass.ToString();
Session["Email"] = objEmail.ToString();
Session["Password"] = objPassword.ToString();
Session["Role"] = objRole.ToString();
Session["DateRegistered"] = user.DateRegistered;
if (Session["Role"].ToString().Equals("user"))
{
return RedirectToAction("Index", "Home");
}
else if (Session["Role"].ToString().Equals("admin"))
{
return RedirectToAction("Index", "Users");
}
else
{
return View();
}
}
else
{
return View();
}
}
else
{
return View();
}
}
else
{
return View();
}
}
Can anyone help me?
You can assign roles in database.
Then do something like this:
if (roleid == "admin") {
return RedirectToAction("Index", "Admin");
}
else if (roleid == "user") {
return RedirectToAction("Index", "User");
}
I'm building an app for our company which needs to have separate database per client. App is for the usage of other multiple companies, so the app needs to identify the company name when the user logs in and make the users operate only within their company db. I have it all set, but the problem is that the app is not able to handle many different databases simultaneously. When users from more different companies log in, the first users db gets changed to the db of the second user who is logged in! This is of course unacceptable. How can I make the app to use many dbs simultaneously?
I have one database which collects all app users and their company names and separate databases for each company. I also have a standard asp below are my codes:
My applicatinon dbcontext is
public static string _DbName;
public ApplicationDbContext() : base(string.IsNullOrWhiteSpace(ConString.dbCatlogConn) ? "DefaultConnection" : ConString.dbCatlogConn, throwIfV1Schema: false)
{
this.Database.CommandTimeout = 600;
}
public ApplicationDbContext(string dbName) : base(dbName)
{
_DbName = dbName;
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
Login class and database initializer in account controller
if (!ModelState.IsValid)
{
return View(model);
}
var regx = new Regex("[-]");
if (!regx.IsMatch(userdash))
{
ViewBag.Message = "Error";
return View();
}
string x = model.UserName.ToLower();
Session["Initial"] = x.Split('-').First();
var dbcompanies = db.CompanyLists.Where(t => (t.InitializationLetters == Session["Initial"].ToString())).Select(t => new { ConnString = t.ConnectionString }).ToList();
if (dbcompanies.Count > 0)
{
if (dbcompanies[0].ConnString == "")
{
}
else
{
Session["ConnectionString"] = dbcompanies[0].ConnString;
}
}
else
{
ModelState.AddModelError("", language == "en" ? "Invalid login attempt." : "text here");
return View(model);
}
if (Session["ConnectionString"].ToString() == "" || Session["ConnectionString"].ToString() == null)
{
ViewBag.Message1 = "notfound";
return View();
}
else
{
using ( db = new ApplicationDbContext(Session["ConnectionString"].ToString()))
{
UserManager.PasswordHasher = new CustomPasswordHasher();
var user = db.Users.Where(e => e.UserName.ToLower() == model.UserName.ToLower()).FirstOrDefault();
var result = new SignInStatus();
if (user == null)
{
result = SignInStatus.Failure;
}
else
{
string dbPassword = dal.DecryptPassword(user.AnotherUsername, user.AnotherSalt, user.PasswordHash);
var status = UserManager.PasswordHasher.VerifyHashedPassword(dbPassword, model.Password);
if (status == PasswordVerificationResult.Success)
{
result = await SignInManager.PasswordSignInAsync(model.UserName, user.PasswordHash, model.RememberMe, shouldLockout: false);
}
else
result = SignInStatus.Failure;
}
switch (result)
{
case SignInStatus.Success:
if (user != null)
{
if (user.Disabled == true)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
ModelState.AddModelError("", language == "en" ? "Invalid login attempt." : "text");
return View(model);
//return View("Lockout");
}
else
{
var ip = Request.ServerVariables["REMOTE_ADDR"];
user.LastIpAddress = ip;
db.SaveChanges();
if (User.IsInRole(UsersTypes.Interview.ToString()))
{
return RedirectToRoute("profile", new { type = profile.Acceptance });
}
}
}
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", language == "en" ? "Invalid login attempt." : "error");
return View(model);
}
}
}
I have found the same problem here asp.net mvc multitenant database per tenant
when I run i got error DbName cant to be null where should I declare or pass the database connection for that variable and will it be the main database?
I have also used the string literal as one of the comments like this one
private const string DbName = "default app connection string";
but I got error It must be variable or indexer
can I find help for that problem
I have an issue with my asp.net MVC project, I am using cookies to persist user’s data
I use the following code to set cookie after successful login:
[HttpPost]
public ActionResult Index(string username,string password)
{
User user = db.Users.Where(t => t.username == username && t.password == password).SingleOrDefault();
if (user != null)
{
HttpCookie aCookie = new HttpCookie("cookie");
aCookie.Values["username"] = username;
aCookie.Values["role"] = user.role.ToString();
aCookie.Values["UserID"] = user.UserID.ToString();
aCookie.Values["route"] = "AdminReports";
aCookie.Secure = false;
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
isLogedIn = true;
return RedirectToAction("AdminReports", "Home");
}
TempData["ErrorMessage"] = "Wrong username or password!";
return View();
}
I Read the cookie using this code :
public ActionResult AdminReports()
{
Response.Write(Server.HtmlEncode(Request.Cookies["cookie"]["username"]));
// Response.Write(Request.Cookies["cookie"]["username"]);
if (Request.Cookies["cookie"] != null)
{
if (Convert.ToInt32(Request.Cookies["cookie"]["role"]) == (int)Enums.Role.Admin)
{
return View();
}
else if (Convert.ToInt32(Request.Cookies["cookie"]["role"]) == (int)Enums.Role.The70Hospitals)
{
return View("The70Hospitals");
}
else if (Convert.ToInt32(Request.Cookies["cookie"]["role"]) == (int)Enums.Role.The380Hospitals)
{
return View("The380Hospitals");
}
else
{
return View("LoginView");
}
}
else
{
return View("LoginView");
}
}
However the cookies lose its data which prevent the user to login. This case happens when I access the project remotely. However it works fine locally in the development mode and it runs normally also when I browse from the IIS (Run locally in the server)
Check your web.config file,
You can do some cookies settings in <system.web> section
<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />
use the System.Web.HttpCookie.HttpOnly property
Hope this helps.
On login I am just assigning values to session but after login it becomes null. I set the session timeout as well but still it doesn't work.
public ActionResult Login([Bind(Include = "Username, Password")] LoginModel loginModel, string ReturnUrl)
{
if (ModelState.IsValid)
{
Egov_Users eGov_Users = db.Egov_Users
.Where(p => p.UserType.Type != "O" && p.UserName == loginModel.Username)
.FirstOrDefault();
if (eGov_Users == null)
{
ModelState.AddModelError("", "Invalid username");
return View();
}
else
{
if (eGov_Users.Password != loginModel.Password)
{
ModelState.AddModelError("", "Invalid Password");
return View();
}
var loginDetail = new LoginDetails();
loginDetail.supplierID = (eGov_Users.SupplierID != null) ? eGov_Users.SupplierID.Value : 0;
loginDetail.userID = eGov_Users.UserId;
loginDetail.username = eGov_Users.UserName;
loginDetail.firstName = eGov_Users.FirstName;
loginDetail.lastName = eGov_Users.LastName;
Session["UserID"] = loginDetail.userID;
Session["SupplierID"] = loginDetail.supplierID;
Session["Username"] = loginDetail.username;
Session["DisplayName"] = loginDetail.firstName + " " + loginDetail.lastName;
if (string.IsNullOrEmpty(ReturnUrl))
{
return RedirectToAction("Index", "Users");
}
}
}
return RedirectToAction("Login", "Login");
}
In webconfig I have set the session timeout as well.
I am trying to set my session object into cookie, so that I might not have login repeatedly. My code is like this :
[HttpPost]
public ActionResult Login(UserAccount user , [Bind(Include = "ID,NameOfSession")] SessionSave Sessions)
{
using (QuestionsDBContext db = new QuestionsDBContext())
{
var usr = db.userAccount.Single(u => u.UserName == user.UserName && u.Password == user.Password);
Session["UserID"] = usr.UserID.ToString();
Session["Username"] = usr.UserName.ToString();
if (user != null)
{
bool userAutherised = true;
if (userAutherised)
{
//create the authentication ticket
var serializer = new JavaScriptSerializer();
string userData = serializer.Serialize(usr.UserName.ToString());
var authTicket = new FormsAuthenticationTicket(
1,
usr.UserName.ToString(), //user id
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
true, //true to remember
userData, //roles
FormsAuthentication.FormsCookiePath
);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
}
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Username or Password is wrong");
}
}
return View();
}
And my index action :
[Authorize]
public ActionResult Index(string sortOrder, string searchString, string currentFilter, int? page)
{
if (Response.Cookies["Username"] != null)
{
//code here
}
}
Somehow, this code is not working. Every time I go to index page, I have to go through login. Please someone make this clear.