summaryrefslogtreecommitdiffstats
path: root/pages/login.php
blob: e5ccda84d13659898fdb8f778e0f97e2eb500c4b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
<?php

if ($accepted) {
	if (isset($_GET['mobile']) AND $_GET['mobile'] == 'true') {
		header("Location: $mydomain" . "easytoken");
		exit;
	}
	header("Location: $mydomain");
	exit;
}

require 'includes/openid.php';
include_once 'globe.php';
include_once('./includes/sqlEmbedded.php');
include_once('./includes/datas.php');
include_once('./includes/chats.php');
include_once('./includes/emails.php');
include_once('./includes/HybridAuth/Auth.php');

$hybrid_config_file = 'includes/HybridAuth/HybridAuthConfig.php';

try {
	//OpenID Method
	if (!$_GET['op'] || $_GET['op'] == 'google' || $_GET['op'] == 'steam' || $_GET['op'] == 'yahoo') {
		$openid = new LightOpenID;

		//Require Email, and first name.
		$openid->required = array('namePerson/first', 'contact/email');

		//Are we not logged in?
		if (!$openid->mode) {
			if (!$_GET['op'] || $_GET['op'] == 'google')
				$openid->identity = 'https://www.google.com/accounts/o8/id';
			else if ($_GET['op'] == 'yahoo')
				$openid->identity = 'https://me.yahoo.com';
			else if ($_GET['op'] == 'steam')
				$openid->identity = 'http://steamcommunity.com/openid';

			header('Location: ' . $openid->authUrl());
		} //Did we try to log in, but then the user canceled it?
		else if ($openid->mode == 'cancel') {
			// header('Location: ' . $mydomain);
			//echo 'User has canceled authentication!';
		} //We logged in and it worked!
		else if ($openid->validate()) {
			//What's in the goodie bag labeled "personal information"... hmmm
			$openIdAttributes = $openid->getAttributes();
			$display = $openIdAttributes['namePerson/first'];

			//You don't have a name entered? whyfore!?
			if (strlen($display) == 0) {
				$display = 'noname';
			}
			$email = $openIdAttributes['contact/email'];
			//$claimedid = $openid->__get('identity');
			// Yahoo fix:
			$claimedid = $openid->__get('openid_identity');

			if ($claimedid == "https://open.login.yahooapis.com/openid20/user_profile/xrds") {
				die(throwLoginError($openIdAttributes, "Yahoo went full retard, and didn't send any way for me to identify you..."));
			}
			
			if ($email == '') {
				$openIdAttributes['op'] = $_GET['op'];
				die(throwLoginError($openIdAttributes, "No email provided by OpenID provider - please try a different provider"));
			}
			
			createNewUser($claimedid, $display, $email);
		} else {
			DoRedirect("Login failed. Back to the home page with you!");
		}
	}

	//Use HybridAuth for everything else
	else if ($_GET['op'] == 'twitter' || $_GET['op'] == 'facebook' || $_GET['op'] == 'live') {
		$provider = $_GET['op'];
		$hybridAuth = new Hybrid_Auth($hybrid_config_file);
		$authenticator = $hybridAuth->authenticate($provider);
		
		if(!$authenticator)
		{
			//If user cancelled request, return to home page (?)
			return;
		}
		
		$userProfile = $authenticator->getUserProfile();

		$claimedid = $authenticator->id . '|' . $userProfile->identifier;
		$display = ($userProfile->firstName != '' ? $userProfile->firstName : $userProfile->displayName);
		$email = $userProfile->email;

		//TODO: This will always fail for Twitter - we need to reconsider our needs...
		if($email == '')
		{
			//$userProfile['op'] = $_GET['op']; //TODO This isn't valid, whoops - but, plan on deleting anyways...
			die(throwLoginError($userProfile, "No email provided by {$authenticator->id} - please try a different provider"));
		}
		createNewUser($claimedid, $display, $email);
		return;
		
	//HybridAuth's OpenID Method
//	} else if ($_GET['op'] == 'yahoo') {
//		$config = array( 
//			"base_url" => $mydomain . "HybridAuth/",
//			"providers" => array ( "OpenID" => array ( "enabled" => true ) )
//		);
//		$ha = new Hybrid_Auth( $config );
//		
//		// Authenticate with Yahoo! then grab the user profile
//		$adapter = $ha->authenticate( "OpenID", array( "openid_identifier" => "https://me.yahoo.com/"));
//		$user_profile = $adapter->getUserProfile(); 
	}

	//Unknown provider
	else {
		DoRedirect("Unknown login provider. Back to the home page with you!");
	}
} catch (ErrorException $e) {
	echo $e->getMessage();
}

function createNewUser($claimedid, $display, $email)
{
	//I know just where to put this stuff!
	//Unless I already have this information...
	$sql = "SELECT `ID`, `isAdmin`, `openID`, `displayName`, `dateJoined` FROM `users` WHERE `openID` = '$claimedid' OR `email` = '$email'";
	$result = mysql_query($sql);

	$_SESSION['isAdmin'] = false;

	//What a loser, he's already registered.
	if (mysql_num_rows($result) > 0) {
		$userID = mysql_result($result, 0, 'ID');
		//Is he a cool admin person?
		if (mysql_result($result, 0, 'isAdmin') == 1)
			$_SESSION['isAdmin'] = true;

		$display = mysql_result($result, 0, 'displayName');
		$dateJoined = mysql_result($result, 0, 'dateJoined');

		//Multiple accounts found?
		if (mysql_num_rows($result) > 1) {
			$d['page'] = "Login";
			$d['error'] = "Multiple results on lookup";
			$d['rows'] = mysql_num_rows($result);
			$d['OpenIDProvider'] = $_GET['op'];
			$d['userID'] = $userID;
			$d['claimedid'] = $claimedid;
			$d['email'] = $email;
			$d['display'] = $display;
			EmailError($d);
		}
		// Continue Loging in; should be fine.
		//TEMPORARY CODE
		//Check openID; and update it if necessary
		if (mysql_result($result, 0, 'openID') == $claimedid) {
			//Don't need to do anything
		} else {
			//Update the OpenID Code
			$sql = "UPDATE `users`
				SET `openID` = '$claimedid'
				WHERE `ID` = '$userID'";
			mysql_query($sql);
		}
		// </TEMPORARY CODE>
		//I last-see you now!
		$sql = "UPDATE `users`
         SET `dateLogin` = NOW()
         WHERE `ID` = '$userID'";
		mysql_query($sql);
	} //Well hello there new dude!
	else {

		//About that personal information - give me a second while save it.
		// sql_clean is an addslashes equivilent
		$sql = "INSERT INTO `users` (`openID`, `displayName`, `email`, `dateJoined`, `dateLogin`)
            VALUES (
                  '$claimedid', 
                  '" . sql_clean($display) . "', 
                  '" . sql_clean($email) . "', 
                   NOW(), NOW())";
		$result = mysql_query($sql);
		//Allright, all set.
		if ($result) {
			$userID = mysql_insert_id();
			$dateJoined = date(DateTime::ISO8601);

			//Tutorial done?
			if (isset($_SESSION['preCompletedTutorial'])) {
				if ($_SESSION['preCompletedTutorial'] == true) {
					onCompletedTutorial($userID);
				}
			}
			//Oh crap?
		} else {
			$d['sqlError'] = mysql_error();
			$d['result'] = $result;
			throwLoginError($d, "Unknown DB Registration failure");
			exit;
		}
		addchat(null, "New user registered: \"$display\"");
		sendNewUserEmail($userID, $email, $display, $dateJoined);
	}
	//If 'remember me' use this for cookie password
	//$_SESSION['Passcode'] = MD5($Password.$Pepper.$Username);
	$_SESSION['accepted'] = 1;
	$_SESSION['userID'] = $userID;
	$_SESSION['email'] = $email;
	$_SESSION['displayName'] = $display;
	$_SESSION['dateJoined'] = $dateJoined;

	//The below is me hashing the claimedID.
	//TODO: Store these values in a single location...
	$salt = "33qs5d4j6z98gt1a7n6b5d4x1c66f5nuh8a6d8g9j09aphgf56z5745";
	$pepper = "chilis baby-back ribss! I want my baby back, baby back, baby back, baby back, baby back, I want my, baby backTREE3!";
	$one = MD5($claimedid);
	$two = MD5($one . $salt);
	$three = MD5($pepper . $two);

	$expire = time() + (6 * 31 * 24 * 60 * 60);
	setcookie("userID", $userID, $expire);
	setcookie("doLogin", "yes", $expire);
	setcookie("auth", $three, $expire);

	$refTo = null;
	if (isset($_GET['ref']))
		$refTo = $_GET['ref'];
	//DoRedirect("Thank you $display.", $_GET['ref']);
	DoRedirect("", $refTo, 0);
	exit;
}

function sendNewUserEmail($userID, $email, $display, $dateJoined) {
	global $mydomain;
	$emailBody = "Thank you for signing in to Pathery!

Questions or feedback? Please reply to this email!

Useful Links:
Change your display name: $mydomain" . "cp
View your achievements and stats: $mydomain" . "achievements?id=" . "$userID

Happy Pathing,

 The Pathery Team
";
	$emailSubject = 'Welcome to Pathery.com!';
	QueueEmail(null, $email, $emailSubject, $emailBody, 5);
}

function throwLoginError($data, $explanation) {
	$randCode = rand(10000, 99999);
	$errortext = "<br />Error; $explanation \n
		<br />The error details have been emailed to the administrator.
		<br />If this problem continues; please email me:
		<a target='top' href='mailto:snap@pathery.com?Subject=Pathery%20Login%20Error%20$randCode'>
			snap@pathery.com
		</a>
		<br />Your error code is: $randCode
		<br />";
	$errortext .= mysql_error();
	DoRedirect($errortext, NULL, 500);
	
	$data['explanation'] = $explanation;
	$data['randCode'] = $randCode;
	EmailError($data);
}

?>