django- adding new user from the frontend - django-users

I have been learning django for like 1 month now and i felt the best way is to do a project. i settled on a simple school management project but I am kind of stacked. This project has different categories of users i.e students and administrator. the school administrator should log in and add new students, the students should also log in and may be edit their profile. I created a nother app UserProfile with User as foreignKey and category
class Category(models.Model):
name=models.CharField(max_length=200)
def __unicode__(self):
return self.name
class UserProfile(models.Model):
user=models.OneToOneField(User)
category=models.ForeignKey(Category)
def __unicode__(self):
return "%s "%(self.category.name)
I added sample users from the admin site and am so far able to redirect the school administrator to his frontend dashboard where he should be adding new student. the students also are redirected to the students page upon login. i have a common login form.
my first question is, should i have user as foreigkey in the student model like below?
class Student(models.Model):
user=models.OneToOneField(User)
regNum=models.CharField(max_length=200, unique=True)
lastName=models.CharField(max_length=200)
otherNames=models.CharField(max_length=200)
dateOfBirth=models.DateField()
idNo=models.IntegerField(default=123456)
email=models.EmailField()
contact=models.IntegerField(default=071234567)
HomeTown=models.CharField(max_length=200)
How can i handle add new student so that the administrator is able to add student details including the students login password and at the same time assign a category to the student. please note that am new in django. thanks

You will need to create a User instance and add it to the student together with student details.
As described here :
https://docs.djangoproject.com/en/1.8/ref/contrib/auth/#django.contrib.auth.models.UserManager.create_user
And here:
Creating users django 1.8
Example:
from django.contrib.auth.models import User
#place this after your form is valid
form=StudentForm(request.POST)
if form.is_valid():
#create student
username=form.cleaned_data['username']
email=form.cleaned_data['email']
password=form.cleaned_data['password']
user=User.objects.create_user(username=username,email=email,password=password)
#create your userprofile here
............
............
#using the user instance now create your student
student=Student.objects.create(user=user,regNum=''......)
.............
..............

Related

Determining Roles VB.NET

So firstly I have no code to show as I'm trying to get my head around how to do this first.
So I have a website that has 3 account pages (Patient, Doctor, Admin) that have 3 different pages for these. There is 3 tables named Patient, Doctor and Admin with account/log in and registered details in them. There is also a field in each of these tables called Role and for Patient table I have the word Patient in the field for each record and the same for Doctor and Admin.
In my login page I need to grab these to determine their login. So if patient is logged in then in the masterpage the patient accountlink will turn visible and so on.
How do i grab all 3 of these roles and determine an if, store in session, and use the session in the masterpage to show whichever link.
Sorry if this is confusing.
What you need to do is have one main table where all the login details go. In this table, have a column called Role and when a new account is made, make it also input into the table, the role of the person.
If you need the other tables for other things, then use an if else statement to also make the information be input into the table that matches its role. (so that means, info input into two tables). This makes it a lot easier.
Then, on the page where the user is redirected after they log in, this is where you write the code to check for the user's role.
sql = "SELECT Role From tablename WHERE username = '"& textbox.text &"'"
Search the main table using the username of the user to find the role and then use an if statement to make the specific links show.
If sql = Patient then
<code here>
Else if sql = Admin then
<code here>
Else if sql = Doctor then
<code here>
End if

Drupal how to have certain admins only see the users they've created

I use Drupal 7 and would prefer to do so but if I need to use Drupal 6 I will. I have a Drupal 7 site that I allow "advisors" to create authenticated users. I am an admin on the site so I see and can do everything. All that an "advisor" can do is create and edit authenticated users. Is there a way to make a view that displays the users that the particular advisor has created while the advisor is logged in?
If you don't understand what I'm saying let me put it this way. I am the admin of the site so I can do everything. I created a user role called advisor. There's also an authenticated role for users. Advisors can create authenticated users. So I have Advisor 1. Advisor 1 created 10 users. I also have Advisor 2. Advisor 2 created 3 users. I'd like a page (more than likely built with views - and I've used views before on other sites so I'm familiar with them) - I'd like a page that Advisor 1 could go to once logged in and it would display all of the 10 users that they created. Advisor 1 wouldn't see the users that Advisor 2 create.
Is this possible? Any help on this would be greatly appreciated. Thank you in advance.
I have implemented something similar and I can give you some guidelines.
First of all drupal 7 doesn't store the information of the creator of the users.
So, in order to track this you will need to attach a custom field to the user to keep this information.
In such case you ll have to make sure that every creator can insert only himself in this field and not anyone else or you 'll have to find an automated way to fill it in.
I suggest you use field permission module for setting permissions to this field (users probably should not even have view, creators should not be able to change it etc ) and computed field module for automatically populate the field (eg creator_field) upon creation for example with the uid of the creator.
Finally when creating the view you could add contextual filtering by using the logged in user on the creator_field.
You should also have a look at Organic Groups. I haven't use it but might be helpful
Hope it helps.
Updated
Add
global $user;
$entity_field[0]['value'] = $user -> uid;
to the Computed Code (PHP) in the computed field settings and store the value as integer in "Database store settings". Then in your view you should add a view of user with contextual filter of creator_field. In the contextual filter settings you must set "provide default value" -> "User ID from logged in user" in the "WHEN THE FILTER VALUE IS NOT IN THE URL" section.
This could be done relatively easily in Drupal 7 by adding a field to the user profile that points back to the user creator (using the Entity Reference module). Profile2 could offer a shortcut to making this field available on a profile, though if this is the only customization that you need to add to your profiles, it would be cleaner to do this in a custom module.
A view (Views module) could be configured to output a list of users with the current logged in user as the creator.
You'll also need to add similar logic for user_access to allow/restrict profile editing (if the current user is the user referenced in the profile). A permissions hook also could be useful if you plan to have different admin levels.
The Tokens module should work to insert this value for the new user, by inserting the current user into the field. Or you can do this before the user is saved. It would go a little something like this:
function mymodule_user_presave(&$edit, $account, $category) {
if ($account->is_new) {
global $user;
$created_by = $user->uid;
$edit['created_by'] = $created_by;
}
}
Good luck.

Multiple ASP.NET Membership roles in the same Website

In my MVC3 application I have ASP.NET Membership roles like - Manager, System Admin and Editor
I am using Windows Authentication for the website and I am adding the users in the Network to the Membership just like in the following example -
http://weblogs.asp.net/scottgu/pages/Recipe_3A00_-Implementing-Role_2D00_Based-Security-with-ASP.NET-2.0-using-Windows-Authentication-and-SQL-Server.aspx
But, my problem is there are people who require multiple permissions. For example
User-John is the Manager of Department-ABC and he can see all the Actions in Department-ABC.
User-John is also Editor in Department-XYZ and he should be able to see all the Actions of an Editor in Department-XYZ;
but NOT the Actions of Manager; because he is not the Manager of Department-XYZ.
User Mathew is the Manager of Department-XYZ and he is an Editor in Department-ABC.
If I use normal role privileges, it will allow User-John to be the Manager of both departments and it is not right.
My solution is to store the DepartmentID, UserID and RoleID in a seperate table in SQL database and allow according to this table.
How can I get the role ID from ASP.NET Membership in C# and also in SQL?
Is it safe to do?
Is there a better solution?
Activity based membership would probably fit here.
In activity based membership your users get access to actions, not to roles.
Typical usage is:
One action = one activity
There are still roles given to users, but they are used to group activities
There is n..n relation between roles and activities
Activity is just a custom action filter that is applied to the action.
Typical example is here (although I don't like this approach, so I made my own implementation).
[Activity(Name="DoSomething")]
public ActionResult DoSomething()
{
...
return View();
}
Membership can be stored in ASP Membership database table, custom table or represented as AD group. Depends whether you implement custom membership provider or you use default implementation.
At the end, there has to be n..n relationship like RoleActivity, where you link the particular role to the activity (like Manager1 to both AddMemberToDepartment and AddComment, and Manager2 to just AddComment). This relation can be classic n..n database relation or 'virtual', where role is in AD and database table relates to it only via group name.
EDIT:
If you use default database role based authorization, table aspnet_Roles will be generated for you. To support activity based membership you will have to add your own activity table manualy, along with additional role-activity relation.
This schema should help you proceed.
aspnet_Roles (autogenerated)
* ApplicationId
* RoleId
* ...(other autogenerated columns)...
aspnet_MyActivity (add manually)
* ActivityId
* ApplicationId
* Name
* Description
aspnet_MyPermission (add manually)
* ApplicationId
* RoleId
* ActivityId
You can fill roles using membership provider.
Then fill manually your activities as your application needs them, say, one activity per action method.
Finally, manually add your activity permissions to roles.
Real world scenario
If your organization is small enough, it may be acceptable to add one role per department and one activity per action/deparment:
role: Dep. mgr. of ABC,
role: Dep. mgr. of XYZ,
activity: createAbcUser,
activity: createXyzUser
Connect them using appropriate permissions and you have your requirement covered.
However, for a large number of departments adding one role per department and giving activity permission for each of them can be a little awkward. In that case you should stick with simple role "Department manager" and simple activity "Create user", and give your manager permission to create user. However, you have to stop manager to create user in a different department - use your hierarchy for that, meaning, check if your user belongs to your manager.
Your action filter will then look like this:
check if any of current users roles has a permission to run that activity
check your hierarchy: does your current user have a permission to work on referenced user?
If both of these are true, action method can be executed.
NOTE: You will probably reference user by some input parameter, so your action filter has to access that parameter. See Getting the values of action parameters within an action filter to solve that.

ASP.NET Membership and Roles

I am trying to use ASP.NET membership and roles for my project and have been going through different articles, posts and SO to check if using it is a better option for me rather than hand coding the whole functionality from scratch. Yet after days of search I haven't yet figured out if its even possible for the following scenario.
The users of my application have roles and they belong to a company as well. So, I would need to retrieve the company id for the user as soon as he/she logs in as I would need the company id on different pages to show the user his/her company specific data.
Roles should be categorized. (i-e Application Admin, Company Admin, Company Users (Managers, front-desk etc). So when company admin assign roles to users, he/she could only assign Manager, front-desk etc and Not Application Admin. (I thought about adding another field to Roles table in order to categorize the roles but I don't know whether that would be a good or bad thing to do and how it will modify the behavior of membership controls)
Not exactly a question but I am rather seeking advice whether I should go for the ASP.NET Membership in this scenario
writing from scratch is not recommended for what you want . you can handle your requirements using asp.net membership .
1- you can save user information in their profiles (company , name , ... ) or create another table to map users to companies.
2- for your second question ,you can create a separate class or method to handle the access.
something like below :
public IList<string> GetRolesUserCanAssign(string userRole)
{
var roles = new List<string>();
if(userRole == "Manager" || userRole == "FrontDesk")
{
return roles;
}
roles.AddRange(new[]{"Manager" , "FrontDesk"});
if(userRole == "CompanyAdmin")
{
return roles;
}
if(userRole == "ApplicationAdmin")
{
roles.Add("CompanyAdmin");
}
return roles;
}

"Role Management" vs "User Management" in ASP.NET

Question No 1
I am familiar with role management, a particular member in a particular role can do this and access this functionally. What I need to do is Manage individual user, not the role he is in.
For example, lets say I create a role, called "Sales". I setup the role permission what the sales persons can do. Now i want to keep a check on individual user. For example if this is "john", i want to show him the records only he created. If his is peter, I want to show him only that records which he created, not by john or other sales people.
Is there a thing called "User Management" in ASP.NET that we can use? If not we have to create it ourselves and I believe the integration with ASP.NET "Role Management" will not be that smooth.
Question No 2.
I am using control for user login. I want to create a session at this time so I can keep track of which user is signed in so I can show him the records only pertaining to him. How can I do that?
Your Q1 isn't really about Role vs User management (ie: authorizations) at this point. It's about audit tracking within your application.
And the way you do that is you capture the ID of the user who created the record in question with the record, so that later you can filter on that ID.
Pseudo database structure
Table Sales
Field...
Field...
Field...
CreatedByUser int not null, -- Populate this on creation and never change it again
ModifiedByUser int not null - populate this on every row update including insert
See ASP.NET Profile Properties.
Assuming the records in the database correspond to a unique ID for a user, you can store the unique id in a profile property per user.
1) If you want to filter records by the creating user, you need to record in your table the ID of the user who created the record. You can access the name of current user through User.Identity.Name and their ID (provider-dependent) through User.ProviderUserKey.
2) Sessions are created automatically in ASP.NET and provided you have a properly configured MembershipProvider, you can retrieve all the needed user info using the User object as shown above.
It sounds like you are a little unfamiliar with ASP.NET Membership and Roles capabilities, because they are actually set up quite well to accomplish what you are describing. I would recommend checking out this tutorial series:
https://web.archive.org/web/20211020202857/http://www.4guysfromrolla.com/articles/120705-1.aspx
You are talking about Authentication and Authorization. For question 1 you and implement a custom authorization provider to allow for user level control http://msdn.microsoft.com/en-us/library/aa479048.aspx For question 2, once you log in and are Authenticated, the session contains a userprinciple object that has the info in it automatically.

Resources