Integration of database components for auth and mapping (MySQL)

This commit is contained in:
Josh Deck 2024-08-13 12:42:32 -04:00
parent dd5da99f77
commit 56a100ad96
8 changed files with 159 additions and 59 deletions

View File

@ -0,0 +1,133 @@
using MySql.Data.MySqlClient;
using System.Data;
using Telerik.SvgIcons;
using TSC2.Components.Layout;
namespace TSC2.Components.CSharp
{
public class DatabaseManager
{
private static string _connectionString = "Server=127.0.0.1;User ID=root;Password=root;Database=tsc2";
/**********************************************/
// SHOP INFORMATION
/**********************************************/
public static List<Tuple<double[], string, string>> LoadAllShops()
{
List<Tuple<double[], string, string>> results = new List<Tuple<double[], string, string>>();
MySqlConnection conn = new MySqlConnection(_connectionString);
conn.Open();
using (var cmd = new MySqlCommand("SELECT * FROM shopinformation", conn))
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
var uniqueID = reader.GetString(0);
var shopName = reader.GetString(1);
//var address = reader.GetString(2);
//var phone = reader.GetString(3);
//var website = reader.GetString(4);
//var hours = reader.GetString(5);
//var about = reader.GetString(6);
double latitude = reader.GetDouble(7);
double longitude = reader.GetDouble(8);
double[] coords = [latitude, longitude];
Tuple<double[], string, string> tuple = new Tuple<double[], string, string>(coords, shopName, uniqueID);
results.Add(tuple);
}
}
}
return results;
}
/**********************************************/
// LOGIN FLOW
/**********************************************/
public async static Task SignInGoogle()
{
MySqlConnection conn = new MySqlConnection(_connectionString);
conn.Open();
using (var cmd = new MySqlCommand("SELECT * FROM userinformation WHERE Platform='Google' AND Token='" + MainLayout.Session["id"] + "'", conn))
using (var count_cmd = new MySqlCommand("SELECT COUNT(*) FROM (SELECT * FROM userinformation WHERE Platform='Google' AND Token='" + MainLayout.Session["id"] + "') AS result", conn))
{
int count = Convert.ToInt32(count_cmd.ExecuteScalar());
if (count == 0) // User is not already in our database
{
try
{
// Generate guid
Guid guid = Guid.NewGuid();
var insert_cmd = new MySqlCommand();
insert_cmd.CommandText = "INSERT INTO userinformation(UniqueID,FullName,Platform,Token) VALUES(@uniqueid,@fullname,@platform,@token)";
insert_cmd.Connection = conn;
insert_cmd.Parameters.AddWithValue("@uniqueid", guid.ToString());
insert_cmd.Parameters.AddWithValue("@fullname", MainLayout.Session["name"]);
insert_cmd.Parameters.AddWithValue("@platform", "Google");
insert_cmd.Parameters.AddWithValue("@token", MainLayout.Session["id"]);
insert_cmd.ExecuteNonQuery();
MainLayout.Session.Add("unique_id", guid.ToString());
}
catch(Exception ex)
{
await Console.Out.WriteLineAsync(ex.Message);
}
}
}
conn.Close();
}
public async static Task SignInFacebook()
{
MySqlConnection conn = new MySqlConnection(_connectionString);
conn.Open();
using (var cmd = new MySqlCommand("SELECT * FROM userinformation WHERE Platform='Facebook' AND Token='" + MainLayout.Session["id"] + "'", conn))
using (var count_cmd = new MySqlCommand("SELECT COUNT(*) FROM (SELECT * FROM userinformation WHERE Platform='Facebook' AND Token='" + MainLayout.Session["id"] + "') AS result", conn))
{
int count = Convert.ToInt32(count_cmd.ExecuteScalar());
if (count == 0) // User is not already in our database
{
try
{
// Generate guid
Guid guid = Guid.NewGuid();
var insert_cmd = new MySqlCommand();
insert_cmd.CommandText = "INSERT INTO userinformation(UniqueID,FullName,Platform,Token) VALUES(@uniqueid,@fullname,@platform,@token)";
insert_cmd.Connection = conn;
insert_cmd.Parameters.AddWithValue("@uniqueid", guid.ToString());
insert_cmd.Parameters.AddWithValue("@fullname", MainLayout.Session["name"]);
insert_cmd.Parameters.AddWithValue("@platform", "Facebook");
insert_cmd.Parameters.AddWithValue("@token", MainLayout.Session["id"]);
insert_cmd.ExecuteNonQuery();
MainLayout.Session.Add("unique_id", guid.ToString());
}
catch (Exception ex)
{
await Console.Out.WriteLineAsync(ex.Message);
}
}
}
conn.Close();
}
}
}

View File

@ -1,25 +1,19 @@
namespace TSC2.Components; using TSC2.Components.CSharp;
namespace TSC2.Components;
public class MapDriver public class MapDriver
{ {
public static List<(double[], string)> InitializeMarkers(double[] inputCoords) public static List<Tuple<double[], string, string>> InitializeMarkers()
{ {
// Initialization // Initialization
List<(double[], string)> results = []; List<Tuple<double[], string, string>> results = [];
// Read list of addresses and names from DB and contact search API to get location // Read list of addresses and names from DB
List<(double[] Coords, string Name)> db = new List<(double[], string)>(); List<Tuple<double[], string, string>> db = DatabaseManager.LoadAllShops();
db.Add(([42.4649, -83.3684], "1"));
db.Add(([42.6649, -83.5684], "2"));
db.Add(([42.8649, -83.7684], "3"));
foreach (var entry in db) foreach (var entry in db)
{ {
(double[] Coords, string Name) info = ([], ""); Tuple<double[], string, string> info = new Tuple<double[], string, string>(entry.Item1, entry.Item2, entry.Item3);
// Read address and contact POI
info.Coords = entry.Coords; // TODO: replace with API lookup for the current entry's address
info.Name = entry.Name; // TODO: replace with name found in DB
results.Add(info); results.Add(info);
} }
return results; return results;

View File

@ -21,7 +21,6 @@
// This should only execute if the user is signed in AND is the first render // This should only execute if the user is signed in AND is the first render
Greeting = "Hello, " + Session["name"]; Greeting = "Hello, " + Session["name"];
Console.Out.WriteLine("Updated greeting");
} }
@ -30,7 +29,6 @@
{ {
Session = new Dictionary<string, string>(); Session = new Dictionary<string, string>();
_navigationManager.NavigateTo("/"); _navigationManager.NavigateTo("/");
Console.WriteLine("Signed out");
} }
} }
} }

View File

@ -1,6 +1,7 @@
@using System.Net.Http; @using System.Net.Http;
@using System.Text.Json; @using System.Text.Json;
@using TSC2.Components.Layout; @using TSC2.Components.Layout;
@using TSC2.Components.CSharp;
@page "/signin-facebook" @page "/signin-facebook"
@ -45,8 +46,6 @@
var id_json = await client.GetStringAsync("https://graph.facebook.com/me?fields=id&access_token=" + tokenResponse.access_token); var id_json = await client.GetStringAsync("https://graph.facebook.com/me?fields=id&access_token=" + tokenResponse.access_token);
FacebookAuthResponse id_response = JsonSerializer.Deserialize<FacebookAuthResponse>(id_json); FacebookAuthResponse id_response = JsonSerializer.Deserialize<FacebookAuthResponse>(id_json);
Console.WriteLine("ID: " + id_response.id);
// Configure the request // Configure the request
List<KeyValuePair<string, string>> requestData = new List<KeyValuePair<string, string>>(); List<KeyValuePair<string, string>> requestData = new List<KeyValuePair<string, string>>();
requestData.Add(new KeyValuePair<string, string>("access_token", tokenResponse.access_token)); requestData.Add(new KeyValuePair<string, string>("access_token", tokenResponse.access_token));
@ -71,7 +70,9 @@
MainLayout.Session.Add("id", profileResponse.id); MainLayout.Session.Add("id", profileResponse.id);
MainLayout.Session.Add("name", profileResponse.name); MainLayout.Session.Add("name", profileResponse.name);
MainLayout.UpdateGreeting(); MainLayout.UpdateGreeting();
Console.WriteLine("Signed in successfully. (FB)");
// Contact database
DatabaseManager.SignInFacebook();
} }
_navigationManager.NavigateTo("/"); _navigationManager.NavigateTo("/");

View File

@ -1,6 +1,7 @@
@using System.Net.Http; @using System.Net.Http;
@using System.Text.Json; @using System.Text.Json;
@using TSC2.Components.Layout; @using TSC2.Components.Layout;
@using TSC2.Components.CSharp;
@page "/signin-google" @page "/signin-google"
@ -38,7 +39,7 @@
auth_json = await response.Content.ReadAsStringAsync(); auth_json = await response.Content.ReadAsStringAsync();
} }
OAuthTokenResponse tokenResponse = JsonSerializer.Deserialize<OAuthTokenResponse>(auth_json); OAuthTokenResponse tokenResponse = JsonSerializer.Deserialize<OAuthTokenResponse>(auth_json);
Console.WriteLine("AUTH: " + auth_json);
// Use the access token to access their information; name, email, & token // Use the access token to access their information; name, email, & token
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
@ -47,16 +48,16 @@
} }
GoogleProfileResponse profileResponse = JsonSerializer.Deserialize<GoogleProfileResponse>(profile_json); GoogleProfileResponse profileResponse = JsonSerializer.Deserialize<GoogleProfileResponse>(profile_json);
Console.WriteLine("PROFILE: " + profile_json);
if (MainLayout.Session.Count == 0) // Fpr security, only add to the session if nothing exists in the session. if (MainLayout.Session.Count == 0) // Fpr security, only add to the session if nothing exists in the session.
{ {
// Add variables to the session
MainLayout.Session.Add("id", profileResponse.id); MainLayout.Session.Add("id", profileResponse.id);
MainLayout.Session.Add("email", profileResponse.email); MainLayout.Session.Add("email", profileResponse.email);
MainLayout.Session.Add("name", profileResponse.name); MainLayout.Session.Add("name", profileResponse.name);
MainLayout.UpdateGreeting(); MainLayout.UpdateGreeting();
Console.WriteLine("Signed in successfully.");
// Contact database
DatabaseManager.SignInGoogle();
} }
_navigationManager.NavigateTo("/"); _navigationManager.NavigateTo("/");

View File

@ -22,22 +22,7 @@
<meta name="description" content="Create New &amp; Used Car Sale Websites with Canvas Template. Get Canvas to build powerful websites easily with the Highly Customizable &amp; Best Selling Bootstrap Template, today."> <meta name="description" content="Create New &amp; Used Car Sale Websites with Canvas Template. Get Canvas to build powerful websites easily with the Highly Customizable &amp; Best Selling Bootstrap Template, today.">
<!-- Document Title <!-- Document Title
============================================= --> ============================================= -->
<title>Dealers - Car | Canvas</title> <title>The Shop Critics</title>
<TelerikButton OnClick="@SayHelloHandler" ThemeColor="primary">Say Hello</TelerikButton>
<br />
@helloString
@code {
MarkupString helloString;
void SayHelloHandler()
{
string msg = string.Format("Hello from <strong>Telerik Blazor</strong> at {0}.<br /> Now you can use C# to write front-end!", DateTime.Now);
helloString = new MarkupString(msg);
}
}
<style> <style>
.dropdown-toggle::after { .dropdown-toggle::after {

View File

@ -27,20 +27,13 @@ namespace TSC2.Components.Pages
protected override void OnInitialized() // Executes every page load; run inexpensive rendering code here protected override void OnInitialized() // Executes every page load; run inexpensive rendering code here
{ {
Console.WriteLine("MapRef null? : " + (MapRef == null ? "yes" : "no"));
InitializeMapMarkers(Center); InitializeMapMarkers(Center);
MapRef?.Refresh(); MapRef?.Refresh();
Console.WriteLine("Initial refresh");
Center = [42.4649, -83.3684]; Center = [42.4649, -83.3684];
Zoom = 11; Zoom = 11;
Console.WriteLine("Map initialized @ " + Center[0] + " " + Center[1]);
InitializeMapMarkers(Center); InitializeMapMarkers(Center);
MapRef?.Refresh(); MapRef?.Refresh();
Console.WriteLine("IsVisible: " + (MapRef == null ? "false" : "true"));
} }
@ -52,31 +45,25 @@ namespace TSC2.Components.Pages
CurrentSelection = dataItem.Title; CurrentSelection = dataItem.Title;
CurrentBlurb = dataItem.Blurb; CurrentBlurb = dataItem.Blurb;
ToggleModal(); ToggleModal();
Console.WriteLine(dataItem.Title);
} }
public List<MarkerModel> MapMarkers { get; set; } = new List<MarkerModel>() public List<MarkerModel> MapMarkers { get; set; } = new List<MarkerModel>();
{
new MarkerModel()
{
Title = ""
}
};
private void InitializeMapMarkers(double[] coords) private void InitializeMapMarkers(double[] coords)
{ {
// Server call to load map markers into a list of tuples // Server call to load map markers into a list of tuples
List<(double[], string)> localMarkers = MapDriver.InitializeMarkers(coords); List<Tuple<double[], string, string>> localMarkers = MapDriver.InitializeMarkers();
foreach (var current in localMarkers) foreach (var current in localMarkers)
{ {
MapMarkers.Add(new MarkerModel() MapMarkers.Add(new MarkerModel()
{ {
LatLng = current.Item1, LatLng = current.Item1,
Title = current.Item2, Title = current.Item2,
UniqueID = current.Item3,
Blurb = string.Format("This is {0}'s blurb. This will be replaced when a lookup is created.", current.Item2) Blurb = string.Format("This is {0}'s blurb. This will be replaced when a lookup is created.", current.Item2)
}); });
} }
@ -114,6 +101,7 @@ namespace TSC2.Components.Pages
public double[] LatLng { get; set; } = [42.4649, -83.3684]; public double[] LatLng { get; set; } = [42.4649, -83.3684];
public string Title { get; set; } = ""; public string Title { get; set; } = "";
public string Blurb { get; set; } = ""; public string Blurb { get; set; } = "";
public string UniqueID { get; set; } = "";
} }
private class LocationDetails private class LocationDetails
@ -153,7 +141,6 @@ namespace TSC2.Components.Pages
public void ToggleModal() public void ToggleModal()
{ {
Console.WriteLine("TOGGLING");
//await Console.Out.WriteLineAsync("IWNAJNQADJK" + isVisible); //await Console.Out.WriteLineAsync("IWNAJNQADJK" + isVisible);
if (isVisible) if (isVisible)
isVisible = false; isVisible = false;

View File

@ -12,6 +12,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="8.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="8.0.0" />
<PackageReference Include="MySql.Data" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Telerik.UI.for.Blazor" Version="6.0.2" /> <PackageReference Include="Telerik.UI.for.Blazor" Version="6.0.2" />
</ItemGroup> </ItemGroup>