Add project files.
This commit is contained in:
17
Controllers/HomeController.cs
Normal file
17
Controllers/HomeController.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
using System.Web.Mvc;
|
||||
|
||||
namespace boilerplate.Controllers
|
||||
{
|
||||
public class HomeController : Controller
|
||||
{
|
||||
// GET: Default
|
||||
public ActionResult Index()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
}
|
||||
}
|
||||
72
Controllers/InMemoryMultipartFormDataStreamProvider.cs
Normal file
72
Controllers/InMemoryMultipartFormDataStreamProvider.cs
Normal file
@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Collections.Specialized;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace boilerplate.Models
|
||||
{
|
||||
public class InMemoryMultipartFormDataStreamProvider : MultipartStreamProvider
|
||||
{
|
||||
private NameValueCollection _formData = new NameValueCollection();
|
||||
private List<HttpContent> _fileContents = new List<HttpContent>();
|
||||
private Collection<bool> _isFormData = new Collection<bool>();
|
||||
public NameValueCollection FormData
|
||||
{
|
||||
get { return _formData; }
|
||||
}
|
||||
public List<HttpContent> Files
|
||||
{
|
||||
get { return _fileContents; }
|
||||
}
|
||||
|
||||
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
|
||||
{
|
||||
ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
|
||||
if (contentDisposition != null)
|
||||
{
|
||||
_isFormData.Add(string.IsNullOrEmpty(contentDisposition.FileName));
|
||||
|
||||
return new MemoryStream();
|
||||
}
|
||||
|
||||
throw new InvalidOperationException(string.Format("Did not find required '{0}' header field in MIME multipart body part..", "Content-Disposition"));
|
||||
}
|
||||
|
||||
public override async Task ExecutePostProcessingAsync()
|
||||
{
|
||||
for (int index = 0; index < Contents.Count; index++)
|
||||
{
|
||||
if (_isFormData[index])
|
||||
{
|
||||
HttpContent formContent = Contents[index];
|
||||
ContentDispositionHeaderValue contentDisposition = formContent.Headers.ContentDisposition;
|
||||
string formFieldName = UnquoteToken(contentDisposition.Name) ?? string.Empty;
|
||||
string formFieldValue = await formContent.ReadAsStringAsync();
|
||||
FormData.Add(formFieldName, formFieldValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
_fileContents.Add(Contents[index]);
|
||||
}
|
||||
}
|
||||
}
|
||||
private static string UnquoteToken(string token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
return token;
|
||||
}
|
||||
|
||||
if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1)
|
||||
{
|
||||
return token.Substring(1, token.Length - 2);
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
}
|
||||
}
|
||||
372
Controllers/PanelController.cs
Normal file
372
Controllers/PanelController.cs
Normal file
@ -0,0 +1,372 @@
|
||||
using boilerplate.Models;
|
||||
using Microsoft.Ajax.Utilities;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.Entity;
|
||||
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
|
||||
using System.Data.Entity.Infrastructure;
|
||||
using System.Data.Entity.SqlServer;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using System.Web.Mvc;
|
||||
using System.Web.UI.WebControls;
|
||||
|
||||
namespace boilerplate.Controllers
|
||||
{
|
||||
public class PanelController : Controller
|
||||
{
|
||||
boilerplateEntities db = new boilerplateEntities();
|
||||
readonly Functions functions = new Functions();
|
||||
|
||||
public async Task<ActionResult> Index()
|
||||
{
|
||||
if (!HasSession()) { return RedirectToAction("Login"); }
|
||||
if (HasSession("ManageDashboard"))
|
||||
{
|
||||
var user = Session["User"] as User;
|
||||
|
||||
ViewBag.Title = "داشبورد";
|
||||
ViewBag.Counter1 = db.Users.Count();
|
||||
ViewBag.Counter2 = db.Users.Count();
|
||||
ViewBag.Counter3 = db.Users.Count();
|
||||
ViewBag.Counter4 = db.Users.Count();
|
||||
ViewBag.Counter5 = db.Users.Count();
|
||||
ViewBag.Counter6 = db.Users.Count();
|
||||
}
|
||||
return View();
|
||||
}
|
||||
|
||||
public async Task<ActionResult> Users()
|
||||
{
|
||||
List<UserModel> models = new List<UserModel>();
|
||||
|
||||
if (!HasSession("ManageUser")) { return RedirectToAction("Index"); }
|
||||
models = db.Users.AsNoTracking().Select(x => new UserModel
|
||||
{
|
||||
Id = x.User_Id,
|
||||
Name = x.User_Name,
|
||||
Family = x.User_Family,
|
||||
Phone = x.User_Phone,
|
||||
Code = x.User_Code,
|
||||
Status = x.User_Status,
|
||||
Role = x.User_Role,
|
||||
CreatedDate = x.User_CreatedDateFa
|
||||
}).ToList();
|
||||
|
||||
return View(models);
|
||||
}
|
||||
|
||||
public new async Task<ActionResult> User(int Id = 0)
|
||||
{
|
||||
if (!HasSession("ManageUser")) { return new HttpStatusCodeResult(HttpStatusCode.Unauthorized); }
|
||||
var model = new User()
|
||||
{
|
||||
User_Id = Id,
|
||||
User_Status = 1,
|
||||
User_Image = "dUser.png"
|
||||
};
|
||||
if (Id != 0)
|
||||
{
|
||||
|
||||
|
||||
model = db.Users.AsNoTracking().Where(x => x.User_Id == Id).FirstOrDefault();
|
||||
if (model == null) { return RedirectToAction("Users"); }
|
||||
|
||||
}
|
||||
|
||||
return View(model);
|
||||
}
|
||||
|
||||
[Route("~/panel/Setting")]
|
||||
public async Task<ActionResult> Setting()
|
||||
{
|
||||
|
||||
var model = new Setting()
|
||||
{
|
||||
Setting_Id = 1,
|
||||
Setting_Social = "[]",
|
||||
Setting_Send = false,
|
||||
};
|
||||
if (!HasSession("ManageSetting")) { return RedirectToAction("Index"); }
|
||||
|
||||
model = db.Settings.AsNoTracking().FirstOrDefault();
|
||||
|
||||
return View(model);
|
||||
}
|
||||
|
||||
[Route("~/panel/SaveSettings")]
|
||||
[HttpPost]
|
||||
public async Task<JsonResult> SaveSettings()
|
||||
{
|
||||
StatusModel statusModel = new StatusModel() { Status = "Success" };
|
||||
|
||||
try
|
||||
{
|
||||
if (HasSession())
|
||||
{
|
||||
var User = Session["User"] as User;
|
||||
if (HasSession("ManageSetting")
|
||||
)
|
||||
{
|
||||
SettingModel model = JsonConvert.DeserializeObject<SettingModel>(Request.Form["Model"]);
|
||||
var Settings = await db.Settings.FirstOrDefaultAsync();
|
||||
if (Settings != null)
|
||||
{
|
||||
Settings.Setting_Name = model.Name;
|
||||
Settings.Setting_Title = model.Title;
|
||||
Settings.Setting_Discount = model.Discount;
|
||||
Settings.Setting_Description = model.Description;
|
||||
Settings.Setting_Keywords = model.Keywords;
|
||||
Settings.Setting_Footer = model.Footer;
|
||||
Settings.Setting_Header = model.Header;
|
||||
Settings.Setting_Social = JsonConvert.SerializeObject(model.Socials);
|
||||
Settings.Setting_Username = model.SmsUsername;
|
||||
Settings.Setting_Password = model.SmsPassword;
|
||||
Settings.Setting_FromNumber = model.SmsFromNumber;
|
||||
Settings.Setting_PaternLogin = model.SmsPaternLogin;
|
||||
Settings.Setting_Address = model.address;
|
||||
Settings.Setting_PostCode = model.postcode;
|
||||
Settings.Setting_Phone = model.phone;
|
||||
Settings.Setting_Website = model.website;
|
||||
db.Entry(Settings).State = EntityState.Modified;
|
||||
for (int i = 0; i < Request.Files.Count; i++)
|
||||
{
|
||||
switch (Request.Files.AllKeys[i])
|
||||
{
|
||||
case "Logo":
|
||||
Request.Files[i].SaveAs(Server.MapPath($"~/Media/logo.png"));
|
||||
break;
|
||||
case "Icon":
|
||||
Request.Files[i].SaveAs(Server.MapPath($"~/Media/favicon.ico"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else { statusModel.Status = "Auth"; }
|
||||
}
|
||||
catch { statusModel.Status = "Error"; }
|
||||
return Json(statusModel);
|
||||
}
|
||||
|
||||
|
||||
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<JsonResult> Login(LoginModel model)
|
||||
{
|
||||
StatusModel statusModel = new StatusModel() { Status = "Success" };
|
||||
try
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(model.Username) && !string.IsNullOrEmpty(model.Password))
|
||||
{
|
||||
var User = await db.Users.Where(x => x.User_Phone == model.Username && x.User_Role == "Admin").FirstOrDefaultAsync();
|
||||
if (User != null)
|
||||
{
|
||||
if (User.User_Status == 1)
|
||||
{
|
||||
if (User.User_Password == functions.HashPassword(model.Password + User.User_CreatedDate))
|
||||
{
|
||||
DateTime Now = DateTime.Now;
|
||||
string Token = functions.GenerateToken();
|
||||
User.User_LoginDate = Now;
|
||||
User.User_LoginDateFa = functions.ConvertToPersianDate(Now);
|
||||
User.User_Token = Token;
|
||||
await db.SaveChangesAsync();
|
||||
Session["User"] = User;
|
||||
SetCookie("UserId", $"{User.User_Id}");
|
||||
SetCookie("Token", Token);
|
||||
|
||||
|
||||
}
|
||||
else { statusModel.Status = "Wrong"; }
|
||||
}
|
||||
else { statusModel.Status = "Block"; }
|
||||
}
|
||||
else { statusModel.Status = "NoExist"; }
|
||||
}
|
||||
else { statusModel.Status = "Empty"; }
|
||||
}
|
||||
else { statusModel.Status = "NotValid"; }
|
||||
}
|
||||
catch { statusModel.Status = "Error"; }
|
||||
return Json(statusModel);
|
||||
}
|
||||
|
||||
[Route("~/Panel/Logout")]
|
||||
public async Task Logout()
|
||||
{
|
||||
if (Session["User"] != null)
|
||||
{
|
||||
var UserModel = Session["User"] as User;
|
||||
var Single = await db.Users.FindAsync(UserModel.User_Id);
|
||||
if (Single != null)
|
||||
{
|
||||
Single.User_Token = null;
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
Session.Clear();
|
||||
Session.Abandon();
|
||||
SetCookie("UserId", "", -1);
|
||||
SetCookie("UserToken", "", -1);
|
||||
Response.Redirect("~/Panel/Login");
|
||||
}
|
||||
[Route("~/Login")]
|
||||
[Route("Login")]
|
||||
public async Task<ActionResult> Login(string Return = "")
|
||||
{
|
||||
ViewBag.Return = Return;
|
||||
if (Session["User"] != null)
|
||||
{
|
||||
Response.Redirect("~/panel/index");
|
||||
}
|
||||
else if (UserSessionExists()) { Response.Redirect("~/panel/Index"); }
|
||||
return View();
|
||||
}
|
||||
|
||||
bool UserSessionExists()
|
||||
{
|
||||
try
|
||||
{
|
||||
string Token = GetCookie("Token");
|
||||
decimal.TryParse(GetCookie("UserId"), out decimal UserId);
|
||||
if (!string.IsNullOrEmpty(Token) && UserId != 0)
|
||||
{
|
||||
var Single = db.Users.Where(x => x.User_Id == UserId && x.User_Token == Token && x.User_Status == 1 && x.User_Role == "Admin").FirstOrDefault();
|
||||
if (Single != null)
|
||||
{
|
||||
Session["User"] = Single;
|
||||
}
|
||||
else
|
||||
{
|
||||
SetCookie("Token", "", -1);
|
||||
SetCookie("UserId", "", -1);
|
||||
}
|
||||
if (Session["User"] != null) { return true; }
|
||||
}
|
||||
SetCookie("Token", "", -1);
|
||||
SetCookie("UserId", "", -1);
|
||||
return false;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
bool HasSession(string Access = "")
|
||||
{
|
||||
if (Session["User"] == null && !UserSessionExists()) return false;
|
||||
return string.IsNullOrEmpty(Access) || functions.HasAccess((Session["User"] as User).User_Access, Access);
|
||||
}
|
||||
|
||||
[Route("~/Verify")]
|
||||
[Route("Verify")]
|
||||
public ActionResult Verify(string Phone = "", string Return = "")
|
||||
{
|
||||
ViewBag.Return = Return;
|
||||
if (Session["User"] != null)
|
||||
{
|
||||
Response.Redirect("~/Index");
|
||||
}
|
||||
if (Phone == "")
|
||||
{
|
||||
Response.Redirect("~/Login");
|
||||
}
|
||||
else
|
||||
{
|
||||
ViewBag.Phone = Phone;
|
||||
}
|
||||
return View();
|
||||
}
|
||||
//set session and cookies afte login
|
||||
[HttpGet]
|
||||
[Route("Complete")]
|
||||
[Route("~/Complete")]
|
||||
public ActionResult Complete()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Log query parameters
|
||||
var user = Request.QueryString["User"];
|
||||
var token = Request.QueryString["Token"];
|
||||
|
||||
if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(token))
|
||||
{
|
||||
Console.WriteLine("User or Token is missing in the query string.");
|
||||
return new HttpStatusCodeResult(400, "Bad Request: User or Token missing.");
|
||||
}
|
||||
|
||||
// Log the query parameters
|
||||
Console.WriteLine($"User: {user}, Token: {token}");
|
||||
|
||||
var currentuser = db.Users
|
||||
.Where(x => x.User_Id.ToString() == user && x.User_Token.ToString() == token)
|
||||
.FirstOrDefault();
|
||||
|
||||
if (currentuser != null)
|
||||
{
|
||||
// Perform necessary actions, like setting session and cookies
|
||||
Session["User"] = currentuser;
|
||||
SetCookie("UserId", $"{currentuser.User_Id}");
|
||||
SetCookie("Token", currentuser.User_Token);
|
||||
|
||||
// Log success
|
||||
Console.WriteLine("User authenticated and session updated.");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Log if user is not found
|
||||
Console.WriteLine("User not found.");
|
||||
return new HttpStatusCodeResult(404, "User not found.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Log error details
|
||||
Console.WriteLine($"Error in Complete: {ex.Message}");
|
||||
return new HttpStatusCodeResult(500, "Internal Server Error: " + ex.Message);
|
||||
}
|
||||
|
||||
// Return a success response or redirect
|
||||
return new HttpStatusCodeResult(200, "Request completed successfully.");
|
||||
}
|
||||
|
||||
string SetCookie(string Key, string Value, int ExpireDay = 365)
|
||||
{
|
||||
try
|
||||
{
|
||||
Response.Cookies.Add(new HttpCookie(Key, Value) { Expires = DateTime.Now.AddDays(ExpireDay) });
|
||||
}
|
||||
catch { }
|
||||
return Value;
|
||||
}
|
||||
|
||||
string GetCookie(string Key)
|
||||
{
|
||||
string value = string.Empty;
|
||||
try
|
||||
{
|
||||
var cookie = Request.Cookies[Key];
|
||||
if (cookie != null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(cookie.Value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
value = cookie.Value;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
323
Controllers/UserController.cs
Normal file
323
Controllers/UserController.cs
Normal file
@ -0,0 +1,323 @@
|
||||
using boilerplate.Models;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Data.Entity;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using System.Web.Hosting;
|
||||
using System.Web.Http;
|
||||
|
||||
namespace boilerplate.Controllers
|
||||
{
|
||||
public class UserController : ApiController
|
||||
{
|
||||
readonly boilerplateEntities db = new boilerplateEntities();
|
||||
SmsManagment Sms = new SmsManagment();
|
||||
readonly Functions functions = new Functions();
|
||||
|
||||
|
||||
[Route("api/User/Manage")]
|
||||
[HttpPost]
|
||||
public async Task<StatusModel> Manage()
|
||||
{
|
||||
StatusModel statusModel = new StatusModel() { Status = "Success" };
|
||||
try
|
||||
{
|
||||
if (Request.Content.IsMimeMultipartContent())
|
||||
{
|
||||
var Provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());
|
||||
NameValueCollection FormData = Provider.FormData;
|
||||
if (string.IsNullOrEmpty(FormData.Get("Model"))) { statusModel.Status = "Empty"; }
|
||||
else
|
||||
{
|
||||
var model = JsonConvert.DeserializeObject<UserModel>(FormData.Get("Model"));
|
||||
var userAccessModel = functions.CheckUserAccess(model.Auth, new string[] { "Admin" }, new string[] { "All", "ManageUser" });
|
||||
|
||||
if (userAccessModel.Id != 0)
|
||||
{
|
||||
string FileName = string.Empty;
|
||||
DateTime Now = DateTime.Now;
|
||||
List<HttpContent> Files = Provider.Files;
|
||||
#region
|
||||
if (Files.Count > 0)
|
||||
{
|
||||
HttpContent UploadedFile = Files[0];
|
||||
Stream UploadedFileReader = await UploadedFile.ReadAsStreamAsync();
|
||||
string OrginalFileName = UploadedFile.Headers.ContentDisposition.FileName.Trim('\"');
|
||||
var Limit = 3145728; // 3 megabyte
|
||||
if (UploadedFileReader.Length > Limit)
|
||||
{
|
||||
statusModel.Status = "Limit";
|
||||
statusModel.Message = $"{Limit}";
|
||||
return statusModel;
|
||||
}
|
||||
if (!MimeMapping.GetMimeMapping(OrginalFileName).StartsWith("image/"))
|
||||
{
|
||||
statusModel.Status = "Format";
|
||||
return statusModel;
|
||||
}
|
||||
PersianCalendar pc = new PersianCalendar();
|
||||
string CurrentDate = $"{pc.GetYear(Now)}_{pc.GetMonth(Now)}_{pc.GetDayOfMonth(Now)}_{pc.GetHour(Now)}_{pc.GetMinute(Now)}_{pc.GetSecond(Now)}_{pc.GetMilliseconds(Now)}_{new Random().Next(10000, 99999)}";
|
||||
FileName = CurrentDate + Path.GetExtension(OrginalFileName);
|
||||
string FullPath = HostingEnvironment.MapPath($"~/Media/User/");
|
||||
using (Stream UploadedFileWriter = File.OpenWrite(Path.Combine(FullPath, FileName)))
|
||||
{
|
||||
await UploadedFileReader.CopyToAsync(UploadedFileWriter);
|
||||
UploadedFileWriter.Close();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
if (model.Id == 0)
|
||||
{
|
||||
var Single = new User()
|
||||
{
|
||||
User_Name = model.Name,
|
||||
User_Family = model.Family,
|
||||
User_Image = string.IsNullOrEmpty(FileName) ? "dUser.png" : FileName,
|
||||
User_Phone = model.Phone,
|
||||
User_Password = functions.HashPassword(model.Password + Now),
|
||||
User_NationalCode = model.NationalCode,
|
||||
User_Status = model.Status,
|
||||
User_Role = model.Role,
|
||||
User_Access = model.Access,
|
||||
User_Token = null,
|
||||
User_Code = null,
|
||||
User_CreatedDate = Now,
|
||||
User_CreatedDateFa = functions.ConvertToPersianDate(Now),
|
||||
User_LoginDate = null,
|
||||
User_LoginDateFa = null,
|
||||
};
|
||||
db.Users.Add(Single);
|
||||
await db.SaveChangesAsync();
|
||||
statusModel.Result = $"{Single.User_Id}";
|
||||
}
|
||||
else
|
||||
{
|
||||
var Single = await db.Users.FindAsync(model.Id);
|
||||
if (Single != null)
|
||||
{
|
||||
Single.User_Name = model.Name;
|
||||
Single.User_Family = model.Family;
|
||||
if (!string.IsNullOrEmpty(FileName)) { Single.User_Image = FileName; }
|
||||
Single.User_Phone = model.Phone;
|
||||
if (!string.IsNullOrEmpty(model.Password)) { Single.User_Password = functions.HashPassword(model.Password + Single.User_CreatedDate); }
|
||||
Single.User_NationalCode = model.NationalCode;
|
||||
Single.User_Status = model.Status;
|
||||
Single.User_Role = model.Role;
|
||||
Single.User_Access = model.Access;
|
||||
await db.SaveChangesAsync();
|
||||
statusModel.Result = $"{Single.User_Id}";
|
||||
|
||||
|
||||
//sms
|
||||
if (model.Status == 1 && !string.IsNullOrEmpty(model.Password) && Single.User_Role == "User")
|
||||
{
|
||||
string[] phone = { Single.User_Phone };
|
||||
string SmsPaternLogin = functions.ReadSetting("RegisterConfirmation");
|
||||
if (!string.IsNullOrEmpty(SmsPaternLogin))
|
||||
{
|
||||
new SmsManagment().SendSms(new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("userName", $"{Single.User_Phone}"), new KeyValuePair<string, string>("password", model.Password) }, phone, SmsPaternLogin);
|
||||
}
|
||||
}
|
||||
}
|
||||
else { statusModel.Status = "NotFound"; }
|
||||
}
|
||||
}
|
||||
else { statusModel.Status = "Auth"; }
|
||||
}
|
||||
}
|
||||
else { statusModel.Status = "NotData"; }
|
||||
}
|
||||
catch (Exception ex) { statusModel.Status = "Error"; statusModel.Result = ex.Message; }
|
||||
return statusModel;
|
||||
}
|
||||
|
||||
[Route("api/User/Counters")]
|
||||
[HttpGet]
|
||||
public List<int> Counters()
|
||||
{
|
||||
var counterList = new List<int>(new int[] { 0, 0, 0, 0, 0, 0 });
|
||||
|
||||
try
|
||||
{
|
||||
// Assuming db is your database context
|
||||
var users = db.Users
|
||||
.Select(c => new { c.User_Status, c.User_Role })
|
||||
.ToList();
|
||||
|
||||
foreach (var user in users)
|
||||
{
|
||||
int userStatus = user.User_Status; // Assuming Customer_Status is nullable
|
||||
int userRole = user.User_Role == "Hr" ? 4 : 5;
|
||||
|
||||
counterList[0]++; // Total count
|
||||
counterList[userStatus + 1]++; // Status-based count
|
||||
counterList[userRole]++; // Role-based count
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Handle exceptions as needed
|
||||
}
|
||||
|
||||
return counterList;
|
||||
}
|
||||
|
||||
[Route("api/User/Login")]
|
||||
[HttpPost]
|
||||
public async Task<HttpResponseMessage> Login([FromBody] PhoneModel model)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(model.Phone))
|
||||
{
|
||||
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "Empty" });
|
||||
}
|
||||
else if (model.Phone.Length != 11)
|
||||
{
|
||||
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "Length" });
|
||||
}
|
||||
else if (model.Phone.Substring(0, 2) != "09")
|
||||
{
|
||||
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "Format" });
|
||||
}
|
||||
|
||||
DateTime nowTime = DateTime.Now;
|
||||
string code = new Random().Next(10000, 99999).ToString();
|
||||
int status;
|
||||
int id;
|
||||
|
||||
var user = db.Users.SingleOrDefault(u => u.User_Phone == model.Phone);
|
||||
|
||||
if (user != null)
|
||||
{
|
||||
// Existing user
|
||||
id = user.User_Id;
|
||||
status = user.User_Status;
|
||||
|
||||
// Generate token
|
||||
byte[] time = BitConverter.GetBytes(nowTime.ToBinary());
|
||||
byte[] key = Guid.NewGuid().ToByteArray();
|
||||
string token = Convert.ToBase64String(time.Concat(key).ToArray());
|
||||
|
||||
// Update user with new password and token
|
||||
user.User_Code = Convert.ToInt32(code);
|
||||
user.User_Token = token;
|
||||
user.User_LoginDate = nowTime;
|
||||
user.User_LoginDateFa = functions.ConvertToPersianDate(nowTime);
|
||||
|
||||
|
||||
db.SaveChanges();
|
||||
|
||||
string[] phone = { user.User_Phone };
|
||||
string SmsPaternLogin = functions.ReadSetting("SmsPaternLogin");
|
||||
if (!string.IsNullOrEmpty(SmsPaternLogin))
|
||||
{
|
||||
new SmsManagment().SendSms(new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("verification-code", $"{code}") }, phone, SmsPaternLogin);
|
||||
}
|
||||
|
||||
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "OK" });
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "NoExist" });
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Request.CreateResponse(HttpStatusCode.OK, new { Status = e.Message });
|
||||
}
|
||||
}
|
||||
|
||||
[Route("api/User/CheckCode")]
|
||||
[HttpPost]
|
||||
public async Task<HttpResponseMessage> CheckCodeAsync([FromBody] CheckCodeModel model)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(model.Phone) || string.IsNullOrEmpty(model.Code))
|
||||
{
|
||||
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "Empty" });
|
||||
}
|
||||
int code = Convert.ToInt32(model.Code);
|
||||
// Query the user based on Phone and Code
|
||||
var user = db.Users
|
||||
.FirstOrDefault(u => u.User_Phone == model.Phone && u.User_Code == code && u.User_Status != 0);
|
||||
|
||||
if (user != null)
|
||||
{
|
||||
// If the user is found, generate a new token
|
||||
DateTime now = DateTime.Now;
|
||||
byte[] time = BitConverter.GetBytes(now.ToBinary());
|
||||
byte[] key = Guid.NewGuid().ToByteArray();
|
||||
string Token = Convert.ToBase64String(time.Concat(key).ToArray());
|
||||
|
||||
// Update the user's token, clear password, and change status
|
||||
user.User_Token = Token;
|
||||
user.User_Code = null;
|
||||
user.User_Status = 1; // Assuming 1 represents an active status
|
||||
user.User_LoginDate = now;
|
||||
user.User_LoginDateFa = functions.ConvertToPersianDate(now); // Assuming DateModifiedGmt is the same but in UTC
|
||||
|
||||
db.SaveChanges();
|
||||
|
||||
return Request.CreateResponse(HttpStatusCode.OK, new
|
||||
{
|
||||
Status = "Success",
|
||||
Token = Token,
|
||||
Id = user.User_Id,
|
||||
Phone = user.User_Phone,
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "Wrong" });
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "Error", Type = "" });
|
||||
}
|
||||
}
|
||||
|
||||
[Route("api/User/Delete")]
|
||||
[HttpPost]
|
||||
public async Task<StatusModel> Delete(AuthModel model)
|
||||
{
|
||||
StatusModel statusModel = new StatusModel() { Status = "Success" };
|
||||
try
|
||||
{
|
||||
if (model.Id != 0)
|
||||
{
|
||||
var userAccessModel = functions.CheckUserAccess(model, new string[] { "Admin" }, new string[] { "All", $"ManageUser" });
|
||||
if (userAccessModel.Id != 0)
|
||||
{
|
||||
var Single = await db.Users.FindAsync(model.Id);
|
||||
if (Single != null)
|
||||
{
|
||||
db.Users.Remove(Single);
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
else { statusModel.Status = "NotFound"; }
|
||||
}
|
||||
else { statusModel.Status = "Auth"; }
|
||||
}
|
||||
else { statusModel.Status = "Empty"; }
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
statusModel.Status = "Error";
|
||||
statusModel.Message = ex.Message;
|
||||
}
|
||||
return statusModel;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user