I just wrote this, but I am not realy happy with that. I think there is an easier way to do this. First I am checking if a user has an ID (from a portal we are using, it is in the header). After that I have to check if the user exists in my application, if not a user will be created, if the user exists, the datetime lastlogon will be updated.
(here is my first problem, CheckIfUserExists always returns true, except on an Exception, is this ok?). After that I am checking if userExists is true. If a user is created it has to be unblocked by an admin. If this happened the user can access the page.
If the user is in Role Admin, Viewbag is true otherwise false. If userExists is false, he is getting the default error.
I think my chain of thought is realy complicated.
public ActionResult Index()
{
bool userExists = false;
if (HelperClass.UserId != "")
userExists = CheckIfUserExists(HelperClass.UserId);
else
return RedirectToAction("AccessDenied", "Error");
if (userExists)
{
bool unblocked = CheckIfUnblocked(HelperClass.UserId);
if (unblocked)
{
if (User.IsInRole("Admin"))
ViewBag.Admin = true;
else
ViewBag.Admin = false;
return View("Index");
}
return RedirectToAction("AccessDenied", "Error");
}
else
{
return RedirectToAction("Index", "Error");
}
}
EDIT: Adding Code
public bool CheckIfUserExists(string u_gvid)
{
try
{
using (NpgsqlConnection con = new NpgsqlConnection(_Connection))
{
con.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.Connection = con;
//qry check if user exists
var result = cmd.ExecuteScalar().ToString().ToLower();
if (result == "false")
{
return CreateUser(HelperClass.UserId, HelperClass.Name);
}
else
{
//Update lastlogonn time
//qry
cmd.ExecuteScalar();
return true;
}
}
}
}
catch (NpgsqlException ex)
{
//log
RedirectToAction("DatabaseError", "Error");
}
catch (Exception ex)
{
//log
RedirectToAction("Index", "Error");
}
return false;
}
public bool CheckIfUnblocked(string u_gvid)
{
try
{
using (NpgsqlConnection con = new NpgsqlConnection(_Connection))
{
con.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
//qry "SELECT unblocked FROM tbl.users WHERE uid = @uid";
var result = (bool)cmd.ExecuteScalar();
if (result)
return true;
else
return false;
}
}
}
catch (NpgsqlException ex)
{
//log
RedirectToAction("DatabaseError", "Error");
}
catch (Exception ex)
{
//log
RedirectToAction("Index", "Error");
}
return false;
}