Advertisement
Guest User

Untitled

a guest
Feb 12th, 2017
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.23 KB | None | 0 0
  1. <?php
  2.  
  3. namespace AppHttpControllers;
  4.  
  5. use AppLibrariesCryptor;
  6. use AppLibrariesErrorLogging;
  7. use AppLibrariesRandomObjectGeneration;
  8. use AppModelsSessions;
  9. use AppModelsTwo_Factor;
  10. use AppModelsUser;
  11. use AppModelsUser_Permissions;
  12. use IlluminateDatabaseQueryException;
  13. use IlluminateHttpRequest;
  14. use LeagueFlysystemException;
  15.  
  16. class AuthController extends Controller
  17. {
  18. /**
  19. * create
  20. * Create a new user instance after a valid registration.
  21. *
  22. * @param Request $request
  23. * @return User
  24. */
  25. public static function create(Request $request) {
  26. try {
  27. if($request->input('emailText') != $request->input('confirmEmailText')) {
  28. return redirect()->route('register');
  29. }
  30.  
  31. $email = $request->input('emailText');
  32. $username = $request->input('usernameText');
  33. $password = RandomObjectGeneration::random_str(intval(getenv('DEFAULT_LENGTH_PASSWORDS')),true);
  34.  
  35. $user = User::create([
  36. 'Username' => $username,
  37. 'Email' => $email,
  38. 'FirstName' => $request->input('firstNameText'),
  39. 'LastName' => $request->input('lastNameText'),
  40. 'MiddleInitial' => $request->input('middleInitialText'),
  41. 'Password' => password_hash($password,PASSWORD_DEFAULT),
  42. '2FA' => 0,
  43. ]);
  44.  
  45. EmailController::sendNewAccountEmail($user,$password);
  46. return redirect()->route('users');
  47.  
  48. } catch(QueryException $qe) {
  49. if(strpos($qe->getMessage(),"1062 Duplicate entry 'admin'") !== false) {
  50. return redirect()->route('register'); //return with username exists error
  51. }
  52. return redirect()->route('register'); //return with unknown error
  53.  
  54. } catch(Exception $e) {
  55. ErrorLogging::logError($e);
  56. return abort('500');
  57. }
  58. }
  59.  
  60. /**
  61. * authenticate
  62. * Authenticates the user against the user's database object. Submits to 2FA if they have
  63. * the option enabled, otherwise logs the user in.
  64. *
  65. * @param Request $request
  66. * @return IlluminateHttpRedirectResponse
  67. */
  68. public static function authenticate(Request $request) {
  69. try {
  70. $user = User::where('Username',$request->input('usernameText'))->first();
  71. if(empty($user) || !password_verify($request->input('passwordText'),$user->Password)) {
  72. return redirect()->route('login');
  73. }
  74.  
  75. $session = Sessions::where('UserId',$user->Id)->first();
  76. if(!empty($session)) {
  77. $session->delete();
  78. }
  79.  
  80. $ip = $_SERVER['REMOTE_ADDR'];
  81. $cryptor = new Cryptor();
  82.  
  83. if($user->getAttribute('2FA') === 1) {
  84. $twoFactor = Two_Factor::where([
  85. 'UserId' => $user->Id, 'Ip' => $ip
  86. ])->first();
  87. if(!empty($twoFactor)) {
  88. $twoFactor->delete();
  89. }
  90.  
  91. $code = RandomObjectGeneration::random_str(6,false,'1234567890');
  92. $twoFactor = Two_Factor::create([
  93. 'UserId' => $user->Id,
  94. 'Ip' => $_SERVER['REMOTE_ADDR'],
  95. 'Code' => password_hash($code,PASSWORD_DEFAULT)
  96. ]);
  97.  
  98. EmailController::sendTwoFactorEmail($user,$code);
  99.  
  100. $newSession = Sessions::create([
  101. 'UserId' => $user->Id,
  102. 'Ip' => $ip,
  103. 'TwoFactorId' => $twoFactor->Id,
  104. 'Authenticated' => 0
  105. ]);
  106.  
  107. $encryptedSession = $cryptor->encrypt($newSession->Id);
  108. Session::put('sessionId',$encryptedSession);
  109.  
  110. return redirect()->route('2fa');
  111. }
  112.  
  113. $newSession = Sessions::create([
  114. 'UserId' => $user->Id,
  115. 'Ip' => $ip,
  116. 'Authenticated' => 1
  117. ]);
  118.  
  119. $encryptedSession = $cryptor->encrypt($newSession->Id);
  120. Session::put('sessionId',$encryptedSession);
  121.  
  122. $intended = Session::pull('intended');
  123. if($intended) {
  124. return redirect()->to($intended);
  125. }
  126. return redirect()->route('authHome');
  127.  
  128. } catch(Exception $e) {
  129. ErrorLogging::logError($e);
  130. return abort('500');
  131. }
  132. }
  133.  
  134. /**
  135. * generateTwoFactorPage
  136. * Route for generating the 2FA page.
  137. *
  138. * @return IlluminateHttpRedirectResponse | IlluminateViewView
  139. */
  140. public static function generateTwoFactorPage() {
  141. try {
  142. if(Session::has('sessionId')) {
  143. $cryptor = new Cryptor();
  144.  
  145. $sessionId = $cryptor->decrypt(Session::get('sessionId'));
  146. $session = Sessions::where('Id',$sessionId)->first();
  147.  
  148. $sessionCheck = self::activeSessionCheck($session);
  149. if(!is_null($sessionCheck)) {
  150. return $sessionCheck;
  151. }
  152.  
  153. if(!is_null($session->TwoFactorId)) {
  154. return view('auth.2fa');
  155. }
  156. }
  157. return redirect()->route('login');
  158.  
  159. } catch(Exception $e) {
  160. ErrorLogging::logError($e);
  161. return abort('500');
  162. }
  163. }
  164.  
  165. /**
  166. * twoFactorVerify
  167. * Validates the 2FA code to authenticate the user.
  168. *
  169. * @param Request $request
  170. * @return IlluminateHttpRedirectResponse
  171. */
  172. public static function twoFactorVerify(Request $request) {
  173. try {
  174. if(!Session::has('sessionId')) {
  175. return redirect()->route('login');
  176. }
  177. $cryptor = new Cryptor();
  178.  
  179. $sessionId = $cryptor->decrypt(Session::get('sessionId'));
  180. $session = Sessions::where('Id',$sessionId)->first();
  181.  
  182. $sessionCheck = self::activeSessionCheck($session);
  183. if(!is_null($sessionCheck)) {
  184. return $sessionCheck;
  185. }
  186.  
  187. $twoFactor = Two_Factor::where([
  188. 'UserId' => $session->UserId, 'Ip' => $_SERVER['REMOTE_ADDR']
  189. ])->first();
  190.  
  191. if(!password_verify($request->input('codeText'),$twoFactor->Code)) {
  192. return redirect()->route('2fa');
  193. }
  194.  
  195. $session->update([
  196. 'TwoFactorId' => null,
  197. 'Authenticated' => 1
  198. ]);
  199.  
  200. $twoFactor->delete();
  201.  
  202. $intended = Session::get('intended');
  203. if($intended) {
  204. return redirect()->to($intended);
  205. }
  206. return redirect()->route('authHome');
  207.  
  208. } catch(Exception $e) {
  209. ErrorLogging::logError($e);
  210. return abort('500');
  211. }
  212. }
  213.  
  214. /**
  215. * resend2FA
  216. * Generates and sends a new 2FA code.
  217. *
  218. * @return IlluminateHttpRedirectResponse
  219. */
  220. public static function resend2FA() {
  221. try {
  222. if(!Session::has('sessionId')) {
  223. return redirect()->route('login');
  224. }
  225. $cryptor = new Cryptor();
  226.  
  227. $sessionId = $cryptor->decrypt(Session::get('sessionId'));
  228. $session = Sessions::where('Id',$sessionId)->first();
  229.  
  230. $sessionCheck = self::activeSessionCheck($session);
  231. if(!is_null($sessionCheck)) {
  232. return $sessionCheck;
  233. }
  234.  
  235. $user = User::where('Id',$session->UserId)->first();
  236. if(empty($user)) {
  237. return redirect()->route('login');
  238. }
  239.  
  240. $twoFactor = Two_Factor::where([
  241. 'UserId' => $session->UserId, 'Ip' => $_SERVER['REMOTE_ADDR']
  242. ])->first();
  243. if(!empty($twoFactor)) {
  244. $twoFactor->delete();
  245. }
  246.  
  247. $code = RandomObjectGeneration::random_str(6, '1234567890');
  248. Two_Factor::create([
  249. 'UserID' => $session->UserId,
  250. 'Ip' => $_SERVER['REMOTE_ADDR'],
  251. 'Code' => password_hash($code,PASSWORD_DEFAULT)
  252. ]);
  253.  
  254. EmailController::sendTwoFactorEmail($user,$code);
  255. return redirect()->route('2fa');
  256.  
  257. } catch(Exception $e) {
  258. ErrorLogging::logError($e);
  259. return abort('500');
  260. }
  261. }
  262.  
  263. /**
  264. * activeSessionCheck
  265. * Helper function to check session objects.
  266. *
  267. * @param $session The session to check.
  268. * @return IlluminateHttpRedirectResponse | null
  269. */
  270. private static function activeSessionCheck($session) {
  271. if($session->Ip !== $_SERVER['REMOTE_ADDR']) {
  272. $session->delete();
  273. Session::forget('sessionId');
  274. return redirect()->route('login');
  275. }
  276.  
  277. if($session->Authenticated === 1) {
  278. return redirect()->route('authHome');
  279. }
  280. return null;
  281. }
  282.  
  283. /**
  284. * check
  285. * Validates if the user is authenticated on this IP Address.
  286. *
  287. * @return bool
  288. */
  289. public static function check() {
  290. if(!Session::has('sessionId')) {
  291. return false;
  292. }
  293. $cryptor = new Cryptor();
  294.  
  295. $sessionId = $cryptor->decrypt(Session::get('sessionId'));
  296. $session = Sessions::where('Id', $sessionId)->first();
  297.  
  298. if($session->Ip !== $_SERVER['REMOTE_ADDR']) {
  299. $session->delete();
  300. Session::forget('sessionId');
  301. return false;
  302. }
  303. return true;
  304. }
  305.  
  306. /**
  307. * adminCheck
  308. * Validates if the user is an authenticated admin user.
  309. *
  310. * @return bool
  311. */
  312. public static function adminCheck() {
  313. $check = self::check();
  314. if(!$check) {
  315. return $check;
  316. }
  317.  
  318. $cryptor = new Cryptor();
  319.  
  320. $sessionId = $cryptor->decrypt(Session::get('sessionId'));
  321. $session = Sessions::where('Id', $sessionId)->first();
  322.  
  323. $user = User::where('Id',$session->UserId)->first();
  324. if(empty($user)) {
  325. $session->delete();
  326. Session::forget('sessionId');
  327. return false;
  328. }
  329.  
  330. if($user->UserType !== 1) {
  331. return false;
  332. }
  333. return true;
  334. }
  335.  
  336. /**
  337. * logout
  338. * Removes session variables storing the authenticated account.
  339. *
  340. * @return IlluminateHttpRedirectResponse
  341. */
  342. public static function logout() {
  343. $cryptor = new Cryptor();
  344.  
  345. $sessionId = $cryptor->decrypt(Session::get('sessionId'));
  346. Sessions::where('Id', $sessionId)->first()->delete();
  347. Session::forget('sessionId');
  348.  
  349. return redirect()->route('login');
  350. }
  351.  
  352. /**
  353. * generateLogin
  354. * Generates the login page.
  355. *
  356. * @return IlluminateHttpRedirectResponse | IlluminateViewView
  357. */
  358. public static function generateLogin() {
  359. if(self::check()) {
  360. return redirect()->route('authHome');
  361. }
  362. return view('auth.login');
  363. }
  364.  
  365. /**
  366. * generateRegister
  367. * Generates the register page if the user is an admin.
  368. *
  369. * @return IlluminateHttpRedirectResponse | IlluminateViewView
  370. */
  371. public static function generateRegister() {
  372. if(self::adminCheck()) {
  373. $permissions = User_Permissions::all();
  374. $variables = array('permissions'=>$permissions);
  375. return view('auth.register')->with($variables);
  376. }
  377. return abort('401');
  378. }
  379. }
  380.  
  381. <?php
  382.  
  383. namespace AppLibraries;
  384.  
  385. use DoctrineInstantiatorExceptionInvalidArgumentException;
  386.  
  387.  
  388. class RandomObjectGeneration
  389. {
  390. const KEYSPACE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  391. const PASSWORD_KEYSPACE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%&';
  392.  
  393. /**
  394. * random_str
  395. * Generates a random string.
  396. *
  397. * @param int $length Length of string to be returned
  398. * @param bool $passwordFlag Boolean flag identifying whether string will be a password
  399. * @param string $keyspace Allowed characters to be used in string
  400. * @throws InvalidArgumentException
  401. * @return string
  402. */
  403. public static function random_str($length, $passwordFlag = false, $keyspace = RandomObjectGeneration::KEYSPACE)
  404. {
  405. if($passwordFlag) {
  406. $keyspace = RandomObjectGeneration::PASSWORD_KEYSPACE;
  407. }
  408. if(empty($length) || !is_int($length) || $length < 0) {
  409. $message = 'Random String Generation: Length is Invalid. Length must be a positive integer. Value Provided: ' .
  410. var_export($length);
  411. throw new InvalidArgumentException($message);
  412. }
  413. if(empty($keyspace) || !is_string($keyspace)) {
  414. $message = 'Random String Generation: Invalid Keyspace';
  415. throw new InvalidArgumentException($message);
  416. }
  417. $str = '';
  418. $max = mb_strlen($keyspace) - 1;
  419. for ($i = 0; $i < $length; ++$i) {
  420. $str .= $keyspace[random_int(0, $max)];
  421. }
  422. return $str;
  423. }
  424. }
  425.  
  426. <?php
  427.  
  428. namespace AppModels;
  429.  
  430.  
  431. use IlluminateDatabaseEloquentModel;
  432.  
  433. class Sessions extends Model
  434. {
  435. protected $table = 'sessions';
  436.  
  437. protected $primaryKey = 'Id';
  438.  
  439. protected $fillable = ['UserId',
  440. 'Ip',
  441. 'TwoFactorId',
  442. 'Authenticated'
  443. ];
  444. }
  445.  
  446. <?php
  447.  
  448. namespace AppLibraries;
  449.  
  450.  
  451. use IlluminateSupportFacadesLog;
  452.  
  453. class ErrorLogging
  454. {
  455. public static function logError(Exception $e) {
  456. $message = $e->getCode() . ': ' . $e->getMessage() . PHP_EOL;
  457. $message .= $e->getTraceAsString() . PHP_EOL;
  458. $message .= str_repeat('-',100) . PHP_EOL . PHP_EOL;
  459. Log::error($message);
  460. }
  461. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement