Java

Authorize user permission with bit field technique in Java

Assume that we have 4 functions: View, Add, Edit, Delete

And 4 user roles: 1, 2, 3, 4 with:

1: User can View

2: User can View and Add

3: User can View, Add and Edit

4: User has full permission

Here is small snippet to detect permission of user.

public class Main {

	public static void main(String[] args) {
		int[] 		list 		= 		new int[] 			{1, 		2, 		3, 		4};
		String[] 	roles 		= 		new String[] 		{"View", 	"Add", 	"Edit", "Delete"};

		// Test for 4 user with 4 different roles
		for(int i = 1; i <= 4; i++) {
			System.out.print("With role " + i + ", user can: ");
			// Test which role user can do
			for(int j = 0; j < 4; j++) {
				// Biggest role of user is role j
				if((i & list[j]) == list[j]) {
					for(int k = 0; k < i; k++) {
						System.out.print(roles[k] + "\t");
					}
					break;
				}
			}
			System.out.print("\n\n");
		}
	}
}

And here is result:
With role 1, user can: View

With role 2, user can: View Add

With role 3, user can: View Add Edit

With role 4, user can: View Add Edit Delete

 

Happy coding!!!

Advertisements

1 thought on “Authorize user permission with bit field technique in Java”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s