package com.hety.auth;
/**
*
*
* @author hety
* @version 1.0 2015-6-9 下午2:27:06
*/
public class AuthTest {
public static void main(String[] args) {
/*
* 如果用户有权限:添加A---2;删除B---3;修改B---4
那用户的权限值 purview =2^2+2^3+2^4=28,也就是2的权的和了。
化成二进制可以表示为11100
这样,如果要验证用户是否有删除B的权限,就可以通过位与运算来实现。
在Java里,位与运算运算符号为&
即是:int value = purview &((int)Math.pow(2,3));
*/
/**
*
* @param totalPower 总权限
* @param currentPower 当前权限
* @return true 拥有此optPurview权限,反之亦然。
*/
public static boolean checkPower(int totalPower, int currentPower) {
// int purviewValue = (int) Math.pow(2, currentPower);
int purviewValue = 1 << currentPower;
return (totalPower & purviewValue) == purviewValue;
}
public static void main(String[] args) {
System.out.println("1 << 1 ="+(1 << 1));
System.out.println("1 << 2 ="+(1 << 2));
System.out.println("1 << 3 ="+(1 << 3));
int test =0;
// int c = ( ((1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)) );
int c = (1 << 1) + (1 << 2) + (1 << 3) + (1 << 4) ;
System.out.println("2^1+2^2+2^3+2^4="+c);
boolean e = checkPower(c, test);
System.out.println(test +"是否具有"+c+"中的权限:"+e );
int tempStatus = (1 << 1 )+ (1 << 3);
System.out.println(tempStatus);
int tempStatus2 = ((1 << 1) + (1 << 3));
System.out.println(tempStatus2);
}
}
// 权限计算:2^1 + 2^2 + 2^3 + 2^4
const c = (2 ** 1) + (2 ** 2) + (2 ** 3) + (2 ** 4);
console.log(`2^1+2^2+2^3+2^4=${c}`);
const test = 11; // 要检查的操作权限(注意:这里 test=11 是一个很大的位,通常权限位不会这么大)
const e = checkPower(c, test);
console.log("auth: " + e);
/**
* 检查用户是否具有指定权限
* @param {number} userPurview - 用户拥有的总权限值(位掩码)
* @param {number} optPurview - 要检查的操作权限位(例如 3 表示删除B)
* @returns {boolean} 是否拥有该权限
*/
function checkPower(userPurview, optPurview) {
const purviewValue = 2 ** optPurview; // 等价于 1 << optPurview
return (userPurview & purviewValue) === purviewValue;
}