From 27a7409c0c0e252129768ff92ae15b9b72d0e1ed Mon Sep 17 00:00:00 2001 From: phoenix Date: Sun, 27 Jul 2025 18:52:06 +0000 Subject: [PATCH] remove dotnet code (#1) Reviewed-on: https://git.kundeng.us/phoenix/textsender-api/pulls/1 Co-authored-by: phoenix Co-committed-by: phoenix --- .gitignore | 5 - Controllers/ContactManagement.cs | 67 ----- Controllers/ContactQueueCreationController.cs | 88 ------ Controllers/ContactsController.cs | 254 ------------------ Controllers/PasswordVerification.cs | 64 ----- Controllers/UsersController.cs | 228 ---------------- Models/Contact.cs | 53 ---- Models/Text.cs | 14 - Models/TextQueue.cs | 16 -- Models/Token.cs | 17 -- Models/User.cs | 46 ---- Program.cs | 63 ----- Properties/launchSettings.json | 41 --- README.md | 10 +- Repositories/BaseRepository.cs | 11 - Repositories/ContactRepository.cs | 131 --------- Repositories/UsersRepository.cs | 136 ---------- TextSender-API.csproj | 20 -- appsettings.Development.json | 20 -- appsettings.json | 21 -- textsender-api.sln | 25 -- 21 files changed, 2 insertions(+), 1328 deletions(-) delete mode 100644 Controllers/ContactManagement.cs delete mode 100644 Controllers/ContactQueueCreationController.cs delete mode 100644 Controllers/ContactsController.cs delete mode 100644 Controllers/PasswordVerification.cs delete mode 100644 Controllers/UsersController.cs delete mode 100644 Models/Contact.cs delete mode 100644 Models/Text.cs delete mode 100644 Models/TextQueue.cs delete mode 100644 Models/Token.cs delete mode 100644 Models/User.cs delete mode 100644 Program.cs delete mode 100644 Properties/launchSettings.json delete mode 100644 Repositories/BaseRepository.cs delete mode 100644 Repositories/ContactRepository.cs delete mode 100644 Repositories/UsersRepository.cs delete mode 100644 TextSender-API.csproj delete mode 100644 appsettings.Development.json delete mode 100644 appsettings.json delete mode 100644 textsender-api.sln diff --git a/.gitignore b/.gitignore index 16ac8e3..e69de29 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +0,0 @@ -.vscode -appsettings.Development.json -*.json -bin -obj diff --git a/Controllers/ContactManagement.cs b/Controllers/ContactManagement.cs deleted file mode 100644 index 36f0630..0000000 --- a/Controllers/ContactManagement.cs +++ /dev/null @@ -1,67 +0,0 @@ -using TextSender_API.Models; - -namespace TextSender_API.Controllers; - -public class ContactManagement -{ - #region Fields - private IConfiguration _config; - #endregion - - - #region Constructors - public ContactManagement(IConfiguration config) - { - this._config = config; - } - #endregion - - - #region Methods - // Queues the contact file to be processed latter - public ContactCreationQueue QueueContact(IFormFile file) - { - var queue = new ContactCreationQueue(); - queue.Processed = false; - var directory = this._config["Paths:ContactQueueDirectory"]; - - if (directory!.ElementAt(directory!.Length - 1) != '/') - { - directory.Append('/'); - } - - if (!System.IO.Directory.Exists(directory)) - { - queue.Status = "Missing directory"; - // Directory does not exist - return queue; - } - - var length = 16; - var chars = "ABCDEF0123456789"; - var random = new Random(); - var filename = new string(Enumerable.Repeat(chars, length).Select(s => - s[random.Next(s.Length)]).ToArray()); - var extension = ".txt"; - - var contactPath = $"{directory}/{filename}{extension}"; - queue.Filepath = contactPath; - - if (System.IO.File.Exists(contactPath)) - { - // Already exists - queue.Status = "File exists"; - return queue; - } - - queue.Status = "Created"; - - using (var filestream = new FileStream(contactPath, FileMode.Create)) - { - file.CopyTo(filestream); - } - - return queue; - } - #endregion -} \ No newline at end of file diff --git a/Controllers/ContactQueueCreationController.cs b/Controllers/ContactQueueCreationController.cs deleted file mode 100644 index 4f9ae4a..0000000 --- a/Controllers/ContactQueueCreationController.cs +++ /dev/null @@ -1,88 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; - -using TextSender_API.Models; -using TextSender_API.Repositories; - -namespace TextSender_API.Controllers; - -[Authorize] -[ApiController] -[Route("api/v1/contact/queue")] -public class ContactQueueCreationController : ControllerBase -{ - #region Fields - private IConfiguration _config; - private readonly ILogger _logger; - #endregion - - - #region Constructors - - public ContactQueueCreationController(ILogger logger, IConfiguration config) - { - this._logger = logger; - this._config = config; - } - #endregion - - #region Methods - [HttpPost("upload"), DisableRequestSizeLimit] - public IActionResult Upload([FromForm(Name = "file")] List contactFile, - [FromForm(Name = "user_id")] string userID) - { - // Save the file on the filesystem to be processed by a separate - // system - var response = new CreateQueueResponse(); - var connString = this._config.GetConnectionString("MongoDBURI"); - var userRepo = new UsersRepository(connString!); - var queueRepo = new ContactCreationQueueRepository(connString!); - - try - { - var ctMgr = new ContactManagement(this._config); - var user = userRepo.Exists(userID); - - if (!user.Item1) - { - return NotFound(response); - } - - foreach (var file in contactFile) - { - var queue = ctMgr.QueueContact(file); - queue.UserId = user.Item2.Id; - queue.DateCreated = DateTime.Now; - queueRepo.Create(queue); - - response.Data.Add(queue); - } - } - catch (Exception ex) - { - this._logger.LogError($"An error occurred: {ex.Message}"); - } - - return Ok(response); - } - #endregion - - - #region Responses - public class CreateQueueResponse - { - #region Properties - [JsonProperty("data")] - public List Data { get; set; } - #endregion - - #region Constructors - public CreateQueueResponse() - { - this.Data = new List(); - } - #endregion - } - #endregion -} \ No newline at end of file diff --git a/Controllers/ContactsController.cs b/Controllers/ContactsController.cs deleted file mode 100644 index 64f635b..0000000 --- a/Controllers/ContactsController.cs +++ /dev/null @@ -1,254 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; - -using TextSender_API.Models; -using TextSender_API.Repositories; - -namespace TextSender_API.Controllers; - -[Authorize] -[ApiController] -[Route("api/v1/contact")] -public class ContactsController : ControllerBase -{ - #region Fields - private IConfiguration _config; - private readonly ILogger _logger; - #endregion - - - #region Constructors - - public ContactsController(ILogger logger, IConfiguration config) - { - this._logger = logger; - this._config = config; - } - #endregion - - #region Methods - [HttpGet, DisableRequestSizeLimit] - public IActionResult RetrieveContacts([FromQuery(Name = "user_id")] string? userID) - { - var response = new CreateContactResponse(); - var connString = this._config.GetConnectionString("MongoDBURI"); - var userRepo = new UsersRepository(connString!); - var contactsRepo = new ContactsRepository(connString!); - - try - { - var contacts = contactsRepo.RetrieveAll(); - var users = userRepo.RetrieveAllUsers(); - - if (users.Count() == 0) - { - return BadRequest(response); - } - - var user = users.FirstOrDefault(us => us.Id!.Equals(userID)); - - if (user == null) - { - return BadRequest(response); - } - - contacts = contacts.Where(c => c.UserID!.Equals(userID)).ToList(); - - if (contacts == null || contacts.Count() == 0) - { - return BadRequest(response); - } - - response.Data = contacts; - } - catch (Exception ex) - { - this._logger.LogError($"An error occurred: {ex.Message}"); - } - - return Ok(response); - } - - - [HttpPost("new"), DisableRequestSizeLimit] - public IActionResult CreateContact([FromBody] Contact contact) - { - var response = new CreateContactResponse(); - var connString = this._config.GetConnectionString("MongoDBURI"); - var userRepo = new UsersRepository(connString!); - var contactsRepo = new ContactsRepository(connString!); - - try - { - var contacts = contactsRepo.RetrieveAll(); - var users = userRepo.RetrieveAllUsers(); - - if (users.Count() == 0) - { - return BadRequest(response); - } - - if (contacts.Count() > 0) - { - if (contacts.Exists(c => c.PhoneNumber!.Equals(contact.PhoneNumber)) || - string.IsNullOrEmpty(contact.UserID)) - { - // The Contact already exists - return BadRequest(response); - } - } - - if (!userRepo.Exists(contact.UserID!).Item1) - { - return BadRequest(response); - } - - contact.DateCreated = DateTime.Now; - contactsRepo.Create(contact); - response.Data.Add(contact); - } - catch (Exception ex) - { - this._logger.LogError($"An error occurred: {ex.Message}"); - } - - return Ok(response); - } - - [HttpPatch("update"), DisableRequestSizeLimit] - public IActionResult UpdateContact([FromBody] Contact contact) - { - var response = new CreateContactResponse(); - var connString = this._config.GetConnectionString("MongoDBURI"); - var userRepo = new UsersRepository(connString!); - var contactsRepo = new ContactsRepository(connString!); - - try - { - var contacts = contactsRepo.RetrieveAll(); - var users = userRepo.RetrieveAllUsers(); - - if (users.Count() == 0 || contacts.Count() == 0) - { - return BadRequest(response); - } - - var c = contacts.FirstOrDefault(c => c.Id!.Equals(contact.Id)); - - if (c == null || - string.IsNullOrEmpty(contact.UserID)) - { - // The Contact does not exists or no user id provided - return BadRequest(response); - } - - if (!userRepo.Exists(contact.UserID!).Item1) - { - return BadRequest(response); - } - - if (!c.UserID!.Equals(contact.UserID)) - { - // The provided user id does is not the same that created the contact - return BadRequest(response); - } - - if (!string.IsNullOrEmpty(contact.Firstname)) - { - c.Firstname = contact.Firstname; - } - - if (string.IsNullOrEmpty(contact.Lastname)) - { - c.Lastname = contact.Lastname; - } - - if (string.IsNullOrEmpty(contact.PhoneNumber)) - { - if (!contacts.Exists(cc => cc.PhoneNumber!.Equals(contact.PhoneNumber))) - { - c.PhoneNumber = contact.PhoneNumber; - } - } - - contactsRepo.Update(c); - response.Data.Add(c); - } - catch (Exception ex) - { - this._logger.LogError($"An error occurred: {ex.Message}"); - } - - return Ok(response); - } - - - [HttpDelete("delete"), DisableRequestSizeLimit] - public IActionResult DeleteContact([FromBody] Contact contact) - { - var response = new CreateContactResponse(); - var connString = this._config.GetConnectionString("MongoDBURI"); - var userRepo = new UsersRepository(connString!); - var contactsRepo = new ContactsRepository(connString!); - - try - { - var contacts = contactsRepo.RetrieveAll(); - var users = userRepo.RetrieveAllUsers(); - - if (users.Count() == 0 || contacts.Count() == 0) - { - return BadRequest(response); - } - - var c = contacts.FirstOrDefault(c => c.Id!.Equals(contact.Id)); - - if (c == null || - string.IsNullOrEmpty(contact.UserID)) - { - // The Contact does not exists or no user id provided - return BadRequest(response); - } - - if (!userRepo.Exists(contact.UserID!).Item1) - { - return BadRequest(response); - } - - if (!c.UserID!.Equals(contact.UserID)) - { - // The provided user id does is not the same that created the contact - return BadRequest(response); - } - - contactsRepo.Delete(c); - response.Data.Add(c); - } - catch (Exception ex) - { - this._logger.LogError($"An error occurred: {ex.Message}"); - } - - return Ok(response); - } - #endregion - - - #region Responses - public class CreateContactResponse - { - #region Properties - [JsonProperty("data")] - public List Data { get; set; } - #endregion - - #region Constructors - public CreateContactResponse() - { - this.Data = new List(); - } - #endregion - } - #endregion -} diff --git a/Controllers/PasswordVerification.cs b/Controllers/PasswordVerification.cs deleted file mode 100644 index 0eac000..0000000 --- a/Controllers/PasswordVerification.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Security.Cryptography; -using System.Text; - -using TextSender_API.Models; -using TextSender_API.Repositories; - -namespace TextSender_API.Controllers; - -public class PasswordVerification -{ - #region Fiends - private UsersRepository _userRepo; - private SaltRepository _saltRepo; - private int _keySize = 64; - private int _iterations = 350000; - #endregion - - #region Constructors - public PasswordVerification(UsersRepository userRepo, SaltRepository saltRepo) - { - this._userRepo = userRepo; - this._saltRepo = saltRepo; - } - #endregion - - #region Methods - public bool VerifyPassword(User user, string password) - { - var salt = this._saltRepo.Retrieve(user.Id!); - var hashedPassword = this.HashPassword(user, salt, password); - - return hashedPassword.Equals(user.Password); - } - public Salt CreateSalt(User user) - { - var salt = new Salt(); - salt.Key = RandomNumberGenerator.GetBytes(this._keySize); - - return salt; - } - - public string HashPassword(User user, Salt salt, string password = "") - { - var hashAlgorithm = HashAlgorithmName.SHA512; - var dbHashedPassword = user.Password; - - if (!string.IsNullOrEmpty(password)) - { - user.Password = password; - } - - var hash = Rfc2898DeriveBytes.Pbkdf2( - Encoding.UTF8.GetBytes(user.Password!), - salt.Key!, - this._iterations, - hashAlgorithm, - this._keySize); - - user.Password = dbHashedPassword; - - return Convert.ToHexString(hash); - } - #endregion -} \ No newline at end of file diff --git a/Controllers/UsersController.cs b/Controllers/UsersController.cs deleted file mode 100644 index c90b7aa..0000000 --- a/Controllers/UsersController.cs +++ /dev/null @@ -1,228 +0,0 @@ -using System.IdentityModel.Tokens; -using System.IdentityModel.Tokens.Jwt; -using System.Linq; -using System.Security.Claims; -using System.Security.Cryptography; -using System.Text; -using System.Threading.Tasks; - -using Microsoft.AspNetCore.Mvc; -using Microsoft.IdentityModel.Tokens; -using Newtonsoft.Json; - -using TextSender_API.Models; -using TextSender_API.Repositories; - -namespace TextSender_API.Controllers; - -[ApiController] -[Route("api/v1/user")] -public class UsersController : ControllerBase -{ - #region Fields - private readonly ILogger _logger; - private IConfiguration _config; - #endregion - - - #region Constructors - - public UsersController(ILogger logger, IConfiguration config) - { - this._logger = logger; - this._config = config; - } - #endregion - - #region Methods - private string AllScopes() - { - var allScopes = new List() - { - "create:contact" - }; - - var scopes = string.Empty; - - for (var i = 0; i < allScopes.Count; i++) - { - if (i == allScopes.Count - 1) - { - scopes += allScopes[i]; - } - else - { - scopes += allScopes[i] + " "; - } - } - - return scopes; - } - - private List Payload() - { - var expLimit = 30; - var currentDate = DateTime.Now; - var expiredDate = currentDate.AddMinutes(expLimit); - var issued = Math.Floor((currentDate - DateTime.UnixEpoch).TotalSeconds); - var expires = Math.Floor((expiredDate - DateTime.UnixEpoch).TotalSeconds); - var issuer = this._config["JWT:Issuer"]; - var audience = this._config["JWT:Audience"]; - var subject = this._config["JWT:Subject"]; - - var claim = new List() - { - new System.Security.Claims.Claim("scope", AllScopes(), "string"), - new System.Security.Claims.Claim(JwtRegisteredClaimNames.Exp, expiredDate.ToString(), "string"), - new System.Security.Claims.Claim(JwtRegisteredClaimNames.Aud, audience!), - new System.Security.Claims.Claim(JwtRegisteredClaimNames.Iss, issuer!), - new Claim(JwtRegisteredClaimNames.Sub, subject!) - }; - - return claim; - } - - [HttpPost("login")] - public IActionResult Login([FromBody] User userRequest) - { - var response = new LoginResponse(); - - try - { - var connString = this._config.GetConnectionString("MongoDBURI"); - var userRepo = new UsersRepository(connString!); - var saltRepo = new SaltRepository(connString!); - var pwdVerify = new PasswordVerification(userRepo, saltRepo); - var result = userRepo.Exists(userRequest); - - if (result.Item1 && pwdVerify.VerifyPassword(result.Item2, userRequest.Password!)) - { - var user = result.Item2; - var token = new Token(); - token.Issued = DateTime.Now; - token.UserId = user.Id; - token.TokenType = "JWT"; - - var payload = Payload(); - payload.Add(new System.Security.Claims.Claim("user_id", user.Id!, ClaimValueTypes.String)); - - var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this._config["JWT:Secret"]!)); - var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); - - var tok = new JwtSecurityToken( - this._config["JWT:Issuer"], - this._config["JWT:Audience"], - payload, - expires: DateTime.UtcNow.AddMinutes(30), - signingCredentials: signIn); - - token.AccessToken = new JwtSecurityTokenHandler().WriteToken(tok); - - var expClaim = payload.FirstOrDefault(cl => - { - return cl.Type.Equals("exp"); - }); - - if (expClaim != null) - { - var expiredDate = DateTime.Parse(expClaim!.Value); - var exp = Math.Floor((expiredDate - DateTime.UnixEpoch).TotalSeconds); - } - - response.Data.Add(token); - Ok(response); - } - else - { - return NotFound(response); - } - } - catch (Exception ex) - { - this._logger.LogError($"An error occurred: {ex.Message}"); - } - - return Ok(response); - } - - [HttpPost("register"), DisableRequestSizeLimit] - public IActionResult Upload([FromBody] User userRequest) - { - var response = new RegisterUserResponse(); - - try - { - var connString = this._config.GetConnectionString("MongoDBURI"); - var userRepo = new UsersRepository(connString!); - var saltRepo = new SaltRepository(connString!); - var allUsers = userRepo.RetrieveAllUsers(); - var result = allUsers.Exists(ea => ea.Username!.Equals(userRequest.Username)); - - if (!result) - { - var pwdVerify = new PasswordVerification(userRepo, saltRepo); - var salt = pwdVerify.CreateSalt(userRequest); - var hashedPassword = pwdVerify.HashPassword(userRequest, salt); - - this._logger.LogInformation("Creating user"); - userRequest.Password = hashedPassword; - userRequest.DateCreated = DateTime.Now; - userRepo.CreateUser(userRequest); - - response.Data.Add(userRequest); - - salt.UserId = userRequest.Id; - saltRepo.Create(salt); - } - else - { - this._logger.LogInformation("User already exists"); - } - } - catch (Exception ex) - { - this._logger.LogError($"An error occurred: {ex.Message}"); - } - - return Ok(response); - } - #endregion - - #region Responses - public class LoginResponse - { - #region Properties - [JsonProperty("data")] - public List Data { get; set; } - #endregion - - #region Constructors - public LoginResponse() - { - this.Data = new List(); - } - #endregion - - #region Methods - #endregion - } - - public class RegisterUserResponse - { - #region Properties - [JsonProperty("data")] - public List Data { get; set; } - #endregion - - #region Constructors - public RegisterUserResponse() - { - this.Data = new List(); - } - #endregion - - #region Methods - #endregion - } - #endregion -} diff --git a/Models/Contact.cs b/Models/Contact.cs deleted file mode 100644 index 72da9a0..0000000 --- a/Models/Contact.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; - -using MongoDB.Bson; -using MongoDB.Bson.Serialization.Attributes; -using Newtonsoft.Json; - -namespace TextSender_API.Models; - -public class Contact -{ -#region Properties - [BsonId] - [BsonRepresentation(BsonType.ObjectId)] - [JsonProperty("id")] - public string? Id { get; set; } - [BsonElement("firstname")] - [JsonProperty("firstname")] - public string? Firstname { get; set; } - [BsonElement("lastname")] - [JsonProperty("lastname")] - public string? Lastname { get; set; } - [BsonElement("phonenumber")] - [JsonProperty("phonenumber")] - public string? PhoneNumber { get; set; } - [BsonElement("date_created")] - [JsonProperty("date_created")] - public DateTime DateCreated { get; set; } - // [BsonRepresentation(BsonType.ObjectId)] - [BsonElement("user_id")] - [JsonProperty("user_id")] - public string? UserID { get; set; } -#endregion -} - - -public class ContactCreationQueue -{ - #region Properties - [BsonId] - [BsonRepresentation(BsonType.ObjectId)] - public string? Id { get; set; } - [BsonElement("filepath")] - public string? Filepath { get; set; } - [BsonElement("status")] - public string? Status { get; set; } - [BsonElement("user_id")] - public string? UserId { get; set; } - [BsonElement("date_created")] - public DateTime? DateCreated { get; set; } - [BsonElement("processed")] - public bool? Processed { get; set; } - #endregion -} \ No newline at end of file diff --git a/Models/Text.cs b/Models/Text.cs deleted file mode 100644 index 8a5e8b0..0000000 --- a/Models/Text.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace TextSender_API.Models; - -public class Text -{ -#region Properties - public int TextID { get; set; } - public string? Subject { get; set; } - public string? Message { get; set; } - public int UserID { get; set; } - public DateTime DateCreated { get; set; } -#endregion -} diff --git a/Models/TextQueue.cs b/Models/TextQueue.cs deleted file mode 100644 index 9d7327b..0000000 --- a/Models/TextQueue.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace TextSender_API.Models; - -public class TextQueue -{ -#region Properties - public int TextQueueID { get; set; } - public string? Status { get; set; } - public string? ContactPhoneNumber { get; set; } - public int TextID { get; set; } - public int UserID { get; set; } - public DateTime DateCreated { get; set; } - public DateTime ExecutionDate { get; set; } -#endregion -} diff --git a/Models/Token.cs b/Models/Token.cs deleted file mode 100644 index afbe858..0000000 --- a/Models/Token.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Newtonsoft.Json; - -namespace TextSender_API.Models; - -public class Token -{ - #region Properties - [JsonProperty("access_token")] - public string? AccessToken { get; set; } - [JsonProperty("token_type")] - public string? TokenType { get; set; } - [JsonProperty("issued")] - public DateTime? Issued { get; set; } - [JsonProperty("id")] - public string? UserId { get; set; } - #endregion -} \ No newline at end of file diff --git a/Models/User.cs b/Models/User.cs deleted file mode 100644 index 9cbf051..0000000 --- a/Models/User.cs +++ /dev/null @@ -1,46 +0,0 @@ -using MongoDB.Bson; -using MongoDB.Bson.Serialization.Attributes; -using Newtonsoft.Json; - -namespace TextSender_API.Models; - -public class User -{ -#region Properties - [BsonId] - [BsonRepresentation(BsonType.ObjectId)] - [JsonProperty("id")] - public string? Id { get; set; } - [BsonElement("firstname")] - [JsonProperty("firstname")] - public string? Firstname { get; set; } - [BsonElement("lastname")] - [JsonProperty("lastname")] - public string? Lastname { get; set; } - [BsonElement("phonenumber")] - [JsonProperty("phone_number")] - public string? PhoneNumber { get; set; } - [BsonElement("username")] - [JsonProperty("username")] - public string? Username { get; set; } - [BsonElement("password")] - [JsonProperty("password")] - public string? Password { get; set; } - [BsonElement("datecreated")] - [JsonProperty("date_created")] - public DateTime? DateCreated { get; set; } -#endregion -} - -public class Salt -{ - #region Properties - [BsonId] - [BsonRepresentation(BsonType.ObjectId)] - public string? Id { get; set; } - [BsonElement("key")] - public byte[]? Key { get; set; } - [BsonElement("user_id")] - public string? UserId { get; set; } - #endregion -} diff --git a/Program.cs b/Program.cs deleted file mode 100644 index 66aca82..0000000 --- a/Program.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Text; - -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.IdentityModel.Tokens; - -using TextSender_API.Repositories; - -var builder = WebApplication.CreateBuilder(args); - -// Add services to the container. - -builder.Services.AddControllers(); -builder.Services.AddControllers().AddNewtonsoftJson(); - -// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle -builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); - -builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => -{ - options.RequireHttpsMetadata = false; - options.SaveToken = true; - options.TokenValidationParameters = new TokenValidationParameters() - { - ValidateIssuer = true, - ValidateAudience = true, - ValidAudience = builder.Configuration["JWT:Audience"], - ValidIssuer = builder.Configuration["JWT:Issuer"], - RequireExpirationTime = false, - ValidateIssuerSigningKey = false, - IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:Secret"]!)) - }; -}); - -// var connectionString = builder.Configuration.GetConnectionString("MongoDBURI"); - - -var app = builder.Build(); - -// Configure the HTTP request pipeline. -if (app.Environment.IsDevelopment()) -{ - app.UseSwagger(); - app.UseSwaggerUI(); -} - - -app.UseHttpsRedirection(); - -app.UseAuthentication(); -app.UseRouting(); -app.UseAuthorization(); -app.UseEndpoints(endpoints => -{ - endpoints.MapControllers(); -}); - -// app.MapControllers(); - -app.Run(); diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json deleted file mode 100644 index e609dd5..0000000 --- a/Properties/launchSettings.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:22514", - "sslPort": 44361 - } - }, - "profiles": { - "http": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "launchUrl": "swagger", - "applicationUrl": "http://localhost:5168", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "https": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "launchUrl": "swagger", - "applicationUrl": "https://localhost:7154;http://localhost:5168", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/README.md b/README.md index b8543de..31c815c 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,9 @@ # TextSender-API -An API used to send texts messages to multiple contacts. +A software system to process Text messaging queueing ## Getting started -Installing dependencies +TODO ```BASH -dotnet restore -``` - -Running server -```BASH -dotnet run ``` diff --git a/Repositories/BaseRepository.cs b/Repositories/BaseRepository.cs deleted file mode 100644 index e437670..0000000 --- a/Repositories/BaseRepository.cs +++ /dev/null @@ -1,11 +0,0 @@ - -namespace TextSender_API.Repositories; - -public class BaseRepository -{ - #region Fields - protected string? _connectionString; - protected string _databaseName = "textSender"; - protected string? _tableName; - #endregion -} \ No newline at end of file diff --git a/Repositories/ContactRepository.cs b/Repositories/ContactRepository.cs deleted file mode 100644 index b4d9ceb..0000000 --- a/Repositories/ContactRepository.cs +++ /dev/null @@ -1,131 +0,0 @@ -using MongoDB.Driver; - -using TextSender_API.Models; - -namespace TextSender_API.Repositories; - - -public class ContactCreationQueueRepository : BaseRepository -{ - #region Fields - private readonly IMongoCollection _bookCollection; - #endregion - - - #region Constructors - public ContactCreationQueueRepository(string connectionString) - { - this._connectionString = connectionString; - this._tableName = "contactCreationQueue"; - var client = this.InitializeClient(); - this._bookCollection = client.GetDatabase(this._databaseName).GetCollection(this._tableName); - } - #endregion - - #region Metods - public Tuple Exists(string id) - { - var allQueue = this.RetrieveAll(); - var result = allQueue.FirstOrDefault(q => q.Id!.Equals(id)); - - if (result != null) - { - return new Tuple(true, result!); - } - else - { - return new Tuple(false, new ContactCreationQueue()); - } - } - - public void Create(ContactCreationQueue queue) - { - this._bookCollection.InsertOne(queue); - } - - public List RetrieveAll() - { - return this._bookCollection.Find(_ => true).ToList(); - } - - public void Update(ContactCreationQueue queue) - { - var filter = Builders.Filter.Eq(q => q.Id, queue.Id); - this._bookCollection.ReplaceOne(filter, queue); - } - - public void Delete(ContactCreationQueue queue) - { - var filter = Builders.Filter.Eq(q => q.Id, queue.Id); - this._bookCollection.DeleteOne(filter); - } - - private MongoClient InitializeClient() - { - return new MongoClient(this._connectionString); - } - #endregion -} - - -public class ContactsRepository : BaseRepository -{ - #region Fields - private readonly IMongoCollection _bookCollection; - #endregion - - - #region Constructors - public ContactsRepository(string connectionString) - { - this._connectionString = connectionString; - this._tableName = "contacts"; - var client = this.InitializeClient(); - this._bookCollection = client.GetDatabase(this._databaseName).GetCollection(this._tableName); - } - #endregion - - #region Metods - public Tuple Exists(string id) - { - var allContacts= this.RetrieveAll(); - var result = allContacts.FirstOrDefault(c => c.Id!.Equals(id)); - - if (result != null) - { - return new Tuple(true, result!); - } - else - { - return new Tuple(false, new Contact()); - } - } - - public void Create(Contact contact) - { - this._bookCollection.InsertOne(contact); - } - - public List RetrieveAll() - { - return this._bookCollection.Find(_ => true).ToList(); - } - - public void Update(Contact contact) - { - var filter = Builders.Filter.Eq(c => c.Id, contact.Id); - this._bookCollection.ReplaceOne(filter, contact); - } - - public void Delete(Contact contact) - { - var filter = Builders.Filter.Eq(c => c.Id, contact.Id); - this._bookCollection.DeleteOne(filter); - } - - private MongoClient InitializeClient() - { - return new MongoClient(this._connectionString); - } - #endregion -} \ No newline at end of file diff --git a/Repositories/UsersRepository.cs b/Repositories/UsersRepository.cs deleted file mode 100644 index c9a86a1..0000000 --- a/Repositories/UsersRepository.cs +++ /dev/null @@ -1,136 +0,0 @@ -using MongoDB.Driver; - -using TextSender_API.Models; - -namespace TextSender_API.Repositories; - - -public class UsersRepository : BaseRepository -{ - #region Fields - private readonly IMongoCollection _bookCollection; - #endregion - - - #region Constructors - public UsersRepository(string connectionString) - { - this._connectionString = connectionString; - this._tableName = "users"; - var client = this.InitializeClient(); - this._bookCollection = client.GetDatabase(this._databaseName).GetCollection(this._tableName); - } - #endregion - - #region Metods - public Tuple Exists(User user) - { - var allUsers = this.RetrieveAllUsers(); - var result = allUsers.FirstOrDefault(ea => ea.Username!.Equals(user.Username)); - - if (result != null) - { - return new Tuple(true, result!); - } - else - { - return new Tuple(false, new User()); - } - } - - public Tuple Exists(string userId) - { - var allUsers = this.RetrieveAllUsers(); - var result = allUsers.FirstOrDefault(ea => ea.Id!.Equals(userId)); - - if (result != null) - { - return new Tuple(true, result!); - } - else - { - return new Tuple(false, new User()); - } - } - - public void CreateUser(User user) - { - this._bookCollection.InsertOne(user); - } - - public List RetrieveAllUsers() - { - return this._bookCollection.Find(_ => true).ToList(); - } - - public void Update(User user) - { - var filter = Builders.Filter.Eq(u => u.Id, user.Id); - this._bookCollection.ReplaceOne(filter, user); - } - - public void Delete(User user) - { - var filter = Builders.Filter.Eq(u => u.Id, user.Id); - this._bookCollection.DeleteOne(filter); - } - - private MongoClient InitializeClient() - { - return new MongoClient(this._connectionString); - } - #endregion -} - - -public class SaltRepository : BaseRepository -{ - #region Fields - private readonly IMongoCollection _bookCollection; - #endregion - - - #region Constructors - public SaltRepository(string connectionString) - { - this._connectionString = connectionString; - this._tableName = "salt"; - var client = this.InitializeClient(); - this._bookCollection = client.GetDatabase(this._databaseName).GetCollection(this._tableName); - } - #endregion - - #region Metods - public void Create(Salt salt) - { - this._bookCollection.InsertOne(salt); - } - - public List RetrieveAll() - { - return this._bookCollection.Find(_ => true).ToList(); - } - - public Salt Retrieve(string userId) - { - return this._bookCollection.Find(s => s.UserId!.Equals(userId)).FirstOrDefault(); - } - - public void Update(Salt salt) - { - var filter = Builders.Filter.Eq(u => u.Id, salt.Id); - this._bookCollection.ReplaceOne(filter, salt); - } - - public void Delete(Salt salt) - { - var filter = Builders.Filter.Eq(u => u.Id, salt.Id); - this._bookCollection.DeleteOne(filter); - } - - private MongoClient InitializeClient() - { - return new MongoClient(this._connectionString); - } - #endregion -} \ No newline at end of file diff --git a/TextSender-API.csproj b/TextSender-API.csproj deleted file mode 100644 index d4d3f0b..0000000 --- a/TextSender-API.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - net7.0 - enable - enable - TextSender_API - - - - - - - - - - - - - diff --git a/appsettings.Development.json b/appsettings.Development.json deleted file mode 100644 index e0a901f..0000000 --- a/appsettings.Development.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "JWT": { - "Audience": "", - "Issuer": "", - "Secret": "", - "Subject": "" - }, - "Paths": { - "ContactQueueDirectory": "/home/user/path/" - }, - "ConnectionStrings": { - "MongoDBURI": "mongodb+srv://:@cluster0.abc.mongodb.net/?retryWrites=true&w=majority" - } -} diff --git a/appsettings.json b/appsettings.json deleted file mode 100644 index 8a3238e..0000000 --- a/appsettings.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*", - "JWT": { - "Audience": "", - "Issuer": "", - "Secret": "", - "Subject": "" - }, - "Paths": { - "ContactQueueDirectory": "/home/user/path/" - }, - "ConnectionStrings": { - "MongoDBURI": "mongodb+srv://:@cluster0.abc.mongodb.net/?retryWrites=true&w=majority" - } -} diff --git a/textsender-api.sln b/textsender-api.sln deleted file mode 100644 index b57d8ea..0000000 --- a/textsender-api.sln +++ /dev/null @@ -1,25 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.5.002.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextSender-API", "TextSender-API.csproj", "{AD184BBA-C715-4112-95A9-530F05323BEE}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {AD184BBA-C715-4112-95A9-530F05323BEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AD184BBA-C715-4112-95A9-530F05323BEE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AD184BBA-C715-4112-95A9-530F05323BEE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AD184BBA-C715-4112-95A9-530F05323BEE}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {70126048-DECC-43EE-9956-2CEF937B7AA1} - EndGlobalSection -EndGlobal