From 56541badf563d33a49d480a6e965c007e79d5d75 Mon Sep 17 00:00:00 2001
From: Victor Wagner <wagner@atlas-card.ru>
Date: Tue, 8 Oct 2013 17:39:19 +0400
Subject: [PATCH] create method

---
 MANIFEST                |  1 +
 lib/VJournal/Session.pm | 57 +++++++++++++++++++++++++++++++++++++++--
 2 files changed, 56 insertions(+), 2 deletions(-)

diff --git a/MANIFEST b/MANIFEST
index 31fd4b4..7a17737 100644
--- a/MANIFEST
+++ b/MANIFEST
@@ -1,4 +1,5 @@
 Makefile.PL
 MANIFEST
 lib/VJournal/Format.pm
+lib/VJournal/Session.pm
 t/user_link.t
diff --git a/lib/VJournal/Session.pm b/lib/VJournal/Session.pm
index f07ce4e..989c7aa 100644
--- a/lib/VJournal/Session.pm
+++ b/lib/VJournal/Session.pm
@@ -94,7 +94,7 @@ sub new {
 			[$cgi->cookie(-name=>COOKIE_NAME,-value=>$sess_id,-expires=>
 				$expire)];
 		}	
-		return bless $pkg,$me;
+		return bless $me,$pkg;
 	}
 }	
 
@@ -124,10 +124,63 @@ sub create {
 		croak("Invalid call to ".$pkg."->create");
 	}	
 	my %params = @_;
-	croack("User name is required by ".$pkg."->creae");
+	croack("User name is required by ".$pkg."->creae") unless $params{-user};
 	$params{-cgi}=CGI->new() if(!$params{-cgi});
 	load_config($params{-cgi});
+	my $user=$params{-user};
+	my %users;
+	my %sessions;
+	dbmopen %users,$config{-userbase},0644;
+	my $session={-cgi=>$params{-cgi},-name=>$params{-user}};
+	if (!exists($users{$user})) {
+		# New user come.
+		require VJournal::Avatar;
+		my @avatar;
+		if (exists $params{-avatar}) {
+			@avatar = VJournal::Avatar::cache($params{-avatar});
+		} else {	
+			@avatar = VJournal::Avatar::by_openid($user);
+		}
+		if (!@avatar && exists $params{-email}) {
+			@avatar = VJournal::Avatar::by_email($params{-email});
+		}
+		my %a = @avatar;
+		$users{$user}=join(":",$params{-email},$a{-src},$a{-width},$a{-height});
+	}
+	my ($email,$avatarsrc,$avatarwidth,$avatarheight)=split(":",$users{$user});
+	$session->{-email} = $email if $email;
+	if ($avatarsrc) {
+		$session->{-avatar} = $avatarsrc;
+		$session->{-avwidth} = $avatarwidth;
+		$session->{-avheight} = $avatarheight;
+	}
+	my $expire = time()+$config{-sessiontime};
+	require Digest::MD5;
+	my
+	$sessioninfo=join(":",$user,$avatarsrc,$email,$avatarwidth,$avatarheight,
+		($params{-bind_to_ip}?$session->{-cgi}->remote_addr():""),$expire);
+	$session->{-id} = Digest::MD5::md5_base64($sessioninfo);
+	$sessions{$session->{-id}} = $sessioninfo;
+	bless $session,$pkg;			
+	$session->{-cookie}=
+			[$session->cookie(-name=>COOKIE_NAME,-value=>$session->{-id},-expires=>
+				$expire)];
+	return $session			
+}
 
+=head2 set_cookie
+
+	$s->set_cookie($s->cookie(-name=>name,-value=>value));
+
+Stores new cookie to be send to client inside the session object.
+They would be output when $s->header would be printed.
+
+=cut
+
+sub set_cookie {
+	my $self=shift;
+	$self->{-cookie}=[] if !exists $self->{-cookie};
+	push @{$self->{-cookie}},@_;
 }
 
 =head2 avatar
-- 
2.39.5