mirror of
https://github.com/Sea-Haven-Industries/shoc-backend.git
synced 2026-09-30 09:33:13 +00:00
231 lines
9.3 KiB
C#
231 lines
9.3 KiB
C#
|
|
using Api.SeaHavenIndustries.DTOs;
|
|||
|
|
using Api.SeaHavenIndustries.Helper;
|
|||
|
|
using Data.SeaHavenIndustries;
|
|||
|
|
using Microsoft.AspNetCore.Authorization;
|
|||
|
|
using Microsoft.AspNetCore.Identity;
|
|||
|
|
using Microsoft.AspNetCore.Mvc;
|
|||
|
|
using Microsoft.EntityFrameworkCore;
|
|||
|
|
using System.Security.Claims;
|
|||
|
|
using System.Security.Cryptography;
|
|||
|
|
|
|||
|
|
namespace Api.SeaHavenIndustries.Controllers
|
|||
|
|
{
|
|||
|
|
[Authorize]
|
|||
|
|
[ApiController]
|
|||
|
|
[Route("[controller]")]
|
|||
|
|
public class UserController : Controller
|
|||
|
|
{
|
|||
|
|
private readonly UserManager<ApplicationUser> _userManager;
|
|||
|
|
private readonly ApplicationDbContext _db;
|
|||
|
|
private readonly SendMessage _sendemail;
|
|||
|
|
|
|||
|
|
public UserController(UserManager<ApplicationUser> userManager, ApplicationDbContext db, SendMessage sendemail)
|
|||
|
|
{
|
|||
|
|
_userManager = userManager;
|
|||
|
|
_db = db;
|
|||
|
|
_sendemail = sendemail;
|
|||
|
|
}
|
|||
|
|
[HttpPost]
|
|||
|
|
[Route("AddUser")]
|
|||
|
|
public async Task<IActionResult> AddUser(User_DTO model)
|
|||
|
|
{
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
ApplicationUser user = new ApplicationUser();
|
|||
|
|
user.EmailConfirmed = true;
|
|||
|
|
user.UserName = model.Email;
|
|||
|
|
user.Email = model.Email;
|
|||
|
|
user.FirstName = model.Name;
|
|||
|
|
user.CreatedDate = DateTime.Now;
|
|||
|
|
user.UniqueName = "Active";
|
|||
|
|
var password = GenerateRandomPassword(8);
|
|||
|
|
var result = await _userManager.CreateAsync(user, password);
|
|||
|
|
if (result.Succeeded)
|
|||
|
|
{
|
|||
|
|
await _userManager.AddToRoleAsync(user, model.Role ?? "");
|
|||
|
|
}
|
|||
|
|
else
|
|||
|
|
{
|
|||
|
|
return BadRequest(result.Errors.FirstOrDefault()?.Description ?? "error");
|
|||
|
|
}
|
|||
|
|
//var request = _httpContextAccessor.HttpContext?.Request;
|
|||
|
|
//var domain = $"{request?.Scheme}://{request?.Host}";
|
|||
|
|
string subject = "Login Information";
|
|||
|
|
//string greeting = $"Dear {model.FirstName},\n\n";
|
|||
|
|
//string loginLink = $"Click here to login:<a href='{domain}/Login'>{domain}/Login</a>\n";
|
|||
|
|
string passwordInfo = $"Your password is: {password}\n\n";
|
|||
|
|
string body = $"{passwordInfo}";
|
|||
|
|
await _sendemail.SendEMail(model?.Email ?? "", subject, body);
|
|||
|
|
|
|||
|
|
return Ok(new DataResponse { Message = "Updated Successfully", Status = "200" });
|
|||
|
|
}
|
|||
|
|
catch (Exception ex)
|
|||
|
|
{
|
|||
|
|
return BadRequest(new Response { Status = "Error", Message = ex.Message });
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
[HttpPost]
|
|||
|
|
[Route("EditUser")]
|
|||
|
|
public async Task<IActionResult> EditUser(EditUser_DTO user)
|
|||
|
|
{
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
var exist = _db.Users.Where(w => w.Id == user.Id).FirstOrDefault();
|
|||
|
|
exist.FirstName = user.Name;
|
|||
|
|
exist.EmailConfirmed = true;
|
|||
|
|
exist.UserName = user.Email;
|
|||
|
|
exist.Email = user.Email;
|
|||
|
|
exist.NormalizedEmail = user.Email.ToUpper();
|
|||
|
|
exist.NormalizedUserName = user.Email.ToUpper();
|
|||
|
|
exist.CreatedDate = DateTime.Now;
|
|||
|
|
exist.UniqueName = "Active";
|
|||
|
|
var existingRole = await _userManager.GetRolesAsync(exist);
|
|||
|
|
|
|||
|
|
if (existingRole != null && existingRole.Any())
|
|||
|
|
{
|
|||
|
|
await _userManager.RemoveFromRolesAsync(exist, existingRole);
|
|||
|
|
}
|
|||
|
|
await _userManager.AddToRoleAsync(exist, user.Role ?? "");
|
|||
|
|
|
|||
|
|
await _db.SaveChangesAsync();
|
|||
|
|
return Ok(new DataResponse { Message = "Updated Successfully", Status = "200" });
|
|||
|
|
}
|
|||
|
|
catch (Exception ex)
|
|||
|
|
{
|
|||
|
|
return BadRequest(new Response { Status = "Error", Message = ex.Message });
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
[HttpGet]
|
|||
|
|
[Route("DeleteUser")]
|
|||
|
|
public async Task<IActionResult> DeleteUser(string id)
|
|||
|
|
{
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
var data = await _db.Users.Where(w => w.Id == id).FirstOrDefaultAsync();
|
|||
|
|
|
|||
|
|
if (data != null)
|
|||
|
|
{
|
|||
|
|
var existworkorder = _db.workOrders.Where(w => w.AssignTo.Contains(data.Id)).ToList();
|
|||
|
|
foreach (var workorder in existworkorder)
|
|||
|
|
{
|
|||
|
|
var existdata = _db.workOrders.Where(w => w.Id == workorder.Id).FirstOrDefault();
|
|||
|
|
existdata.AssignTo = null;
|
|||
|
|
}
|
|||
|
|
var existworkordercomments = _db.Comments.Where(w => w.UserId.Contains(data.Id)).ToList();
|
|||
|
|
foreach (var workorderc in existworkordercomments)
|
|||
|
|
{
|
|||
|
|
var existdatacomm = _db.Comments.Where(w => w.Id == workorderc.Id).FirstOrDefault();
|
|||
|
|
existdatacomm.UserId = null;
|
|||
|
|
}
|
|||
|
|
var existtemplate = _db.Templates.Where(w => w.AssignTo.Contains(data.Id)).ToList();
|
|||
|
|
foreach (var workordert in existtemplate)
|
|||
|
|
{
|
|||
|
|
var existdattem = _db.Templates.Where(w => w.Id == workordert.Id).FirstOrDefault();
|
|||
|
|
existdattem.AssignTo = null;
|
|||
|
|
}
|
|||
|
|
var existtempexistuserrolelate = _db.UserRoles.Where(w => w.UserId.Contains(data.Id)).ToList();
|
|||
|
|
if (existtempexistuserrolelate.Count() > 0)
|
|||
|
|
{
|
|||
|
|
_db.UserRoles.RemoveRange(existtempexistuserrolelate);
|
|||
|
|
}
|
|||
|
|
_db.Users.Remove(data);
|
|||
|
|
}
|
|||
|
|
else
|
|||
|
|
{
|
|||
|
|
return BadRequest(new Response { Status = "Error", Message = "ID not matched!" });
|
|||
|
|
}
|
|||
|
|
await _db.SaveChangesAsync();
|
|||
|
|
return Ok(new DataResponse { Message = "Updated Successfully", Status = "200" });
|
|||
|
|
}
|
|||
|
|
catch (Exception ex)
|
|||
|
|
{
|
|||
|
|
return BadRequest(new Response { Status = "Error", Message = ex.Message });
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
[HttpPost]
|
|||
|
|
[Route("DeleteCurrentUser")]
|
|||
|
|
public async Task<IActionResult> DeleteCurrentUser()
|
|||
|
|
{
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
var userid = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "";
|
|||
|
|
var exist = _db.Users.Where(w => w.Id == userid).FirstOrDefault();
|
|||
|
|
if(exist != null)
|
|||
|
|
{
|
|||
|
|
exist.IsDeleted = true;
|
|||
|
|
}
|
|||
|
|
await _db.SaveChangesAsync();
|
|||
|
|
return Ok(new DataResponse { Message = "Updated Successfully", Status = "200" });
|
|||
|
|
}
|
|||
|
|
catch (Exception ex)
|
|||
|
|
{
|
|||
|
|
return BadRequest(new Response { Status = "Error", Message = ex.Message });
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
[HttpGet]
|
|||
|
|
[Route("UserProfile")]
|
|||
|
|
public async Task<IActionResult> UserProfile()
|
|||
|
|
{
|
|||
|
|
var userid = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "";
|
|||
|
|
|
|||
|
|
var data = await _db.Users.Where(w => w.Id == userid).Select(s => new
|
|||
|
|
{
|
|||
|
|
s.Id,
|
|||
|
|
Name = s.FirstName,
|
|||
|
|
addeddate = s.CreatedDate,
|
|||
|
|
s.Email,
|
|||
|
|
s.Contact
|
|||
|
|
}).ToListAsync();
|
|||
|
|
return Ok(data);
|
|||
|
|
}
|
|||
|
|
public static string GenerateRandomPassword(int length = 8)
|
|||
|
|
{
|
|||
|
|
const string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_-+=<>?";
|
|||
|
|
const string capitalLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|||
|
|
const string digits = "1234567890";
|
|||
|
|
const string symbols = "!@#$%^&*()_-+=<>?";
|
|||
|
|
|
|||
|
|
using (var rng = RandomNumberGenerator.Create())
|
|||
|
|
{
|
|||
|
|
var passwordChars = new char[length];
|
|||
|
|
|
|||
|
|
// Ensure at least one capital letter
|
|||
|
|
passwordChars[0] = capitalLetters[GetNextNonNegativeIndex(rng, capitalLetters.Length)];
|
|||
|
|
|
|||
|
|
// Ensure at least one digit
|
|||
|
|
passwordChars[1] = digits[GetNextNonNegativeIndex(rng, digits.Length)];
|
|||
|
|
|
|||
|
|
// Ensure at least one symbol
|
|||
|
|
passwordChars[2] = symbols[GetNextNonNegativeIndex(rng, symbols.Length)];
|
|||
|
|
|
|||
|
|
// Fill the rest of the password with random characters
|
|||
|
|
for (int i = 3; i < length; i++)
|
|||
|
|
{
|
|||
|
|
passwordChars[i] = validChars[GetNextNonNegativeIndex(rng, validChars.Length)];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Shuffle the password characters, excluding the initial characters
|
|||
|
|
Random random = new Random();
|
|||
|
|
for (int i = length - 1; i > 2; i--)
|
|||
|
|
{
|
|||
|
|
int j = random.Next(2, i + 1);
|
|||
|
|
(passwordChars[i], passwordChars[j]) = (passwordChars[j], passwordChars[i]);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return new string(passwordChars);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static int GetNextNonNegativeIndex(RandomNumberGenerator rng, int maxValue)
|
|||
|
|
{
|
|||
|
|
byte[] randomBytes = new byte[4];
|
|||
|
|
rng.GetBytes(randomBytes);
|
|||
|
|
int nextIndex = BitConverter.ToInt32(randomBytes, 0) % maxValue;
|
|||
|
|
return (nextIndex + maxValue) % maxValue; // Ensure the index is non-negative
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|