├── README.md ├── NewUpstorm.Domain ├── Enums │ └── UserRole.cs ├── Entities │ ├── WeatherInfo.cs │ ├── WindInfo.cs │ ├── SunTime.cs │ ├── User.cs │ ├── RootObject.cs │ └── MainInfo.cs └── NewUpstorm.Domain.csproj ├── NewUpstorm.Web ├── appsettings.Development.json ├── Controllers │ ├── BaseController.cs │ ├── EmailsController.cs │ ├── ForecastsController.cs │ ├── AccountsController.cs │ └── UsersController.cs ├── Helpers │ └── RouteConfiguration.cs ├── Properties │ └── launchSettings.json ├── NewUpstorm.Web.csproj ├── Middlewares │ └── ExceptionHandlerMiddleware.cs ├── appsettings.json ├── Program.cs └── Extensions │ └── ServiceExtentions.cs ├── NewUpstorm.Service ├── Interfaces │ ├── IEmailService.cs │ ├── IAuthService.cs │ ├── IForecastService.cs │ └── IUserService.cs ├── DTOs │ ├── UserCreationDto.cs │ ├── UserForUpdateDto.cs │ ├── UserForResultDto.cs │ └── UserForPasswordDto.cs ├── Exceptions │ └── CustomException.cs ├── Configurations │ └── AppAPISetting.cs ├── Mappers │ └── MappingProfile.cs ├── NewUpstorm.Service.csproj └── Services │ ├── AuthService.cs │ ├── ForecastService.cs │ ├── EmailService.cs │ └── UserService.cs ├── NewUpstorm.Data ├── IRepositories │ ├── IForecastRepository.cs │ └── IUserRepository.cs ├── DbContexts │ └── AppDbContext.cs ├── NewUpstorm.Data.csproj ├── Repositories │ ├── ForecastRepository.cs │ └── UserRepository.cs └── Migrations │ ├── 20230516123134_FirstMigration.cs │ ├── AppDbContextModelSnapshot.cs │ └── 20230516123134_FirstMigration.Designer.cs ├── NewUpstorm.sln └── .gitignore /README.md: -------------------------------------------------------------------------------- 1 | # New-Upstorm 2 | I found it with weather forecast open API and and connecting with SQL Server by Entity Framework Core for users. 3 | 4 | -------------------------------------------------------------------------------- /NewUpstorm.Domain/Enums/UserRole.cs: -------------------------------------------------------------------------------- 1 | namespace NewUpstorm.Domain.Enums 2 | { 3 | public enum UserRole 4 | { 5 | Admin = 10, 6 | Consumer = 20 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /NewUpstorm.Web/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /NewUpstorm.Service/Interfaces/IEmailService.cs: -------------------------------------------------------------------------------- 1 | namespace NewUpstorm.Service.Interfaces 2 | { 3 | public interface IEmailService 4 | { 5 | ValueTask SendEmailAsync(string to); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /NewUpstorm.Service/Interfaces/IAuthService.cs: -------------------------------------------------------------------------------- 1 | namespace NewUpstorm.Service.Interfaces 2 | { 3 | public interface IAuthService 4 | { 5 | ValueTask GenerateTokenASync(string email, string password); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /NewUpstorm.Domain/Entities/WeatherInfo.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace NewUpstorm.Domain; 4 | 5 | public class WeatherInfo 6 | { 7 | public long Id { get; set; } 8 | 9 | [JsonProperty("description")] 10 | public string Description { get; set; } 11 | } 12 | -------------------------------------------------------------------------------- /NewUpstorm.Domain/Entities/WindInfo.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace NewUpstorm.Domain.Entities 4 | { 5 | public class WindInfo 6 | { 7 | public long Id { get; set; } 8 | 9 | [JsonProperty("speed")] 10 | public float Speed { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /NewUpstorm.Web/Controllers/BaseController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace NewUpstorm.Web.Controllers 5 | { 6 | [Route("api/[controller]")] 7 | [ApiController] 8 | public class BaseController : ControllerBase 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /NewUpstorm.Service/DTOs/UserCreationDto.cs: -------------------------------------------------------------------------------- 1 | namespace NewUpstorm.Service.DTOs 2 | { 3 | public class UserCreationDto 4 | { 5 | public string FirstName { get; set; } 6 | public string LastName { get; set; } 7 | public string Email { get; set; } 8 | public string Password { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /NewUpstorm.Service/Exceptions/CustomException.cs: -------------------------------------------------------------------------------- 1 | namespace NewUpstorm.Service.Exceptions 2 | { 3 | public class CustomException : Exception 4 | { 5 | public int Code { get; set; } 6 | public CustomException(int code, string message) : base(message) 7 | { 8 | Code = code; 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /NewUpstorm.Service/DTOs/UserForUpdateDto.cs: -------------------------------------------------------------------------------- 1 | namespace NewUpstorm.Service.DTOs 2 | { 3 | public class UserForUpdateDto 4 | { 5 | public long Id { get; set; } 6 | public string FirstName { get; set; } 7 | public string LastName { get; set; } 8 | public string Email { get; set; } 9 | public string Password { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /NewUpstorm.Domain/Entities/SunTime.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace NewUpstorm.Domain.Entities 4 | { 5 | public class SunTime 6 | { 7 | public long Id { get; set; } 8 | 9 | [JsonProperty("sunrise")] 10 | public int Sunrise { get; set; } 11 | 12 | [JsonProperty("sunset")] 13 | public int Sunset { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /NewUpstorm.Domain/NewUpstorm.Domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | disable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /NewUpstorm.Service/Interfaces/IForecastService.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using NewUpstorm.Domain.Entities; 3 | 4 | namespace NewUpstorm.Service.Interfaces 5 | { 6 | public interface IForecastService 7 | { 8 | ValueTask GetCurrentForecastAsync(string city); 9 | Task> GetWeeklyForecstsAsync(string city, string countryCode); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /NewUpstorm.Data/IRepositories/IForecastRepository.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using NewUpstorm.Domain.Entities; 3 | 4 | namespace NewUpstorm.Data.IRepositories 5 | { 6 | public interface IForecastRepository 7 | { 8 | ValueTask SelectCurrentForecastAsync(string city); 9 | ValueTask SelectWeeklyForecastAsync(string city, string county_code); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /NewUpstorm.Web/Helpers/RouteConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System.Text.RegularExpressions; 2 | 3 | namespace NewUpstorm.Web.Helpers 4 | { 5 | public class RouteConfiguration : IOutboundParameterTransformer 6 | { 7 | public string TransformOutbound(object value) 8 | { 9 | // Slugify value 10 | return value == null ? null : Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower(); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /NewUpstorm.Service/Configurations/AppAPISetting.cs: -------------------------------------------------------------------------------- 1 | namespace NewUpstorm.Service.Configurations 2 | { 3 | public class AppAPISetting 4 | { 5 | public const string PATH = 6 | $"https://api.openweathermap.org/data/2.5/weather?q=Tashkent&units=metric&appid=[enter your api]"; 7 | 8 | public const string WEEKLY_PATH = 9 | $"https://api.openweathermap.org/data/2.5/forecast?q=Tashkent,uz&appid=[enter your api]"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /NewUpstorm.Data/DbContexts/AppDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using NewUpstorm.Domain; 3 | using NewUpstorm.Domain.Entities; 4 | 5 | namespace NewUpstorm.Data.DbContexts 6 | { 7 | public class AppDbContext : DbContext 8 | { 9 | public AppDbContext(DbContextOptions options) 10 | : base(options) 11 | { 12 | 13 | } 14 | 15 | public virtual DbSet Users { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /NewUpstorm.Service/DTOs/UserForResultDto.cs: -------------------------------------------------------------------------------- 1 | using NewUpstorm.Domain.Enums; 2 | 3 | namespace NewUpstorm.Service.DTOs 4 | { 5 | public class UserForResultDto 6 | { 7 | public long Id { get; set; } 8 | public string FirstName { get; set; } 9 | public string LastName { get; set; } 10 | public string Email { get; set; } 11 | public string Password { get; set; } 12 | public UserRole UserRole { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /NewUpstorm.Service/Mappers/MappingProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using NewUpstorm.Domain.Entities; 3 | using NewUpstorm.Service.DTOs; 4 | 5 | namespace NewUpstorm.Service.Mappers 6 | { 7 | public class MappingProfile : Profile 8 | { 9 | public MappingProfile() 10 | { 11 | CreateMap().ReverseMap(); 12 | CreateMap().ReverseMap(); 13 | CreateMap().ReverseMap(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /NewUpstorm.Data/IRepositories/IUserRepository.cs: -------------------------------------------------------------------------------- 1 | using NewUpstorm.Domain.Entities; 2 | using System.Linq.Expressions; 3 | 4 | namespace NewUpstorm.Data.IRepositories 5 | { 6 | public interface IUserRepository 7 | { 8 | ValueTask InsertAsync(User user); 9 | ValueTask UpdateAsync(User user); 10 | ValueTask DeleteAsync(User user); 11 | ValueTask SelectAsync(Expression> expression); 12 | IQueryable SelectAll(Expression> expression = null); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /NewUpstorm.Domain/Entities/User.cs: -------------------------------------------------------------------------------- 1 | using NewUpstorm.Domain.Enums; 2 | using System; 3 | 4 | namespace NewUpstorm.Domain.Entities 5 | { 6 | public class User 7 | { 8 | public long Id { get; set; } 9 | public string FirstName { get; set; } 10 | public string LastName { get; set; } 11 | public string Email { get; set; } 12 | public string Password { get; set; } 13 | public UserRole UserRole { get; set; } 14 | public DateTime CreatedAt { get; set; } 15 | public DateTime? UpdatedAt { get; set;} 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /NewUpstorm.Domain/Entities/RootObject.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace NewUpstorm.Domain.Entities 4 | { 5 | public class RootObject 6 | { 7 | public long Id { get; set; } 8 | 9 | [JsonProperty("main")] 10 | public MainInfo MainInfo { get; set; } 11 | 12 | [JsonProperty("weather")] 13 | public WeatherInfo[] WeatherInfo { get; set; } 14 | 15 | [JsonProperty("sys")] 16 | public SunTime SunTime { get; set; } 17 | 18 | [JsonProperty("wind")] 19 | public WindInfo WindInfo { get; set; } 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /NewUpstorm.Domain/Entities/MainInfo.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace NewUpstorm.Domain.Entities; 4 | 5 | public class MainInfo 6 | { 7 | public long Id { get; set; } 8 | [JsonProperty("temp")] 9 | public float NowTemperature { get; set; } 10 | 11 | [JsonProperty("temp_min")] 12 | public float NightTemperature { get; set; } 13 | 14 | [JsonProperty("temp_max")] 15 | public float DayTemperature { get; set; } 16 | 17 | [JsonProperty("pressure")] 18 | public float Pressure { get; set; } 19 | 20 | [JsonProperty("humidity")] 21 | public float Humidity { get; set; } 22 | } 23 | -------------------------------------------------------------------------------- /NewUpstorm.Service/DTOs/UserForPasswordDto.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace NewUpstorm.Service.DTOs 4 | { 5 | public class UserForPasswordDto 6 | { 7 | [Required(ErrorMessage = "Value must not be null or empty")] 8 | public string Email { get; set; } 9 | 10 | [Required(ErrorMessage ="Old passowrd must not be null or empty!")] 11 | public string OldPassword { get; set; } 12 | 13 | [Required(ErrorMessage ="New passowrd must not be null or empty!")] 14 | public string NewPasswword { get; set; } 15 | 16 | [Compare("NewPassowrd")] 17 | public string ConfirmPassword { get; set; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /NewUpstorm.Web/Controllers/EmailsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using NewUpstorm.Service.Interfaces; 3 | 4 | namespace NewUpstorm.Web.Controllers 5 | { 6 | public class EmailsController : BaseController 7 | { 8 | private readonly IEmailService emailService; 9 | public EmailsController(IEmailService emailService) 10 | { 11 | this.emailService = emailService; 12 | } 13 | 14 | 15 | [HttpPost] 16 | public async Task SendVerifcationAsync(string email) 17 | => Ok(new 18 | { 19 | Code = 200, 20 | Message = "Success", 21 | Data = await this.emailService.SendEmailAsync(email) 22 | }); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /NewUpstorm.Service/Interfaces/IUserService.cs: -------------------------------------------------------------------------------- 1 | using NewUpstorm.Service.DTOs; 2 | 3 | namespace NewUpstorm.Service.Interfaces 4 | { 5 | public interface IUserService 6 | { 7 | ValueTask AddAsync(UserCreationDto userDto); 8 | ValueTask RemoveAsync(long id); 9 | ValueTask ModifyAsync(UserForUpdateDto userDto); 10 | ValueTask RetriewByIdAsync(long id); 11 | ValueTask> RetriewAllAsync(string search = null); 12 | ValueTask ChangePaswordAsync(UserForPasswordDto userDto); 13 | ValueTask CheckUserAsync(string email, string password = null); 14 | ValueTask UserVerify(string code); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /NewUpstorm.Service/NewUpstorm.Service.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | disable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /NewUpstorm.Web/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:25132", 8 | "sslPort": 44335 9 | } 10 | }, 11 | "profiles": { 12 | "NewUpstorm.Web": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7224;http://localhost:5046", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /NewUpstorm.Data/NewUpstorm.Data.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | disable 7 | 8 | 9 | 10 | 11 | 12 | all 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | 15 | 16 | 17 | all 18 | runtime; build; native; contentfiles; analyzers; buildtransitive 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /NewUpstorm.Web/NewUpstorm.Web.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | disable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /NewUpstorm.Web/Controllers/ForecastsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using NewUpstorm.Service.Interfaces; 3 | 4 | namespace NewUpstorm.Web.Controllers 5 | { 6 | public class ForecastsController : BaseController 7 | { 8 | private readonly IForecastService forecastService; 9 | public ForecastsController(IForecastService forecastService) 10 | { 11 | this.forecastService = forecastService; 12 | } 13 | 14 | [HttpGet("current")] 15 | public async Task GetCurrentAsync(string city) 16 | => Ok(new 17 | { 18 | Code = 200, 19 | Message = "Success", 20 | Data = await this.forecastService.GetCurrentForecastAsync(city) 21 | }); 22 | 23 | [HttpGet("weekly")] 24 | public async Task GetWeeklyAsync([FromQuery] string city, string countryCode) 25 | => 26 | Ok(new 27 | { 28 | Code = 200, 29 | Message = "Success", 30 | Data = await this.forecastService.GetWeeklyForecstsAsync(city, countryCode) 31 | }); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /NewUpstorm.Web/Controllers/AccountsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using NewUpstorm.Service.DTOs; 3 | using NewUpstorm.Service.Interfaces; 4 | 5 | namespace NewUpstorm.Web.Controllers 6 | { 7 | public class AccountsController : BaseController 8 | { 9 | private readonly IAuthService authService; 10 | private readonly IUserService userService; 11 | public AccountsController(IAuthService authService, IUserService userService) 12 | { 13 | this.authService = authService; 14 | this.userService = userService; 15 | } 16 | 17 | [HttpPost] 18 | [Route("sign-up")] 19 | public async Task PostUserAsync(UserCreationDto dto) 20 | => Ok(new 21 | { 22 | Code = 200, 23 | Message = "Success", 24 | Data = await this.userService.AddAsync(dto) 25 | }); 26 | 27 | [HttpPost("generate-token")] 28 | public async Task GenerateTokenAsync(string username, string passoword = null) 29 | => Ok(new 30 | { 31 | Code = 200, 32 | Message = "Success", 33 | Data = await this.authService.GenerateTokenASync(username, passoword) 34 | }); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /NewUpstorm.Web/Controllers/UsersController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using NewUpstorm.Service.DTOs; 3 | using NewUpstorm.Service.Interfaces; 4 | 5 | namespace NewUpstorm.Web.Controllers 6 | { 7 | public class UsersController : BaseController 8 | { 9 | private readonly IUserService userService; 10 | public UsersController(IUserService userService) 11 | { 12 | this.userService = userService; 13 | } 14 | 15 | [HttpPost("create")] 16 | public async Task PostAsync(UserCreationDto dto) 17 | => Ok(await this.userService.AddAsync(dto)); 18 | 19 | [HttpPut("post")] 20 | public async Task PutAsync(UserForUpdateDto dto) 21 | => Ok(await this.userService.ModifyAsync(dto)); 22 | 23 | [HttpDelete("delete")] 24 | public async Task DeleteAsync(long id) 25 | => Ok(await this.userService.RemoveAsync(id)); 26 | 27 | [HttpGet("id")] 28 | public async Task GetAsync(long id) 29 | => Ok(await this.userService.RetriewByIdAsync(id)); 30 | 31 | [HttpGet("list")] 32 | public async Task GetAllAsync([FromQuery]string search = null) 33 | => Ok(await this.userService.RetriewAllAsync(search)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /NewUpstorm.Web/Middlewares/ExceptionHandlerMiddleware.cs: -------------------------------------------------------------------------------- 1 | using NewUpstorm.Service.Exceptions; 2 | 3 | namespace NewUpstorm.Web.Middlewares 4 | { 5 | public class ExceptionHandlerMiddleware 6 | { 7 | private readonly RequestDelegate next; 8 | private readonly ILogger logger; 9 | public ExceptionHandlerMiddleware(RequestDelegate next, ILogger logger) 10 | { 11 | this.next = next; 12 | this.logger = logger; 13 | } 14 | 15 | public async Task InvokeAsync(HttpContext context) 16 | { 17 | try 18 | { 19 | await this.next(context); 20 | } 21 | catch (CustomException ex) 22 | { 23 | context.Response.StatusCode = ex.Code; 24 | await context.Response.WriteAsJsonAsync(new 25 | { 26 | Code = ex.Code, 27 | Message = ex.Message 28 | }); 29 | } 30 | catch (Exception ex) 31 | { 32 | this.logger.LogError($"{ex.ToString()}\n"); 33 | context.Response.StatusCode = 500; 34 | await context.Response.WriteAsJsonAsync(new 35 | { 36 | Code = 500, 37 | Message = ex.Message 38 | }); 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /NewUpstorm.Web/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | 9 | "AllowedHosts": "*", 10 | "ConnectionStrings": { 11 | "SqlConnection": "Server=(localdb)\\mssqllocaldb;Database=MyUpstorm;Trusted_Connection=True;" 12 | }, 13 | 14 | "Email": { 15 | "Host": "smtp.gmail.com", 16 | "EmailAddress": "firdavsmuzaffarov03@gmail.com", 17 | "Password": "fcfijmgfprhtyupyasdf" 18 | }, 19 | 20 | "Serilog": { 21 | "Using": [ 22 | "Serilog.Sinks.File" 23 | ], 24 | "MinimumLevel": { 25 | "Default": "Debug", 26 | "Override": { 27 | "Microsoft": "Error", 28 | "System": "Debug" 29 | } 30 | }, 31 | "Enrich": [ 32 | "FromLogContext", 33 | "WithMachineName", 34 | "WithProcessId", 35 | "WithThreadId" 36 | ], 37 | "WriteTo": [ 38 | { 39 | "Name": "File", 40 | "Args": { 41 | "path": "Logs//RestApiLog.log", 42 | "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}\n\n", 43 | "rollOnFileSizeLimit": true, 44 | "fileSizeLimitBytes": 4194304, 45 | "retainedFileCountLimit": 15, 46 | "rollingInterval": "Minute" 47 | } 48 | } 49 | ] 50 | }, 51 | 52 | "JWT": { 53 | "Key": "b0694d83-18fc-465f-abbd-dfcd94d1eca8", 54 | "Issuer": "https://new-upstorm.uz", 55 | "Audience": "ahsan.uz", 56 | "lifetime": 20 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /NewUpstorm.Data/Repositories/ForecastRepository.cs: -------------------------------------------------------------------------------- 1 | //using Newtonsoft.Json; 2 | //using Newtonsoft.Json.Linq; 3 | //using NewUpstorm.Data.IRepositories; 4 | //using NewUpstorm.Domain.Entities; 5 | //using System; 6 | 7 | //namespace NewUpstorm.Data.Repositories 8 | //{ 9 | // public class ForecastRepository : IForecastRepository 10 | // { 11 | // string path = AppAPISetting.PATH; 12 | // string weeklyPath = AppAPISetting.WEEKLY_PATH; 13 | 14 | // public async ValueTask SelectCurrentForecastAsync(string city) 15 | // { 16 | // path = path.Replace("Tashkent",city); 17 | 18 | // HttpClient client = new HttpClient(); 19 | // var response = (await client.GetAsync(path)); 20 | // string content = await response.Content.ReadAsStringAsync(); 21 | 22 | // RootObject data = JsonConvert.DeserializeObject(content); 23 | 24 | // return data; 25 | // } 26 | 27 | // public async ValueTask SelectWeeklyForecastAsync(string city, string county_code) 28 | // { 29 | // path = path.Replace("Tashkent", city).Replace("uz", county_code); 30 | 31 | // using (var httpClient = new HttpClient()) 32 | // { 33 | // var response = httpClient.GetAsync(path).Result; 34 | // var content = response.Content.ReadAsStringAsync().Result; 35 | 36 | // var data = JObject.Parse(content); 37 | 38 | // var forecasts = data["list"]; 39 | 40 | // return forecasts; 41 | // } 42 | // } 43 | // } 44 | //} 45 | -------------------------------------------------------------------------------- /NewUpstorm.Data/Migrations/20230516123134_FirstMigration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace NewUpstorm.Data.Migrations 7 | { 8 | public partial class FirstMigration : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.CreateTable( 13 | name: "Users", 14 | columns: table => new 15 | { 16 | Id = table.Column(type: "bigint", nullable: false) 17 | .Annotation("SqlServer:Identity", "1, 1"), 18 | FirstName = table.Column(type: "nvarchar(max)", nullable: true), 19 | LastName = table.Column(type: "nvarchar(max)", nullable: true), 20 | Email = table.Column(type: "nvarchar(max)", nullable: true), 21 | Password = table.Column(type: "nvarchar(max)", nullable: true), 22 | UserRole = table.Column(type: "int", nullable: false), 23 | CreatedAt = table.Column(type: "datetime2", nullable: false), 24 | UpdatedAt = table.Column(type: "datetime2", nullable: true) 25 | }, 26 | constraints: table => 27 | { 28 | table.PrimaryKey("PK_Users", x => x.Id); 29 | }); 30 | } 31 | 32 | protected override void Down(MigrationBuilder migrationBuilder) 33 | { 34 | migrationBuilder.DropTable( 35 | name: "Users"); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /NewUpstorm.Web/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.ApplicationModels; 2 | using Microsoft.EntityFrameworkCore; 3 | using NewUpstorm.Data.DbContexts; 4 | using NewUpstorm.Service.Mappers; 5 | using NewUpstorm.Web.Extensions; 6 | using NewUpstorm.Web.Helpers; 7 | using NewUpstorm.Web.Middlewares; 8 | using Serilog; 9 | 10 | var builder = WebApplication.CreateBuilder(args); 11 | 12 | // adding configuration db path 13 | builder.Services.AddDbContext(options => 14 | options.UseSqlServer(builder.Configuration.GetConnectionString("SqlConnection"))); 15 | builder.Services.AddAutoMapper(typeof(MappingProfile)); 16 | // add custom services 17 | builder.Services.AddCustomServices(); 18 | // Add services to the container. 19 | builder.Services.AddControllers(); 20 | // set up swagger 21 | builder.Services.AddSwaggerService(); 22 | // JWT servies 23 | builder.Services.AddJwtService(builder.Configuration); 24 | // Logger 25 | var logger = new LoggerConfiguration() 26 | .ReadFrom.Configuration(builder.Configuration) 27 | .Enrich.FromLogContext() 28 | .CreateLogger(); 29 | builder.Logging.ClearProviders(); 30 | builder.Logging.AddSerilog(logger); 31 | // convert api url name to dash case 32 | builder.Services.AddControllers(options => options.Conventions 33 | .Add(new RouteTokenTransformerConvention(new RouteConfiguration()))); 34 | 35 | 36 | var app = builder.Build(); 37 | 38 | // Configure the HTTP request pipeline. 39 | if (app.Environment.IsDevelopment()) 40 | { 41 | app.UseSwagger(); 42 | app.UseSwaggerUI(); 43 | } 44 | 45 | app.UseHttpsRedirection(); 46 | 47 | app.UseMiddleware(); 48 | 49 | app.UseAuthorization(); 50 | 51 | app.UseAuthorization(); 52 | 53 | app.MapControllers(); 54 | 55 | app.Run(); 56 | -------------------------------------------------------------------------------- /NewUpstorm.Data/Repositories/UserRepository.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using NewUpstorm.Data.DbContexts; 3 | using NewUpstorm.Data.IRepositories; 4 | using NewUpstorm.Domain.Entities; 5 | using System.Linq.Expressions; 6 | 7 | namespace NewUpstorm.Data.Repositories 8 | { 9 | public class UserRepository : IUserRepository 10 | { 11 | private readonly AppDbContext DbContext; 12 | public UserRepository(AppDbContext dbContext) 13 | { 14 | DbContext = dbContext; 15 | } 16 | 17 | public async ValueTask DeleteAsync(User user) 18 | { 19 | this.DbContext.Users.Remove(user); 20 | await this.DbContext.SaveChangesAsync(); 21 | return true; 22 | } 23 | 24 | public async ValueTask InsertAsync(User user) 25 | { 26 | var enteredUser = await this.DbContext.Users.AddAsync(user); 27 | await this.DbContext.SaveChangesAsync(); 28 | return enteredUser.Entity; 29 | } 30 | 31 | public IQueryable SelectAll(Expression> expression = null) 32 | { 33 | if (expression is not null) 34 | return this.DbContext.Users.Where(expression); 35 | 36 | return this.DbContext.Users; 37 | } 38 | 39 | public async ValueTask SelectAsync(Expression> expression) 40 | => await this.DbContext.Users.FirstOrDefaultAsync(expression); 41 | 42 | public async ValueTask UpdateAsync(User user) 43 | { 44 | var updatedUser = this.DbContext.Users.Update(user); 45 | await this.DbContext.SaveChangesAsync(); 46 | return updatedUser.Entity; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /NewUpstorm.Service/Services/AuthService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Microsoft.IdentityModel.Tokens; 3 | using NewUpstorm.Service.Interfaces; 4 | using System.IdentityModel.Tokens.Jwt; 5 | using System.Security.Claims; 6 | using System.Text; 7 | 8 | namespace NewUpstorm.Service.Services 9 | { 10 | public class AuthService : IAuthService 11 | { 12 | private readonly IUserService userService; 13 | private readonly IConfiguration configuration; 14 | public AuthService(IUserService userService, IConfiguration configuration) 15 | { 16 | this.userService = userService; 17 | this.configuration = configuration; 18 | } 19 | 20 | public async ValueTask GenerateTokenASync(string email, string password) 21 | { 22 | var user = await this.userService.CheckUserAsync(email, password); 23 | 24 | var tokenHandler = new JwtSecurityTokenHandler(); 25 | var tokenKey = Encoding.UTF8.GetBytes(configuration["JWT:Key"]); 26 | var tokenDescriptor = new SecurityTokenDescriptor 27 | { 28 | Subject = new ClaimsIdentity(new Claim[] 29 | { 30 | new Claim("Id", user.Id.ToString()), 31 | new Claim(ClaimTypes.Role, user.UserRole.ToString()), 32 | new Claim(ClaimTypes.Name, user.FirstName) 33 | }), 34 | IssuedAt = DateTime.UtcNow, 35 | Expires = DateTime.UtcNow.AddDays(1), 36 | SigningCredentials = new SigningCredentials( 37 | new SymmetricSecurityKey(tokenKey), SecurityAlgorithms.HmacSha256Signature) 38 | }; 39 | var token = tokenHandler.CreateToken(tokenDescriptor); 40 | return tokenHandler.WriteToken(token); 41 | } 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /NewUpstorm.Service/Services/ForecastService.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Linq; 3 | using NewUpstorm.Domain.Entities; 4 | using NewUpstorm.Service.Exceptions; 5 | using NewUpstorm.Service.Interfaces; 6 | using NewUpstorm.Service.Configurations; 7 | 8 | namespace NewUpstorm.Service.Services 9 | { 10 | public class ForecastService : IForecastService 11 | { 12 | string path = AppAPISetting.PATH; 13 | string weeklyPath = AppAPISetting.WEEKLY_PATH; 14 | 15 | public async ValueTask GetCurrentForecastAsync(string city) 16 | { 17 | path = path.Replace("Tashkent", city); 18 | 19 | HttpClient client = new HttpClient(); 20 | var response = (await client.GetAsync(path)); 21 | string content = await response.Content.ReadAsStringAsync(); 22 | RootObject weather = JsonConvert.DeserializeObject(content); 23 | 24 | if (weather.MainInfo is null) 25 | throw new CustomException(401, "API configuration error"); 26 | 27 | return weather; 28 | } 29 | 30 | public async Task> GetWeeklyForecstsAsync(string city, string countryCode) 31 | { 32 | string path = weeklyPath.Replace("Tashkent", city).Replace("uz", countryCode); 33 | 34 | using (var httpClient = new HttpClient()) 35 | { 36 | var response = await httpClient.GetAsync(path); 37 | var content = await response.Content.ReadAsStringAsync(); 38 | 39 | var data = JObject.Parse(content); 40 | var forecasts = data["list"]; 41 | 42 | if (forecasts == null || !forecasts.Any()) 43 | throw new CustomException(401, "API configuration error"); 44 | 45 | var results = forecasts.ToObject>(); 46 | return results; 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /NewUpstorm.Service/Services/EmailService.cs: -------------------------------------------------------------------------------- 1 | using MailKit.Net.Smtp; 2 | using MailKit.Security; 3 | using Microsoft.Extensions.Configuration; 4 | using MimeKit; 5 | using MimeKit.Text; 6 | using NewUpstorm.Service.Exceptions; 7 | using NewUpstorm.Service.Interfaces; 8 | using StackExchange.Redis; 9 | 10 | namespace NewUpstorm.Service.Services 11 | { 12 | public class EmailService : IEmailService 13 | { 14 | private readonly IConfiguration configuration; 15 | public EmailService(IConfiguration configuration) 16 | { 17 | this.configuration = configuration; 18 | } 19 | 20 | public async ValueTask SendEmailAsync(string to) 21 | { 22 | try 23 | { 24 | Random random = new Random(); 25 | int verificationCode = random.Next(123456, 999999); 26 | 27 | ConnectionMultiplexer redisConnect = ConnectionMultiplexer.Connect("localhost"); 28 | IDatabase db = redisConnect.GetDatabase(); 29 | db.StringSet("code", verificationCode.ToString()); 30 | var result = db.StringGet("code"); 31 | 32 | var email = new MimeMessage(); 33 | email.From.Add(MailboxAddress.Parse(this.configuration["EmailAddress"])); 34 | email.To.Add(MailboxAddress.Parse(to)); 35 | email.Subject = "Email verification upstorm.uz"; 36 | email.Body = new TextPart(TextFormat.Html) { Text = verificationCode.ToString() }; 37 | 38 | var sendMessage = new SmtpClient(); 39 | await sendMessage.ConnectAsync(this.configuration["Host"], 587, SecureSocketOptions.StartTls); 40 | await sendMessage.AuthenticateAsync(this.configuration["EmailAddress"], this.configuration["Password"]); 41 | await sendMessage.SendAsync(email); 42 | await sendMessage.DisconnectAsync(true); 43 | 44 | return verificationCode.ToString(); 45 | } 46 | catch (Exception ex) 47 | { 48 | throw new CustomException(400, ex.Message); 49 | } 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /NewUpstorm.Data/Migrations/AppDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using NewUpstorm.Data.DbContexts; 8 | 9 | #nullable disable 10 | 11 | namespace NewUpstorm.Data.Migrations 12 | { 13 | [DbContext(typeof(AppDbContext))] 14 | partial class AppDbContextModelSnapshot : ModelSnapshot 15 | { 16 | protected override void BuildModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "6.0.12") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 22 | 23 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 24 | 25 | modelBuilder.Entity("NewUpstorm.Domain.Entities.User", b => 26 | { 27 | b.Property("Id") 28 | .ValueGeneratedOnAdd() 29 | .HasColumnType("bigint"); 30 | 31 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 32 | 33 | b.Property("CreatedAt") 34 | .HasColumnType("datetime2"); 35 | 36 | b.Property("Email") 37 | .HasColumnType("nvarchar(max)"); 38 | 39 | b.Property("FirstName") 40 | .HasColumnType("nvarchar(max)"); 41 | 42 | b.Property("LastName") 43 | .HasColumnType("nvarchar(max)"); 44 | 45 | b.Property("Password") 46 | .HasColumnType("nvarchar(max)"); 47 | 48 | b.Property("UpdatedAt") 49 | .HasColumnType("datetime2"); 50 | 51 | b.Property("UserRole") 52 | .HasColumnType("int"); 53 | 54 | b.HasKey("Id"); 55 | 56 | b.ToTable("Users"); 57 | }); 58 | #pragma warning restore 612, 618 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /NewUpstorm.Data/Migrations/20230516123134_FirstMigration.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using NewUpstorm.Data.DbContexts; 9 | 10 | #nullable disable 11 | 12 | namespace NewUpstorm.Data.Migrations 13 | { 14 | [DbContext(typeof(AppDbContext))] 15 | [Migration("20230516123134_FirstMigration")] 16 | partial class FirstMigration 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.12") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 24 | 25 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 26 | 27 | modelBuilder.Entity("NewUpstorm.Domain.Entities.User", b => 28 | { 29 | b.Property("Id") 30 | .ValueGeneratedOnAdd() 31 | .HasColumnType("bigint"); 32 | 33 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 34 | 35 | b.Property("CreatedAt") 36 | .HasColumnType("datetime2"); 37 | 38 | b.Property("Email") 39 | .HasColumnType("nvarchar(max)"); 40 | 41 | b.Property("FirstName") 42 | .HasColumnType("nvarchar(max)"); 43 | 44 | b.Property("LastName") 45 | .HasColumnType("nvarchar(max)"); 46 | 47 | b.Property("Password") 48 | .HasColumnType("nvarchar(max)"); 49 | 50 | b.Property("UpdatedAt") 51 | .HasColumnType("datetime2"); 52 | 53 | b.Property("UserRole") 54 | .HasColumnType("int"); 55 | 56 | b.HasKey("Id"); 57 | 58 | b.ToTable("Users"); 59 | }); 60 | #pragma warning restore 612, 618 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /NewUpstorm.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.4.33205.214 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NewUpstorm.Data", "NewUpstorm.Data\NewUpstorm.Data.csproj", "{EC81B8A3-E50E-4781-ABDC-71EB9A6EEAE1}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NewUpstorm.Domain", "NewUpstorm.Domain\NewUpstorm.Domain.csproj", "{5DEC1FCA-289A-4B24-B53A-53DAC084EBD9}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NewUpstorm.Service", "NewUpstorm.Service\NewUpstorm.Service.csproj", "{3D9EBE14-D89E-4E84-A1E9-5E124A520E35}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NewUpstorm.Web", "NewUpstorm.Web\NewUpstorm.Web.csproj", "{32BC6725-2E42-4741-BDDD-4F474B9C88E9}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {EC81B8A3-E50E-4781-ABDC-71EB9A6EEAE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {EC81B8A3-E50E-4781-ABDC-71EB9A6EEAE1}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {EC81B8A3-E50E-4781-ABDC-71EB9A6EEAE1}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {EC81B8A3-E50E-4781-ABDC-71EB9A6EEAE1}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {5DEC1FCA-289A-4B24-B53A-53DAC084EBD9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {5DEC1FCA-289A-4B24-B53A-53DAC084EBD9}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {5DEC1FCA-289A-4B24-B53A-53DAC084EBD9}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {5DEC1FCA-289A-4B24-B53A-53DAC084EBD9}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {3D9EBE14-D89E-4E84-A1E9-5E124A520E35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {3D9EBE14-D89E-4E84-A1E9-5E124A520E35}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {3D9EBE14-D89E-4E84-A1E9-5E124A520E35}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {3D9EBE14-D89E-4E84-A1E9-5E124A520E35}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {32BC6725-2E42-4741-BDDD-4F474B9C88E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {32BC6725-2E42-4741-BDDD-4F474B9C88E9}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {32BC6725-2E42-4741-BDDD-4F474B9C88E9}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {32BC6725-2E42-4741-BDDD-4F474B9C88E9}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | GlobalSection(ExtensibilityGlobals) = postSolution 41 | SolutionGuid = {4DFD69BB-6A5B-4D4F-AE02-FC80DC29DC9E} 42 | EndGlobalSection 43 | EndGlobal 44 | -------------------------------------------------------------------------------- /NewUpstorm.Web/Extensions/ServiceExtentions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication.JwtBearer; 2 | using Microsoft.IdentityModel.Tokens; 3 | using Microsoft.OpenApi.Any; 4 | using Microsoft.OpenApi.Models; 5 | using NewUpstorm.Data.IRepositories; 6 | using NewUpstorm.Data.Repositories; 7 | using NewUpstorm.Service.Interfaces; 8 | using NewUpstorm.Service.Services; 9 | using System.Reflection; 10 | using System.Text; 11 | 12 | namespace NewUpstorm.Web.Extensions 13 | { 14 | public static class ServiceExtentions 15 | { 16 | public static void AddCustomServices(this IServiceCollection services) 17 | { 18 | services.AddScoped(); 19 | services.AddScoped(); 20 | services.AddScoped(); 21 | services.AddScoped(); 22 | 23 | services.AddScoped(); 24 | } 25 | 26 | public static void AddSwaggerService(this IServiceCollection services) 27 | { 28 | services.AddSwaggerGen(c => 29 | { 30 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "New-upstorm.api", Version = "v1" }); 31 | var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Version}.xml"; 32 | 33 | c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme 34 | { 35 | Name = "Authorization", 36 | Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", 37 | In = ParameterLocation.Header, 38 | Type = SecuritySchemeType.ApiKey 39 | }); 40 | 41 | c.AddSecurityRequirement(new OpenApiSecurityRequirement 42 | { 43 | { 44 | new OpenApiSecurityScheme 45 | { 46 | Reference = new OpenApiReference 47 | { 48 | Type = ReferenceType .SecurityScheme, 49 | Id = "Bearer" 50 | } 51 | }, 52 | new string[] {} 53 | } 54 | }); 55 | }); 56 | } 57 | 58 | public static void AddJwtService(this IServiceCollection services, IConfiguration configuration) 59 | { 60 | services.AddAuthentication(x => 61 | { 62 | x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 63 | x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 64 | }).AddJwtBearer(o => 65 | { 66 | var Key = Encoding.UTF8.GetBytes(configuration["JWT:Key"]); 67 | o.SaveToken = true; 68 | o.TokenValidationParameters = new TokenValidationParameters 69 | { 70 | ValidateIssuer = true, 71 | ValidateAudience = true, 72 | ValidateLifetime = true, 73 | ValidateIssuerSigningKey = true, 74 | ValidIssuer = configuration["JWT:Issuer"], 75 | ValidAudience = configuration["JWT:Audience"], 76 | IssuerSigningKey = new SymmetricSecurityKey(Key) 77 | }; 78 | }); 79 | } 80 | 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /NewUpstorm.Service/Services/UserService.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using NewUpstorm.Data.IRepositories; 3 | using NewUpstorm.Domain.Entities; 4 | using NewUpstorm.Service.DTOs; 5 | using NewUpstorm.Service.Exceptions; 6 | using NewUpstorm.Service.Interfaces; 7 | 8 | namespace NewUpstorm.Service.Services 9 | { 10 | public class UserService : IUserService 11 | { 12 | private readonly IMapper mapper; 13 | private readonly IUserRepository userRepository; 14 | public UserService(IUserRepository userRepository, IMapper mapper) 15 | { 16 | this.userRepository = userRepository; 17 | this.mapper = mapper; 18 | } 19 | 20 | public async ValueTask AddAsync(UserCreationDto userDto) 21 | { 22 | var user = await this.userRepository.SelectAsync(t => t.Email == userDto.Email); 23 | if (user is not null) 24 | throw new CustomException(403, "User already exist"); 25 | 26 | var mappedUser = this.mapper.Map(userDto); 27 | var result = await this.userRepository.InsertAsync(mappedUser); 28 | return this.mapper.Map(result); 29 | } 30 | 31 | public async ValueTask ModifyAsync(UserForUpdateDto userDto) 32 | { 33 | var updatingUser = await this.userRepository.SelectAsync(t => t.Id == userDto.Id); 34 | if (updatingUser is null) 35 | throw new CustomException(404, "User not found"); 36 | 37 | this.mapper.Map(userDto, updatingUser); 38 | updatingUser.UpdatedAt = DateTime.UtcNow; 39 | var result = await this.userRepository.UpdateAsync(updatingUser); 40 | return this.mapper.Map(result); 41 | } 42 | 43 | public async ValueTask RemoveAsync(long id) 44 | { 45 | var user = await this.userRepository.SelectAsync(t => t.Id == id); 46 | if (user is null) 47 | throw new CustomException(404, "User not found"); 48 | 49 | return await this.userRepository.DeleteAsync(user); 50 | } 51 | 52 | public async ValueTask> RetriewAllAsync(string search = null) 53 | { 54 | var users = this.userRepository.SelectAll(); 55 | var result = this.mapper.Map>(users); 56 | 57 | if (!string.IsNullOrEmpty(search)) 58 | return result.Where( 59 | u => u.FirstName.ToLower().Contains(search.ToLower()) || 60 | u.LastName.ToLower().Contains(search.ToLower()) || 61 | u.Email.ToLower().Contains(search.ToLower())) 62 | .ToList(); 63 | 64 | return result; 65 | } 66 | 67 | public async ValueTask RetriewByIdAsync(long id) 68 | { 69 | var user = await this.userRepository.SelectAsync(t => t.Id == id); 70 | if (user is null) 71 | throw new CustomException(404, "User not found"); 72 | 73 | return this.mapper.Map(user); 74 | } 75 | 76 | public async ValueTask ChangePaswordAsync(UserForPasswordDto userDto) 77 | { 78 | var existUser = await this.userRepository.SelectAsync(t => t.Email.ToLower() == userDto.Email.ToLower()); 79 | if (existUser is null) 80 | throw new Exception("This username is not exist"); 81 | else if (userDto.NewPasswword != userDto.ConfirmPassword) 82 | throw new Exception("New password and confirm password are not equal"); 83 | else if (existUser.Password != userDto.NewPasswword) 84 | throw new Exception("Paassword is incorrect"); 85 | 86 | existUser.Password = userDto.ConfirmPassword; 87 | await this.userRepository.UpdateAsync(existUser); 88 | return this.mapper.Map(existUser); 89 | } 90 | 91 | public async ValueTask UserVerify(string code) 92 | { 93 | throw new NotImplementedException(); 94 | } 95 | 96 | public async ValueTask CheckUserAsync(string email, string password = null) 97 | { 98 | var user = await this.userRepository.SelectAsync(t => t.Email.ToLower() == email.ToLower()); 99 | if (user is null) 100 | throw new CustomException(404, "User is not found"); 101 | return this.mapper.Map(user); 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The following command works for downloading when using Git for Windows: 2 | # curl -LOf http://gist.githubusercontent.com/kmorcinek/2710267/raw/.gitignore 3 | # 4 | # Download this file using PowerShell v3 under Windows with the following comand: 5 | # Invoke-WebRequest https://gist.githubusercontent.com/kmorcinek/2710267/raw/ -OutFile .gitignore 6 | # 7 | # or wget: 8 | # wget --no-check-certificate http://gist.githubusercontent.com/kmorcinek/2710267/raw/.gitignore 9 | 10 | # User-specific files 11 | *.suo 12 | *.user 13 | *.sln.docstates 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Rr]elease/ 18 | x64/ 19 | [Bb]in/ 20 | [Oo]bj/ 21 | # build folder is nowadays used for build scripts and should not be ignored 22 | #build/ 23 | 24 | # NuGet Packages 25 | *.nupkg 26 | # The packages folder can be ignored because of Package Restore 27 | **/packages/* 28 | # except build/, which is used as an MSBuild target. 29 | !**/packages/build/ 30 | # Uncomment if necessary however generally it will be regenerated when needed 31 | #!**/packages/repositories.config 32 | 33 | # MSTest test Results 34 | [Tt]est[Rr]esult*/ 35 | [Bb]uild[Ll]og.* 36 | 37 | *_i.c 38 | *_p.c 39 | *.ilk 40 | *.meta 41 | *.obj 42 | *.pch 43 | *.pdb 44 | *.pgc 45 | *.pgd 46 | *.rsp 47 | *.sbr 48 | *.tlb 49 | *.tli 50 | *.tlh 51 | *.tmp 52 | *.tmp_proj 53 | *.log 54 | *.vspscc 55 | *.vssscc 56 | .builds 57 | *.pidb 58 | *.scc 59 | 60 | # Visual C++ cache files 61 | ipch/ 62 | *.aps 63 | *.ncb 64 | *.opensdf 65 | *.sdf 66 | *.cachefile 67 | 68 | # Visual Studio profiler 69 | *.psess 70 | *.vsp 71 | *.vspx 72 | 73 | # Guidance Automation Toolkit 74 | *.gpState 75 | 76 | # ReSharper is a .NET coding add-in 77 | _ReSharper*/ 78 | *.[Rr]e[Ss]harper 79 | 80 | # TeamCity is a build add-in 81 | _TeamCity* 82 | 83 | # DotCover is a Code Coverage Tool 84 | *.dotCover 85 | 86 | # NCrunch 87 | *.ncrunch* 88 | .*crunch*.local.xml 89 | 90 | # Installshield output folder 91 | [Ee]xpress/ 92 | 93 | # DocProject is a documentation generator add-in 94 | DocProject/buildhelp/ 95 | DocProject/Help/*.HxT 96 | DocProject/Help/*.HxC 97 | DocProject/Help/*.hhc 98 | DocProject/Help/*.hhk 99 | DocProject/Help/*.hhp 100 | DocProject/Help/Html2 101 | DocProject/Help/html 102 | 103 | # Click-Once directory 104 | publish/ 105 | 106 | # Publish Web Output 107 | *.Publish.xml 108 | 109 | # Windows Azure Build Output 110 | csx 111 | *.build.csdef 112 | 113 | # Windows Store app package directory 114 | AppPackages/ 115 | 116 | # Others 117 | *.Cache 118 | ClientBin/ 119 | [Ss]tyle[Cc]op.* 120 | ~$* 121 | *~ 122 | *.dbmdl 123 | *.[Pp]ublish.xml 124 | *.pfx 125 | *.publishsettings 126 | modulesbin/ 127 | tempbin/ 128 | 129 | # EPiServer Site file (VPP) 130 | AppData/ 131 | 132 | # RIA/Silverlight projects 133 | Generated_Code/ 134 | 135 | # Backup & report files from converting an old project file to a newer 136 | # Visual Studio version. Backup files are not needed, because we have git ;-) 137 | _UpgradeReport_Files/ 138 | Backup*/ 139 | UpgradeLog*.XML 140 | UpgradeLog*.htm 141 | 142 | # vim 143 | *.txt~ 144 | *.swp 145 | *.swo 146 | 147 | # Temp files when opening LibreOffice on ubuntu 148 | .~lock.* 149 | 150 | # svn 151 | .svn 152 | 153 | # CVS - Source Control 154 | **/CVS/ 155 | 156 | # Remainings from resolving conflicts in Source Control 157 | *.orig 158 | 159 | # SQL Server files 160 | **/App_Data/*.mdf 161 | **/App_Data/*.ldf 162 | **/App_Data/*.sdf 163 | 164 | 165 | #LightSwitch generated files 166 | GeneratedArtifacts/ 167 | _Pvt_Extensions/ 168 | ModelManifest.xml 169 | 170 | # ========================= 171 | # Windows detritus 172 | # ========================= 173 | 174 | # Windows image file caches 175 | Thumbs.db 176 | ehthumbs.db 177 | 178 | # Folder config file 179 | Desktop.ini 180 | 181 | # Recycle Bin used on file shares 182 | $RECYCLE.BIN/ 183 | 184 | # OS generated files # 185 | Icon? 186 | 187 | # Mac desktop service store files 188 | .DS_Store 189 | 190 | # SASS Compiler cache 191 | .sass-cache 192 | 193 | # Visual Studio 2014 CTP 194 | **/*.sln.ide 195 | 196 | # Visual Studio temp something 197 | .vs/ 198 | 199 | # dotnet stuff 200 | project.lock.json 201 | 202 | # VS 2015+ 203 | *.vc.vc.opendb 204 | *.vc.db 205 | 206 | # Rider 207 | .idea/ 208 | 209 | # Visual Studio Code 210 | .vscode/ 211 | 212 | # Output folder used by Webpack or other FE stuff 213 | **/node_modules/* 214 | **/wwwroot/* 215 | 216 | # SpecFlow specific 217 | *.feature.cs 218 | *.feature.xlsx.* 219 | *.Specs_*.html 220 | 221 | # UWP Projects 222 | AppPackages/ 223 | 224 | ##### 225 | # End of core ignore list, below put you custom 'per project' settings (patterns or path) 226 | ##### 227 | /NewUpstorm.Web/Logs/RestApiLog202305211720.log 228 | /NewUpstorm.Web/Logs/RestApiLog202305211721.log 229 | --------------------------------------------------------------------------------