Security model and existing database - security

I have created a database with code first and DbContext.
However this sit separately to the security model database on a new MVC 4 site.
My question is how do i combine my existing database with the security model or should they be kept separate for a valid reason
For example is this the best solution
http://blog.spontaneouspublicity.com/including-asp-net-simple-membership-tables-as-part-of-your-entity-framework-model
This would recreate the security model and roles when i first ran the application.
Or is there an alternative way of doing this.

I love the new MVC and Simplemembership Provider for this reason. You can very easily combine your models with the asp.net account models.
When you use the default internet template it creates a context called UsersContext. To do something simple like add additional fields to a UserProfile object to track in the database you need to do 3 simple things.
Add the properties to the model (in the account models if you use the default template)
In the register action on the account controller, add the new fields IE:
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
var db = new UsersContext();
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { FirstName = model.FirstName, LastName = model.LastName, Address = model.Address, Company = model.Company, Phone = model.Phone, Country = model.Country, City = model.City, State = model.State, Zip = model.Zip });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Dashboard");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Note the new keyword where I took values from the model passed and just matched them up to the model. (model binding may or may not work here but I haven't tested that yet)
3) Change the register View and model to pass all the info needed
I almost cried when this worked flawlessly the first time with no strange errors.
Good luck

Related

CS1646 Keyword, identifier, or string expected after verbatim specifier: #

tables in my EntityFramework model are events, eventtypes, subevents, subeventtypes
using the MVC5 builders (right click on controllers, add, add controller) I created controllers and views for the last three tables without issue however when I create the controller and views for the events entity I produce the following errors
Keyword, identifier, or string expected after verbatim specifier: #
'EventType' is a type, which is not valid in the given context
the code that was generated in the event controller is
{
private Entities db = new Entities();
// GET: Events
public ActionResult Index()
{
var events = db.Events.Include(# => #.EventType); ERROR HERE
return View(events.ToList());
}
any help with this issue would be greatly appreciated
TIA
I experienced the same issue when using the "MVC Controller with views, using Entity Framework" template.
var #group = await _context.Groups
.Include(# => #.Company)
.FirstOrDefaultAsync(m => m.GroupId == id);
My workaround was simple to replace the # symbol with another character i.e. g
var #group = await _context.Groups
.Include(g => g.Company)
.FirstOrDefaultAsync(m => m.GroupId == id);

Create a Custom Login page for logged in Users with Mvc5 Identity?

I am trying to find a guide or something that can teach me to make a view that users navigate to when they login. The view should show profile properties like firstname,lastname, and additional custom data. The problem is I dont know how to send the id from login to a another view. In other words when this succeeds in AccountController...
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
// return RedirectToAction("Customer", "Account");
... I want to send id to another view. I tried make a view like so:
public ActionResult Customer(string userId)
{
ApplicationDbContext _context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
var ThisUser = UserManager.FindById(User.Identity.GetUserId());
//string a = Convert.ToString(User.Identity.GetUserId());
//RegisterViewModel RVM = db.RegisterViewModels.Find(a);
return View(ThisUser);
}
It did not work. Any suggestions?
There is a lot of information to found about ASP.NET Identity on the web, in particular Microsoft's own documentation is really good. Check this out for a starter for some great examples.

Orchard CMS ask for an invite token to link to backend data during registration using workflows only

I am using Orchard CMS v1.9 and want to display a custom registration page to accept the usual username/password/email and an additional token (invite token). The token will be used to match the user to some to custom data on the server.
I have walked through this blog Customizing User Registation With Dynamic Forms And Workflows. But in addition to what is achieved in this blog I want to force a registering user to enter a token. The token is used to lookup data on the server and create a link to the userpart.
Adding the token to the form is not the issue - its the querying and linking the entered token to the backend data and storing it in the userpart that im finding awkward.
Is this possible using just workflows - or do i need a custom module? I did not see a custom action that allowed me to match the token and link.
Is there a custom module already available that does something
similar?
Disclaimer: This approach is currently based on Orchard 1.10 but was initially developed on the 1.9.x branch. It does not rely on Dynamic Forms and Workflows, but I think you could achieve something similar with those modules.
Okay so I ended up building an example module with our approach to extended users / activation system. I stripped out a lot of code, but also let some juicy parts, which aren't directly related to your answer, in it.
First you should check out the UsersController it has the activate actions you are searching for. You may need to extend the orchard LogOn-View and include some GET & POST Actions accordingly.
[AllowAnonymous]
[HttpGet]
public ActionResult Activate(string activationCode)
{
// validation stuff....
var viewModel = new CustomUserActivate
{
// This is the activationCode you're looking for
ActivationCode = userFromActivationCode.ActivationCode,
UserName = userFromActivationCode.User.UserName,
WelcomeText = userFromActivationCode.WelcomeText,
Email = userFromActivationCode.User.Email
};
return this.View(viewModel);
}
[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Activate(CustomUserActivate input)
{
if ( input == null )
{
this.ModelState.AddModelError("_form", this.T("The argument cannot be null").Text);
}
CustomUserPart customUserPart = null;
if ( this.ModelState.IsValid )
{
customUserPart = this.myService.GetCustomUserByActivationCode(input.ActivationCode);
if ( customUserPart == null || customUserPart.User == null || customUserPart.User.UserName != input.UserName )
{
this.notifier.Add(NotifyType.Error, this.T("The activation failed"));
}
if ( string.IsNullOrEmpty(input.Email) )
{
this.ModelState.AddModelError("Email", this.T("You must specify an email address.").Text);
}
else if ( input.Email.Length >= 255 )
{
this.ModelState.AddModelError("Email", this.T("The email address you provided is too long.").Text);
}
else if ( !Regex.IsMatch(input.Email, UserPart.EmailPattern, RegexOptions.IgnoreCase) )
{
// http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
this.ModelState.AddModelError("Email", this.T("You must specify a valid email address.").Text);
}
else if ( !this.myService.VerifyEmailUnicity(customUserPart.User.Id, input.Email) )
{
this.ModelState.AddModelError("Email", this.T("This email address is already in use.").Text);
}
}
if ( !this.ModelState.IsValid )
{
return this.View(input);
}
Debug.Assert(customUserPart != null, "customUserPart != null");
var user = customUserPart.User;
var userParams = new CreateUserParams(user.UserName, input.Password, input.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true);
this.myService.ActivateCustomUser(customUserPart.Id, userParams);
this.notifier.Add(NotifyType.Information, this.T("Your account was activated. You can now log in."));
return this.RedirectToAction("LogOn", "Account", new { area = "Orchard.Users" });
}
The interesting stuff happens in MyService.cs.
We designed the activation system so that you can still leverage all the features of the Orchard.User Module like Email-Verifcation.
For this we've implemented some CustomSettings, where you can decide if your user get's completely activated when an ActivationCode is used or if you trigger the normal Orchard mechanism.
I guess it's best to checkout the module and step through the code in Visual Studio.
Here a two screenshots of our activation views.
Step 1 - Enter your activation code
Step 2 - Fill in the remaining fields
Profit!
All the additional source is to make use of the CustomUser / ActivationCode in Workflows, Events, Tokens, etc. But I leave this for you to discover.
If you want more detailed descriptions of the source on GitHub let me know.
Hope this helps!

Getting domain variables on layout

What is the best way to pass the model variables to layout in Grails? Specifically, I'm using Spring security plugin which has User class. I also have Contact class that looks like this:
class Contact {
String realname
String company
String mobile
String fix
String email
User user
...
What are the options for getting the currently logged in person's company in my layout (main.gsp)?
To add to the above answer, you could alternatively set a session variable for the user when you login in whatever controller method gets called.
You can also just set a session variable for the company in the controller method:
session.company = Contact.findByUser(session.user)?.company
or from the example above
session.company = Contact.findByUser(SecurityContextHolder.context.authentication?.principal)?.company
And in your main.gsp, something like:
<span id="companyName">${session.company}</span>
Do you mean that you need to pass this model for every page, automatically, instead of manual passing it at render at each of controllers? You can use filters there:
def filters = {
all(controller: '*', action: '*') {
before = {
request.setAttribute('loggedInPerson', SecurityContextHolder.context.authentication?.principal)
//Notice, that there is used original Authentication, from Spring Security
//If you need you can load your Contact object there, or something
}
after = {
}
afterView = {
}
}
}
and use loggedInPerson at your gsp:
Hello ${loggedInPerson.username}!
Btw, there is also Spring Security tags, that can help you without using your own filter, like:
Hello <sec:loggedInUserInfo field="username"/>!
If you want to add a certain object to the model, you can also use the "interceptors" provided by grails. To add a certain variable to a particular controller, you can use something like this.
def afterInterceptor = {model, modelAndView->
model.loggedInUser = getLoggedInUser() // retrieve your user details here
}
And you can retrieve loggedInUser in the main.gsp layout as ${loggedInUser}.
If you need to get these details in multiple controllers, you can create a BaseController and keep the afterInterceptor in this BaseController. All controllers which need the reference to the logged in user in their corresponding views should extend the BaseController.

Where to check user email does not already exist?

I have an account object that creates a user like so;
public class Account
{
public ICollection<User> Users { get; set; }
public User CreateUser(string email)
{
User user = new User(email);
user.Account = this;
Users.Add(user);
}
}
In my service layer when creating a new user I call this method. However there is a rule that the users email MUST be unique to the account, so where does this go? To me it should go in the CreateUser method with an extra line that just checks that the email is unique to the account.
However if it were to do this then ALL the users for the account would need to be loaded in and that seems like a bit of an overhead to me. It would be better to query the database for the users email - but doing that in the method would require a repository in the account object wouldn't it? Maybe the answer then is when loading the account from the repository instead of doing;
var accountRepository.Get(12);
//instead do
var accountRepository.GetWithUserLoadedOnEmail(12, "someone#example.com");
Then the account object could still check the Users collection for the email and it would have been eagerly loaded in if found.
Does this work? What would you do?
I'm using NHibernate as an ORM.
First off, I do not think you should use exceptions to handle "normal" business logic like checking for duplicate email addresses. This is a well document anti-pattern and is best avoided. Keep the constraint on the DB and handle any duplicate exceptions because they cannot be avoid, but try to keep them to a minimum by checking. I would not recommend locking the table.
Secondly, you've put the DDD tag on this questions, so I'll answer it in a DDD way. It looks to me like you need a domain service or factory. Once you have moved this code in a domain service or factory, you can then inject a UserRepository into it and make a call to it to see if a user already exists with that email address.
Something like this:
public class CreateUserService
{
private readonly IUserRepository userRepository;
public CreateUserService(IUserRepository userRepository)
{
this.userRepository = userRepository;
}
public bool CreateUser(Account account, string emailAddress)
{
// Check if there is already a user with this email address
User userWithSameEmailAddress = userRepository.GetUserByEmailAddress(emailAddress);
if (userWithSameEmailAddress != null)
{
return false;
}
// Create the new user, depending on you aggregates this could be a factory method on Account
User newUser = new User(emailAddress);
account.AddUser(newUser);
return true;
}
}
This allows you to separate the responsiblities a little and use the domain service to coordinate things. Hope that helps!
If you have properly specified the constraints on the users table, the add should throw an exception telling you that there is already a duplicate value. You can either catch that exception in the CreateUser method and return null or some duplicate user status code, or let it flow out and catch it later.
You don't want to test if it exists in your code and then add, because there is a slight possibility that between the test and the add, someone will come along and add the same email with would cause the exception to be thrown anyway...
public User CreateUser(string email)
{
try
{
User user = new User(email);
user.Account = this;
user.Insert();
catch (SqlException e)
{
// It would be best to check for the exception code from your db...
return null;
}
}
Given that "the rule that the users email MUST be unique to the account", then the most important thing is to specify in the database schema that the email is unique, so that the database INSERT will fail if the email is duplicate.
You probably can't prevent two users adding the same email nearly-simultaneously, so the next thing is that the code should handle (gracefully) an INSERT failure cause by the above.
After you've implemented the above, seeing whether the email is unique before you do the insert is just optional.

Resources