# # SimpleAuth.pm -- シンプルな認証モジュール ver.0.2 # # ・PostgreSQL版 (Pgモジュールのみ対応) # ・日本語非対応 # # ゼミ生はソースコードを改変してもいいです。 # 改変した場合、オリジナルと区別するために自分の名前を書いてください。 # # copyright (c) 2010 Hiroshi Nakasone All rights reserved. # package SimpleAuth; use strict; sub new { my $class = shift @_; my $dbobject = shift @_; my $user_management_table = shift @_; my $user_id_field = shift @_; my $user_password_field = shift @_; my $self = { db => $dbobject, user_management_table => $user_management_table, user_id_field => $user_id_field, user_password_field => $user_password_field, }; bless $self, $class; return $self; } sub authorize_user { my $self = shift @_; my $user_id = shift @_; my $password = shift @_; my $sql = "SELECT ".$self->{user_id_field}." FROM ". $self->{user_management_table} . " WHERE ". $self->{user_id_field} ."='".$user_id. "' AND ". $self->{user_password_field} ."='". $password ."';"; my $result = $self->{db}->exec($sql); my $num_of_rows = $result->ntuples; my $session_id = ""; #allow if ($num_of_rows > 0) { $session_id = $self->make_session_id(); my $sql = "INSERT INTO simpleauth_session (session_id, user_id, timestamp) ". "VALUES ('".$session_id."', '".$user_id."', current_timestamp);"; $result = $self->{db}->exec($sql); #DBに入れる } #deny else { $session_id = 0; } return $session_id; } sub authorize_session { my $self = shift @_; my $session_id = shift @_; my $sql = "SELECT user_id FROM simpleauth_session ". "WHERE session_id='". $session_id ."';"; my $result = $self->{db}->exec($sql); my $num_of_rows = $result->ntuples; my $user_id = 0; if ($num_of_rows > 0) { $user_id = $result->getvalue(0,0); } return $user_id; } sub make_session_id { use Digest::MD5 'md5_hex'; my $self = shift @_; my @chars = qw( A B C D E F C H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 0 ); my $base_string = ""; for (my $i=0; $i<52; $i++) { $base_string .= $chars[int(rand(@chars))]; } my $session_id = md5_hex($base_string); return $session_id; } sub get_cookie_value { my $self = shift @_; my $cookie_name = shift @_; my @cookies = ($ENV{'HTTP_COOKIE'}); if ($cookies[0] =~ /; /) { @cookies = split(/; /, $cookies[0]); } my %cookies = {}; foreach my $cookie (@cookies) { my ($key, $value) = split(/=/, $cookie); $cookies{$key} = $value; } if ($cookies{$cookie_name}) { return $self->url_decode($cookies{$cookie_name}); } return 0; } sub url_encode { my $self = shift @_; my $value = shift @_; $value =~ s/(\W)/'%'.unpack('H2', $1)/eg; return $value; } sub url_decode { my $self = shift @_; my $value = shift @_; $value =~ s/%([0-9A-Fa-f][0-9A-Fa-f])/pack('H2', $1)/eg; return $value; } 1;