1 | using System;
|
---|
2 | using System.Linq;
|
---|
3 | using Microsoft.AspNetCore.Mvc;
|
---|
4 | using db_tsh.Models;
|
---|
5 | using Microsoft.Extensions.Configuration;
|
---|
6 | using System.Data.SqlClient;
|
---|
7 | using System.Collections.Generic;
|
---|
8 | using System.Security.Claims;
|
---|
9 | using Npgsql;
|
---|
10 | using Microsoft.AspNetCore.Authentication.Cookies;
|
---|
11 | using Microsoft.AspNetCore.Authentication;
|
---|
12 | using System.Threading.Tasks;
|
---|
13 | using Renci.SshNet;
|
---|
14 |
|
---|
15 | namespace db_tsh.Controllers
|
---|
16 | {
|
---|
17 | public class AccountController : Controller
|
---|
18 | {
|
---|
19 | private readonly IConfiguration _configuration;
|
---|
20 |
|
---|
21 | public AccountController(IConfiguration configuration)
|
---|
22 | {
|
---|
23 | _configuration = configuration;
|
---|
24 | }
|
---|
25 |
|
---|
26 | private async Task<NpgsqlConnection> OpenDatabaseConnectionAsync()
|
---|
27 | {
|
---|
28 | var dbPort = 9999; // Default PostgreSQL port
|
---|
29 | var dbUser = _configuration["ConnectionStrings:DefaultConnection"].Split(';')[2].Split('=')[1];
|
---|
30 | var dbPassword = _configuration["ConnectionStrings:DefaultConnection"].Split(';')[3].Split('=')[1];
|
---|
31 | var dbName = _configuration["ConnectionStrings:DefaultConnection"].Split(';')[4].Split('=')[1];
|
---|
32 |
|
---|
33 | var connectionString = $"Host=localhost;Port={dbPort};Username={dbUser};Password={dbPassword};Database={dbName}";
|
---|
34 |
|
---|
35 | var conn = new NpgsqlConnection(connectionString);
|
---|
36 | await conn.OpenAsync();
|
---|
37 | return conn;
|
---|
38 | }
|
---|
39 |
|
---|
40 | // Other actions...
|
---|
41 | [HttpGet]
|
---|
42 | public ActionResult RegisterOrLogin()
|
---|
43 | {
|
---|
44 | return View();
|
---|
45 | }
|
---|
46 |
|
---|
47 | [HttpGet]
|
---|
48 | public ActionResult Register()
|
---|
49 | {
|
---|
50 | return View();
|
---|
51 | }
|
---|
52 |
|
---|
53 | [HttpPost]
|
---|
54 | public async Task<IActionResult> RegisterAsync(Customer cust)
|
---|
55 | {
|
---|
56 |
|
---|
57 | if (ModelState.IsValid)
|
---|
58 | {
|
---|
59 | string connectionString = _configuration.GetConnectionString("DefaultConnection");
|
---|
60 | using (NpgsqlConnection con = await OpenDatabaseConnectionAsync())
|
---|
61 | {
|
---|
62 |
|
---|
63 | // Check if email is already registered
|
---|
64 | string checkEmailQuery = "SELECT COUNT(*) FROM project.customer WHERE email = @Email";
|
---|
65 | using (NpgsqlCommand checkEmailCmd = new NpgsqlCommand(checkEmailQuery, con))
|
---|
66 | {
|
---|
67 | checkEmailCmd.Parameters.AddWithValue("@Email", cust.Email);
|
---|
68 | object existingEmailCount = checkEmailCmd.ExecuteScalar();
|
---|
69 |
|
---|
70 | if (existingEmailCount != DBNull.Value && Convert.ToInt32(existingEmailCount) > 0)
|
---|
71 | {
|
---|
72 | ModelState.AddModelError(string.Empty, "Email is already registered.");
|
---|
73 | return View(cust);
|
---|
74 | }
|
---|
75 | }
|
---|
76 |
|
---|
77 | // Insert new user into the database
|
---|
78 | string insertUserQuery = "INSERT INTO project.customer (name, email, password, type) VALUES (@Name, @Email, @Password, true)";
|
---|
79 | using (NpgsqlCommand insertUserCmd = new NpgsqlCommand(insertUserQuery, con))
|
---|
80 | {
|
---|
81 | insertUserCmd.Parameters.AddWithValue("@Name", cust.Name);
|
---|
82 | insertUserCmd.Parameters.AddWithValue("@Email", cust.Email);
|
---|
83 | insertUserCmd.Parameters.AddWithValue("@Password", cust.Password);
|
---|
84 | int rowsAffected = (int)insertUserCmd.ExecuteNonQuery();
|
---|
85 |
|
---|
86 | if (rowsAffected > 0)
|
---|
87 | {
|
---|
88 | ViewData["message"] = "User registered successfully.";
|
---|
89 | return RedirectToAction("Index", "Home");
|
---|
90 | }
|
---|
91 | else
|
---|
92 | {
|
---|
93 | ModelState.AddModelError(string.Empty, "Failed to register user.");
|
---|
94 | return View(cust);
|
---|
95 | }
|
---|
96 | }
|
---|
97 | }
|
---|
98 | }
|
---|
99 | // If model state is not valid, return the registration view with validation errors
|
---|
100 | return View("RegisterOrLogin", cust);
|
---|
101 | }
|
---|
102 |
|
---|
103 |
|
---|
104 | [HttpPost]
|
---|
105 | public async Task<ActionResult> RegisterOrLogin(Customer cust, string email, string password)
|
---|
106 | {
|
---|
107 | // Early exit if email or password is null or empty
|
---|
108 | if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
|
---|
109 | {
|
---|
110 | // Display an error message if either the username or password is missing.
|
---|
111 | ViewData["message"] = "Please enter both username and password.";
|
---|
112 | cust.success = 0;
|
---|
113 | return View();
|
---|
114 | }
|
---|
115 |
|
---|
116 | try
|
---|
117 | {
|
---|
118 | // Use the helper method to get a connection
|
---|
119 | using (NpgsqlConnection sqlcon = await OpenDatabaseConnectionAsync())
|
---|
120 | {
|
---|
121 | string query = "SELECT email, password FROM project.customer WHERE email = @Email AND password = @Password";
|
---|
122 | using (NpgsqlCommand cmd = new NpgsqlCommand(query, sqlcon))
|
---|
123 | {
|
---|
124 | cmd.Parameters.AddWithValue("@Email", email);
|
---|
125 | cmd.Parameters.AddWithValue("@Password", password);
|
---|
126 |
|
---|
127 | using (NpgsqlDataReader sdr = await cmd.ExecuteReaderAsync())
|
---|
128 | {
|
---|
129 | if (sdr.Read()) // If user found
|
---|
130 | {
|
---|
131 | var claims = new List<Claim>
|
---|
132 | {
|
---|
133 | new Claim(ClaimTypes.Name, email)
|
---|
134 | // You can add more claims as needed.
|
---|
135 | };
|
---|
136 |
|
---|
137 | var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
---|
138 | var authProperties = new AuthenticationProperties
|
---|
139 | {
|
---|
140 | // You can customize authentication properties if needed.
|
---|
141 | };
|
---|
142 |
|
---|
143 | await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
|
---|
144 |
|
---|
145 | ViewData["message"] = "User logged in successfully";
|
---|
146 | cust.success = 1;
|
---|
147 |
|
---|
148 | // No need to explicitly close the connection
|
---|
149 | return RedirectToAction("Index", "Home");
|
---|
150 | }
|
---|
151 | else // User not found
|
---|
152 | {
|
---|
153 | ViewBag.Errorpass = "Email and password are incorrect!";
|
---|
154 | cust.success = 0;
|
---|
155 | return View();
|
---|
156 | }
|
---|
157 | }
|
---|
158 | }
|
---|
159 | }
|
---|
160 | }
|
---|
161 | catch (Exception ex)
|
---|
162 | {
|
---|
163 | // Log the exception or handle error
|
---|
164 | ViewData["message"] = "An error occurred while logging in: " + ex.Message;
|
---|
165 | cust.success = 0;
|
---|
166 | return View();
|
---|
167 | }
|
---|
168 | }
|
---|
169 |
|
---|
170 |
|
---|
171 |
|
---|
172 | [HttpGet]
|
---|
173 | public async Task<IActionResult> LogoutAsync()
|
---|
174 | {
|
---|
175 | await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
---|
176 |
|
---|
177 | return View("RegisterOrLogin");
|
---|
178 | }
|
---|
179 | }
|
---|
180 | }
|
---|