Best practice for seperating a ASP.Net MVC site with AD from different AD Groups? - asp.net

I've got a ASP.net MVC site that authenticates against Azure Active Directory. I have users in Groups in AD and need to be able to show different navbar items and pages depending on what group the user is in.
Currently I have a shared layout .cshtml for everyone for the navbar and am including or excluding navbar items using code like below. I am passing in the logged in user and the group they should be in to a helper and then checking to see if that helper is in the group:
#if (Helpers.AuthenticationHelper.HasPermissions(User, "IT") == true)
{
<span>User has access to IT</span>
}
else
{
<span>User has no access to IT</span>
}
#if (Helpers.AuthenticationHelper.HasPermissions(User, "Accounting") == true)
{
<span>User has access to Accounting</span>
}
else
{
<span>User has no access to Accounting</span>
}
And then for actual web pages I'm essentially doing that same thing but in the controller and redirecting them to a different view if they do not have permissions.
Is this a secure way of doing this or are there security flaws? Could someone smart enough find a way around this? I need to make sure under no circumstance can the users in one group see stuff intended for another group. Thanks. Appreciate any advice.
EDIT: Adding Controller Code on request.
public ActionResult Dashboard()
{
using (Data.WebAppsCoreContext _context = new Data.WebAppsCoreContext())
{
var securityRepo = new SecurityRepository(_context);
var metricBool = securityRepo.Metrics(AuthenticationHelper.GetGroups(User), "Metrics");
if (metricBool == true)
{
//return normal view
return View();
}
else
{
//return alternate view
return View("/Something/Something/");
}
}
}

Related

Displaying form on first login

I'm trying to work out how I can display a form to a user upon their first login to my app ( to fill in profile information) after which they can proceed to the regular site.
Could anyone point me in the right direction?
Thanks
You can make the trick using app startup script:
https://devsite.googleplex.com/appmaker/settings#app_start
Assuming that you have Profile model/datasource, code in your startup script will look similar to this:
loader.suspendLoad();
var profileDs = app.datasources.Profile;
// It would be more secure to move this filtering to the server side
profileDs.query.filters.UserEmail._equals = app.user.email;
profileDs.load({
success: function() {
if (profileDs.item === null) {
app.showPage(app.pages.CreateProfile);
} else {
app.showPage(app.pages.HomePage);
}
loader.resumeLoad();
},
failure: function() {
loader.resumeLoad();
// your fallback code goes here
}
});
If profile is absolute must, I would also recommend to enforce the check in onAttach event for every page but CreateProfile (to prevent navigation by direct link):
// Profile datasource should be already loaded by startup script
// when onAttach event is fired
if (app.datasources.Profile.item === null) {
throw new Error('Invalid operation!');
}
I suggest checking the user profile upon login. If the profile is not present, display the profile form, otherwise, proceed to the regular site.

Ionic2 tabs/app,ts passing value

I need to pass value from tabs.ts to each page of tabs. So I have something like this:
constructor(public navParams: NavParams) {
...// config
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// If there's a user take him to the home page.
this.user = [];
this.user.push(user);
this.rootPage = HomePage;
} else {
// If there's no user logged in send him to the LoginPage
this.rootPage = LoginPage;
}
});
}
this.tab1Root = HomePage;
this.tab4Root = ProfilePage;
How to pass value (user) to each page of tabs? I tried with few combinations of this code but doesnt work (getting some erros - e.g If I put this.tab1Root... to onAuthStateChanged method, then it gives me: "Maximum call stack size exceeded"). Here are docs: http://ionicframework.com/docs/v2/api/components/tabs/Tab/ - I understand 90% of this but still dont know how I should pass this value...
My second question - is there any better way to take current user and pass him as value to each page? Will be better if I use provider or something?
Third question: it is good to have this code in tabs.ts than in app.ts?
Thanks!
You can use [rootParams] attribute in ion-tab
<ion-tab ... [rootParams]="user"></ion-tab>
In tab file:
constructor(navParams: NavParams) {
console.log("Passed params", navParams.data.user);
}
Second way is using events: http://ionicframework.com/docs/v2/api/util/Events/
It allows you to share data between any of your pages.
Provider is a good option.
It depends. Better way is to make an authorization once - using provider inside app.ts - when app starts.

Managing a list of urls to redirect according to language in Asp.net Web Forms

I have a web site developed with Asp.Net Web Forms (.Net Framework 4.6). I have two languages and many content pages. If a user in page clicks to language button then users redirected to same content's opposite language. For example if i am in contact page and if i click to spanish language button i am going to contact page in spanish which is a diffent web form.
To achive that i have a list of if statement like that:
if (ThePageIClickOnLanguageButton == "Help") { Response.Redirect("/Ayuda", false); }
if (ThePageIClickOnLanguageButton == "Sign-In") { Response.Redirect("/Iniciar-Sesion", false); }
if (ThePageIClickOnLanguageButton == "Support") { Response.Redirect("/Asistencia", false); }
if (ThePageIClickOnLanguageButton == "Products") { Response.Redirect("/Productos", false); }
So to achive same thing in the spanish pages i have to do same thing opposite like that:
if (ThePageIClickOnLanguageButton == "Ayuda") { Response.Redirect("/Help", false); }
if (ThePageIClickOnLanguageButton == "Iniciar-Sesion") { Response.Redirect("/Sign-In", false); }
if (ThePageIClickOnLanguageButton == "Asistencia") { Response.Redirect("/Support", false); }
if (ThePageIClickOnLanguageButton == "Productos") { Response.Redirect("/Products", false); }
My pages keep increasing so i am adding new lines all the time in to this if list.
There must be a better way to achive this. Like making a list like below list and create a method to find current page, look in to the list, find the url of other language and redirect it to there.
/Help = /Ayuda
/Sign-In = /Iniciar-Sesion
/Support = /Asistencia
/Products = /Productos
Any idea how to achive that?

manage views with css or regions in Backbone Marionette

I am working on a page having lot of input-controls and related divs. There are use-cases on this page where I am suppossed to show/hide the divs depending on the order of user clicking on input-controls in various follow-up screens.
Now the divs are all there in first load itself and by showing/hiding, the screen changes for the user. Now to show/hide I can use css and add view* class to .main content div depending on business logic.
ex.:
.main div{
display: none;
}
.main.view1 div.a,.main.view1 div.b,.main.view1 div.f{
display:block;
}
.main.view2 div.c,.main.view2 div.f {
display:block;
}
.main.view3 div.c,.main.view3 div.f {
display:block;
}
....etc
But this way the no. of css classes are getting unmanageable.
Please suggest if there is a better method I can use wherein it becomes easy to manage the user-flows. I think there are regions in marionette which can help me manage this. Please suggest the best way and elaborate if the answer is marionette.regions
You can model the application as a state machine to model complicated workflows.
To define a state machine:
Define all the states that your application can be in.
Define the set of actions that are allowed in each state. Each action will transition the state of the application from one state to another.
Write the business logic for each action which includes both persisting changes to the server and also changing the state of the views accordingly.
This design is similar to creating a DFA, but you can add extra behaviour according to your needs.
If this sounds too abstract, here's an example of a simple state machine.
Let's say you're building a simple login application.
Design the States and Actions
INITIAL_STATE: The user visits the page for the first time and both fields are empty. Let's say you only want to make the username visible, but not the password in this state. (Similar to the new Gmail workflow)
USERNAME_ENTRY_STATE: When the user types in the username and hits return, in this state, you want to display the username and hide the password. You can have onUsernameEntered as an action in this state.
PASSWORD_ENTRY_STATE: Now, the username view will be hidden and the password view will be shown. When the user hits return, you have to check if the usernames and passwords match. Let's call this action onPasswordEntered
AUTHENTICATED_STATE: When the server validates the username/password combination, let's say you want to show the home page. Let's call this action onAuthenticated
I have omitted handling the Authentication Failed case for now.
Design the Views:
In this case, we have the UsernameView and the PasswordView
Design the Models:
A single Auth model suffices for our example.
Design the Routes:
Check out the best practices for handling routes with Marionette. The state machine should be initialized in the login route.
Sample Pseudo-Code:
I've only shown the code relevant to managing the state machine. Rendering and event handling can be handled as usual;
var UsernameView = Backbone.View.extend({
initialize: function(options) {
this.stateMachine = options.stateMachine;
},
onUserNameEntered: function() {
username = //get username from DOM;
this.stateMachine.handleAction('onUserNameEntered', username)
},
show: function() {
//write logic to show the view
},
hide: function() {
//write logic to hide the view
}
});
var PasswordView = Backbone.View.extend({
initialize: function(options) {
this.stateMachine = options.stateMachine;
},
onPasswordEntered: function() {
password = //get password from DOM;
this.stateMachine.handleAction('onPasswordEntered', password)
},
show: function() {
//write logic to show the view
},
hide: function() {
//write logic to hide the view
}
});
Each state will have an entry function which will initialize the views and and exit function which will cleanup the views. Each state will also have functions corresponding to the valid actions in that state. For example:
var BaseState = function(options) {
this.stateMachine = options.stateMachine;
this.authModel = options.authModel;
};
var InitialState = BaseState.extend({
entry: function() {
//show the username view
// hide the password view
},
exit: function() {
//hide the username view
},
onUsernameEntered: function(attrs) {
this.authModel.set('username', attrs.username');
this.stateMachine.setState('PASSWORD_ENTRY_STATE');
}
});
Similarly, you can write code for other states.
Finally, the State Machine:
var StateMachine = function() {
this.authModel = new AuthModel;
this.usernameView = new UserNameView({stateMachine: this});
//and all the views
this.initialState = new InitialState({authModel: this.authModel, usernameView: this.usernameView});
//and similarly, all the states
this.currentState = this.initialState;
};
StateMachine.prototype = {
setState: function(stateCode) {
this.currentState.exit(); //exit from currentState;
this.currentState = this.getStateFromStateCode(stateCode);
this.currentState.entry();
},
handleAction: function(action, attrs) {
//check if action is valid for current state
if(actionValid) {
//call appropriate event handler in currentState
}
}
};
StateMachine.prototype.constructor = StateMachine;
For a simple application this seems to be an overkill. For complicated business logic, it is worth the effort. This design pattern automatically prevents cases such as double-clicking on a button, since you would have already moved on to the next state and the new state does not recognise the previous state's action.
Once you have built the state machine, other members of your team can just plug in their states and views and also can see the big picture in a single place.
Libraries such as Redux do some of the heavy-lifting shown here. So you may want to consider React + Redux + Immutable.js as well.

Orchard Custom Widget with Form

I built a custom module that manages appointments for a service-based company. All of the current functionality is contained in the admin section. I have not used a single ContentItem or ContentPart. All the models are just plain records.
I'm looking to create a widget to expose the ability to sign up for an appointment from the front end. I have a partial view and a controller that handles the display and form submit, but I'm not sure how to tie that into a widget that can be placed in one of the content zones of the front-end.
I've spent quite a bit of time researching this, and can't find a good path to follow. (I've tried a few and got sub-optimal results)
Any suggestions?
The best answer for me was to create a widget Type definition in the migration.cs file of the module:
ContentDefinitionManager.AlterTypeDefinition("CreateAppointmentWidget",
cfg => cfg
.WithPart("WidgetPart")
.WithPart("CommonPart")
.WithSetting("Stereotype", "Widget"));
Then create a handler for that widget at /MyModule/Handlers/CreateAppointmentWidgetHandler.cs:
public class CreateAppointmentWidgetHandler : ContentHandler
{
private readonly IRepository<FieldTechRecord> _repository;
public CreateAppointmentWidgetHandler(IRepository<FieldTechRecord> repository)
{
_repository = repository;
}
protected override void BuildDisplayShape(BuildDisplayContext context)
{
base.BuildDisplayShape(context);
if (context.ContentItem.ContentType == "CreateAppointmentWidget")
{
CreateAppointmentViewModel model = new CreateAppointmentViewModel(_repository.Fetch(x => x.IsActive));
context.Shape.AppointmentModel = model;
}
}
}
Then create a matching widget template at /MyModule/Views/Widget-CreateAppointmentWidget.cshtml that inserts the Partial View:
#Html.Partial("CreateAppointment", (MyModule.Models.Views.CreateAppointmentViewModel)Model.AppointmentModel)
The above code grabs the partial view /MyModule/Views/CreateAppointment.cshtml.
Thanks to Giscard's suggestion, I was able to correct the links rendered from CreateAppointment.cshtml by using #Url.RouteUrl() and defining named routes to point where I needed the action and ajax requests to go.
The nice thing about this solution is that it provided a way to create the widget without having to rework my models to use Orchards ContentPart functionality.
Something is not connecting in my head, because I have been able to create a theme with zones, and then dispatch a shape from my module into that zone without much more than doing #Display.Shape(). So I am curious if it's absolutely necessary to use a handler to override the BuildDisplayShape.
Again, this is in the scenario where you have models as plain records (not using ContentItem or ContentPart - and even if not using them, you've shown an example of creating one through migrations).
Something like this - Controller:
public ShapeResult MyShape()
{
var shape = _orchardServices.New.MyPath1_MyShape();
return new ShapeResult(this, shape);
}
Then create a MyShape.cshtml shape with whatever code I have (no need for example).
NOTE: I use a custom IShapeTemplateHarvester file which adds paths where I can store my shapes (instead of using "Views", "Views/Items", "Views/Parts", "Views/Fields", which is the stock in Orchard). It goes something like this:
NB: I hate that code doesn't automatically wrap in SO.
[OrchardSuppressDependency("Orchard.DisplayManagement
.Descriptors.ShapeTemplateStrategy.BasicShapeTemplateHarvester")]
public class MyShapeTemplateHarvester : BasicShapeTemplateHarvester,
IShapeTemplateHarvester
{
public new IEnumerable<string> SubPaths()
{
var paths = base.SubPaths().ToList();
paths.Add("Views/MyPath1");
paths.Add("Views/MyPath2");
return paths;
}
}
Say I have Index.cshtml in my Theme. I have two choices (I use both and use the Theme as the default presentation).
Index.cshtml in Theme folder:
#*Default Content*#
Index.cshtml in Module folder:
#*Special Content overriding Theme's Index.cshtml*#
Display.MyPath1_MyShape()
Even better for me is that I can do this in the Index.cshtml in Theme folder:
#*Whatever content*#
Display.MyPath1_MySecondShape()
There is no ~/MyPath1/MySecondShape.cshtml in the Theme, but there is one in the Module, which the Theme displays! This is great because I can have a special Theme and have multiple modules (that are placed on separate sites) go back and forth with the theme (think Dashboard for different services in the same profession on different sites).
NOTE: The above may only be possible with IThemeSelector implementation such as:
public class MyThemeSelector : IThemeSelector
{
public ThemeSelectorResult GetTheme(RequestContext context)
{
if (MyFilter.IsApplied(context))
{
return new ThemeSelectorResult { Priority = 200,
ThemeName = "MyDashboard" };
}
return null;
}
}
Just my two bits.

Resources