LoginSignup
0
0

More than 5 years have passed since last update.

権限をどう持つ?

Posted at

よく見かけるDBレイアウト(権限テーブルとか)

id name read write exec
001 taro 1 0 0

権限項目が増えると...

  • カラムが増える
  • SQLが変わる
  • コードが変わる

面倒。

ビットマスク

上述の3カラム(read,write,exec)を繋げて2進数にして、

8進表記に変換したものを1カラムで管理。

unixのファイルパーミッションみたいな感じ。

read - write - exec

100

4

id name permission
001 taro 4

権限の有無は、該当するビットに1を立てたものと論理積をとる。

論理積はお互い1の場合に1を返すので、権限がない場合は0になる。

# 読み込み権限を持っている
taro_permission = bin(4)     # 0b100

# 読み込み出来る?
read = bin(4)    # 0b100
print(int(taro_permission, 2) & int(read, 2))
# 4 -> で き る

# 書き込み出来る?
write = bin(2)   # 0b010
print(int(taro_permission, 2) & int(write, 2))
# 0 -> で き な い

# 実行出来る?
execute = bin(1)   # 0b001
print(int(taro_permission, 2) & int(execute, 2))
# 0 -> で き な い

# 読み込み or 実行できる?
write_n_exec = bin(3)   # 0b011
print(int(taro_permission, 2) & int(write_n_exec, 2))
# 0 -> や っ ぱ り で き な い

ちょっとスッキリに見える。

コードは短くなった気はするけど、

フィールド増えてくると人間の目では辛くなってくるので結局やめた。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0