source: redirect.php

Last change on this file was e3d4e0a, checked in by Vlado 222039 <vlado.popovski@…>, 6 days ago

Upload project files

  • Property mode set to 100644
File size: 2.1 KB
Line 
1<?php
2
3session_start();
4
5require __DIR__ . "/vendor/autoload.php";
6
7$client = new Google\Client;
8
9$client->setClientId("");
10$client->setClientSecret("");
11$client->setRedirectUri('http://localhost:8000/redirect.php');
12
13if (!isset($_GET["code"])) {
14 exit("Login Failed: No authorization code received.");
15}
16
17try {
18 $token = $client->fetchAccessTokenWithAuthCode($_GET["code"]);
19
20 if (isset($token["error"])) {
21 exit("Error fetching access token: " . $token["error"]);
22 }
23
24 $client->setAccessToken($token["access_token"]);
25
26 $oauth = new Google\Service\Oauth2($client);
27 $userinfo = $oauth->userinfo->get();
28
29 if (!$userinfo || !isset($userinfo->email) || !isset($userinfo->name)) {
30 exit("Error: Invalid user data.");
31 }
32
33 $email = $userinfo->email;
34 $username = $userinfo->name;
35
36 require "./connect.php";
37
38 $sql = "SELECT * FROM users WHERE email = ?";
39 $stmt = $conn->prepare($sql);
40 $stmt->bind_param("s", $email);
41 $stmt->execute();
42 $result = $stmt->get_result();
43
44 if ($result->num_rows > 0) {
45 // User already exists
46 $user = $result->fetch_assoc();
47 $_SESSION['email'] = $email;
48 $_SESSION['user_ID'] = $user['user_ID'];
49 $_SESSION['is_admin'] = $user['is_admin'];
50 header("Location: /Home.php");
51 } else {
52 // New user
53 $username = explode("@", $email)[0];
54 $password = '';
55
56 $sql = "INSERT INTO users (email, username, password) VALUES (?, ?, ?)";
57 $stmt = $conn->prepare($sql);
58 $stmt->bind_param("sss", $email, $username, $password);
59 $stmt->execute();
60
61 $sql = "SELECT * FROM users WHERE email = ?";
62 $stmt = $conn->prepare($sql);
63 $stmt->bind_param("s", $email);
64 $stmt->execute();
65 $result = $stmt->get_result();
66
67 $user = $result->fetch_assoc();
68 $_SESSION['email'] = $email;
69 $_SESSION['user_ID'] = $user['user_ID'];
70 $_SESSION['is_admin'] = $user['is_admin'];
71
72 header("Location: /Home.php");
73 }
74
75 $conn->close();
76} catch (Exception $e) {
77 exit("Error: " . $e->getMessage());
78}
79?>
Note: See TracBrowser for help on using the repository browser.