diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..ce3b7779 --- /dev/null +++ b/.gitignore @@ -0,0 +1,404 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates +*.old +*.original +*.txt +*.bin +*.ldf +*.mdf + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/APIBook/.dockerignore b/APIBook/.dockerignore new file mode 100644 index 00000000..3729ff0c --- /dev/null +++ b/APIBook/.dockerignore @@ -0,0 +1,25 @@ +**/.classpath +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md \ No newline at end of file diff --git a/APIBook/.vscode/launch.json b/APIBook/.vscode/launch.json new file mode 100644 index 00000000..672dc349 --- /dev/null +++ b/APIBook/.vscode/launch.json @@ -0,0 +1,35 @@ +{ + "version": "0.2.0", + "configurations": [ + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "name": ".NET Core Launch (web)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/APIBook/bin/Debug/net6.0/APIBook.dll", + "args": [], + "cwd": "${workspaceFolder}/APIBook", + "stopAtEntry": false, + // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + } + ] +} \ No newline at end of file diff --git a/APIBook/.vscode/tasks.json b/APIBook/.vscode/tasks.json new file mode 100644 index 00000000..239633cf --- /dev/null +++ b/APIBook/.vscode/tasks.json @@ -0,0 +1,41 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/APIBook/APIBook.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/APIBook/APIBook.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/APIBook/APIBook.csproj" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/APIBook/APIBook.sln b/APIBook/APIBook.sln new file mode 100644 index 00000000..f5f54ef2 --- /dev/null +++ b/APIBook/APIBook.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.4.33103.184 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "APIBook", "APIBook\APIBook.csproj", "{3C79CF80-0AD9-42A5-8FA8-6B75170A037F}" +EndProject +Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-compose.dcproj", "{E51AE39F-906B-43A0-B84C-87C090CBC6FB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3C79CF80-0AD9-42A5-8FA8-6B75170A037F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3C79CF80-0AD9-42A5-8FA8-6B75170A037F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3C79CF80-0AD9-42A5-8FA8-6B75170A037F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3C79CF80-0AD9-42A5-8FA8-6B75170A037F}.Release|Any CPU.Build.0 = Release|Any CPU + {E51AE39F-906B-43A0-B84C-87C090CBC6FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E51AE39F-906B-43A0-B84C-87C090CBC6FB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E51AE39F-906B-43A0-B84C-87C090CBC6FB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E51AE39F-906B-43A0-B84C-87C090CBC6FB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {EB867682-F5B3-445D-887B-C39BEA7452A9} + EndGlobalSection +EndGlobal diff --git a/APIBook/APIBook/APIBook.csproj b/APIBook/APIBook/APIBook.csproj new file mode 100644 index 00000000..bfd373a0 --- /dev/null +++ b/APIBook/APIBook/APIBook.csproj @@ -0,0 +1,36 @@ + + + + net6.0 + enable + enable + ecb3b24a-4605-4a48-a09b-7da3b33965f5 + Linux + ..\docker-compose.dcproj + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + diff --git a/APIBook/APIBook/Authorization/Auth.cs b/APIBook/APIBook/Authorization/Auth.cs new file mode 100644 index 00000000..8420af29 --- /dev/null +++ b/APIBook/APIBook/Authorization/Auth.cs @@ -0,0 +1,46 @@ +using APIBook.Repository; +using Microsoft.IdentityModel.Tokens; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; + +namespace APIBook +{ + public class JwtAuth + { + private readonly string _key; + + + public JwtAuth(string key) + { + _key = key; + } + + public string Authenticate(string username, string password) + { + User user_loggin = UserRepository.Get(username, password); // Pegar o usuario do pseudo repositorio. + + + JwtSecurityTokenHandler token_handle = new JwtSecurityTokenHandler(); + + var token_key = Encoding.ASCII.GetBytes(_key); + + SecurityTokenDescriptor token_descriptor = new SecurityTokenDescriptor + { + Subject = new ClaimsIdentity(new Claim[] + { + new Claim(ClaimTypes.Name, user_loggin.Username), // objetos utilizado para formar a token unica do usuario. + new Claim(ClaimTypes.Role, user_loggin.Role) + }), + Expires = DateTime.UtcNow.AddHours(1), // limita a token por uma hora + SigningCredentials = new SigningCredentials( + new SymmetricSecurityKey(token_key), + SecurityAlgorithms.HmacSha256Signature) + }; + + var token = token_handle.CreateToken(token_descriptor); + + return token_handle.WriteToken(token); // trasnformar class da token em string + } + } +} diff --git a/APIBook/APIBook/Controller/BookController.cs b/APIBook/APIBook/Controller/BookController.cs new file mode 100644 index 00000000..5b2513d8 --- /dev/null +++ b/APIBook/APIBook/Controller/BookController.cs @@ -0,0 +1,132 @@ +using APIBook.Model; +using APIBook.Repository; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace APIBook.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class BookController : ControllerBase + { + private readonly JwtAuth _jwtAuthentication; + private readonly IBookRepository _bookRepository; + public BookController(IBookRepository bookRepository, JwtAuth auth) + { + _bookRepository = bookRepository; + _jwtAuthentication = auth; + } + + + + // Qualquer usuario logado ou não pode utilizar + [HttpGet] + public async Task> GetBooks() + { + var b = await _bookRepository.Get(); // Pegando a lista de livros representado por b + if(b == null) + return NoContent(); + + return Ok(b.OrderBy(x => x.Title)); // Ordenar a ordem em Acresente pelo TITULO como julgado no teste + } + + + // Apenas usuarios autenticados podem usar + [Authorize] + [HttpGet("{id}")] + public async Task> GetBook(int id) + { + Book? book = await _bookRepository.GetById(id); // irar chamar a função de get by ID e procurar na DB + + if (book == null) // Se nesse caso retornar nenhum livro a variavel nomeada book sera nulla nesse caso deve se esperar o retorno NotFound codigo 404 + return NotFound(); + + return Ok(book); // Caso contrario e encontrar algum livro do ID em questão é necessario retornar o objeto ao usuario + } + + + [Authorize (Roles = "admin,user")] + [HttpGet("(Title){Title}")] // Esse argumento (Title) vai ser o indentificador da função para diferenciar a do ID + public async Task> GetBook(string Title) + { + var b = await _bookRepository.GetByName(Title); // Irar procurar na db qualquer livro que contem esse titulo sendo inteiro ou em pedaços + if(b == null) + return NotFound(); + + return Ok(b); + } + + // Apenas o ADMIN pode usar para postar, atualizar e deletar, respeite o admin. https://youtu.be/yxq0ZnjEENs + [Authorize(Roles = "admin")] + [HttpPost] + public async Task> PostBook([FromBody] Book book) + { + var books = await _bookRepository.Get(); + if(books == null) + return NoContent(); + + Book? new_book = new Book(); + bool found = false; + foreach (Book b in books) + { + if(b.Title == null || book.Title == null) + continue; + + if (b.Date == book.Date && b.Title.ToLower() == book.Title.ToLower()) + { + found = true; + break; + } + } + + if (found) + return NoContent(); + + new_book = await _bookRepository.Create(book); + if(new_book == null) + return NoContent(); + + return CreatedAtAction(nameof(GetBook), new { id = new_book.Id }, new_book); + } + + [Authorize(Roles = "admin")] + [HttpDelete("{id}")] + public async Task Delete(int id) + { + Book? book = await _bookRepository.GetById(id); + if (book == null) + return NotFound(); + + await _bookRepository.Delete(id); + + return NoContent(); + } + + + [Authorize(Roles = "admin")] + [HttpPut("{id}")] + public async Task PutBooks(int id, [FromBody] Book book) + { + if (id != book.Id) + return NoContent(); + + await _bookRepository.Update(book); + return Ok(book); + } + + // Qualquer anonimo pode autorizar + [AllowAnonymous] + [HttpPost("Auth")] + public ActionResult AuthUser([FromBody] User user) + { + string? token = _jwtAuthentication.Authenticate(user.Username, user.Password); + if (token == null) + return Unauthorized(); + return Ok(new { + usuario = user.Username, + tokken = token + }); + } + } + +} diff --git a/APIBook/APIBook/Dockerfile b/APIBook/APIBook/Dockerfile new file mode 100644 index 00000000..7caca2a9 --- /dev/null +++ b/APIBook/APIBook/Dockerfile @@ -0,0 +1,20 @@ +FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base +WORKDIR /app +EXPOSE 80 +EXPOSE 443 + +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build +WORKDIR /src +COPY ["APIBook/APIBook.csproj", "APIBook/"] +RUN dotnet restore "APIBook/APIBook.csproj" +COPY . . +WORKDIR "/src/APIBook" +RUN dotnet build "APIBook.csproj" -c Release -o /app/build + +FROM build AS publish +RUN dotnet publish "APIBook.csproj" -c Release -o /app/publish /p:UseAppHost=false + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "APIBook.dll"] \ No newline at end of file diff --git a/APIBook/APIBook/Migrations/20221112182723_booksDB.Designer.cs b/APIBook/APIBook/Migrations/20221112182723_booksDB.Designer.cs new file mode 100644 index 00000000..23487862 --- /dev/null +++ b/APIBook/APIBook/Migrations/20221112182723_booksDB.Designer.cs @@ -0,0 +1,57 @@ +// +using APIBook.Model; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace APIBook.Migrations +{ + [DbContext(typeof(BookContext))] + [Migration("20221112182723_booksDB")] + partial class booksDB + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("APIBook.Model.Book", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Author") + .HasColumnType("nvarchar(max)"); + + b.Property("Date") + .HasColumnType("nvarchar(max)"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Saga") + .HasColumnType("nvarchar(max)"); + + b.Property("Title") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Books"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/APIBook/APIBook/Migrations/20221112182723_booksDB.cs b/APIBook/APIBook/Migrations/20221112182723_booksDB.cs new file mode 100644 index 00000000..d81d1566 --- /dev/null +++ b/APIBook/APIBook/Migrations/20221112182723_booksDB.cs @@ -0,0 +1,38 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace APIBook.Migrations +{ + /// + public partial class booksDB : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Books", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Title = table.Column(type: "nvarchar(max)", nullable: true), + Saga = table.Column(type: "nvarchar(max)", nullable: true), + Description = table.Column(type: "nvarchar(max)", nullable: true), + Author = table.Column(type: "nvarchar(max)", nullable: true), + Date = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Books", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Books"); + } + } +} diff --git a/APIBook/APIBook/Migrations/BookContextModelSnapshot.cs b/APIBook/APIBook/Migrations/BookContextModelSnapshot.cs new file mode 100644 index 00000000..eac6cef0 --- /dev/null +++ b/APIBook/APIBook/Migrations/BookContextModelSnapshot.cs @@ -0,0 +1,54 @@ +// +using APIBook.Model; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace APIBook.Migrations +{ + [DbContext(typeof(BookContext))] + partial class BookContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("APIBook.Model.Book", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Author") + .HasColumnType("nvarchar(max)"); + + b.Property("Date") + .HasColumnType("nvarchar(max)"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Saga") + .HasColumnType("nvarchar(max)"); + + b.Property("Title") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Books"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/APIBook/APIBook/Model/Book.cs b/APIBook/APIBook/Model/Book.cs new file mode 100644 index 00000000..68790ffb --- /dev/null +++ b/APIBook/APIBook/Model/Book.cs @@ -0,0 +1,12 @@ +namespace APIBook.Model +{ + public class Book + { + public int Id { get; set; } + public string? Title { get; set; } + public string? Saga { get; set; } + public string? Description { get; set; } + public string? Author { get; set; } + public string? Date { get; set; } + } +} diff --git a/APIBook/APIBook/Model/BookContext.cs b/APIBook/APIBook/Model/BookContext.cs new file mode 100644 index 00000000..dbf23cc1 --- /dev/null +++ b/APIBook/APIBook/Model/BookContext.cs @@ -0,0 +1,14 @@ +using Microsoft.EntityFrameworkCore; + +namespace APIBook.Model +{ + public class BookContext : DbContext + { + public DbSet? Books { get; set; } // O banco de dados + public BookContext(DbContextOptions options) : base(options) + { + + } + + } +} diff --git a/APIBook/APIBook/Model/User.cs b/APIBook/APIBook/Model/User.cs new file mode 100644 index 00000000..b2709d52 --- /dev/null +++ b/APIBook/APIBook/Model/User.cs @@ -0,0 +1,13 @@ +namespace APIBook +{ + + public class User + { + public int ID { get; set; } = 0; + public string Username { get; set; } = string.Empty; + + public string Password { get; set; } = string.Empty; + + public string Role { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/APIBook/APIBook/Program.cs b/APIBook/APIBook/Program.cs new file mode 100644 index 00000000..69885efe --- /dev/null +++ b/APIBook/APIBook/Program.cs @@ -0,0 +1,86 @@ +using APIBook.Model; +using APIBook.Repository; +using APIBook.Services; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.Tokens; +using Serilog; +using System.Text; + +namespace APIBook +{ + public class Program + { + public static void Main(string[] args) + { + var builder = WebApplication.CreateBuilder(args); + + + Log.Logger = (Serilog.ILogger)new LoggerConfiguration() + .WriteTo.File("programlogs/log.txt", Serilog.Events.LogEventLevel.Information) + //.WriteTo.Console() + .CreateLogger(); + + + + builder.Services.AddControllers(); + // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle + builder.Services.AddEndpointsApiExplorer(); + builder.Services.AddSwaggerGen(c => + { + c.SwaggerDoc("V0.0.1 Dirty", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "YOUNG BOOKS API", Version = "v0.0.1 Dirty" }); + }); + builder.Services.AddScoped(); + var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); + + builder.Services.AddDbContext(db => db.UseSqlServer(connectionString)); + + + string key = "$$os_seguredos_dos_admins1337_iaiaiaiaiaiii$$"; // chave + + builder.Services.AddAuthentication(c => { + c.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + c.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }).AddJwtBearer(c => + { + c.RequireHttpsMetadata = false; + c.SaveToken = true; + c.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters + { + IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key)), + ValidateIssuerSigningKey = true, + ValidateIssuer = false, + ValidateAudience = false + }; + }); + + + builder.Services.AddSingleton(new JwtAuth(key)); // adiciona a chave para a cripotgrafia para o token + + builder.Host.UseSerilog(Log.Logger); // adicionar o Serilog como sistema de logs + + var app = builder.Build(); + + //create db + DataBaseMigrateService.MigrationInitialsation(app); // criar a o banco de dado caso não tenha + + // Configure the HTTP request pipeline. + if (app.Environment.IsDevelopment()) + { + app.UseSwagger(); + } + app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/V0.0.1 Dirty/swagger.json", "YOUNG BOOKS API v0.0.1 Dirty")); + + + app.UseHttpsRedirection(); + + app.UseAuthentication(); + app.UseAuthorization(); + + + app.MapControllers(); + + app.Run(); + } + } +} \ No newline at end of file diff --git a/APIBook/APIBook/Properties/launchSettings.json b/APIBook/APIBook/Properties/launchSettings.json new file mode 100644 index 00000000..d1eea4e0 --- /dev/null +++ b/APIBook/APIBook/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "profiles": { + "APIBook": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "https://localhost:7190;http://localhost:5297" + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "Docker": { + "commandName": "Docker", + "launchBrowser": true, + "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger", + "publishAllPorts": true, + "useSSL": true + } + }, + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:22894", + "sslPort": 44317 + } + } +} \ No newline at end of file diff --git a/APIBook/APIBook/Repository/BookRepository.cs b/APIBook/APIBook/Repository/BookRepository.cs new file mode 100644 index 00000000..935ea502 --- /dev/null +++ b/APIBook/APIBook/Repository/BookRepository.cs @@ -0,0 +1,87 @@ +using APIBook.Model; +using Microsoft.EntityFrameworkCore; + +namespace APIBook.Repository +{ + public class BookRepository : IBookRepository + { + public readonly BookContext _ctx; + public BookRepository(BookContext context) + { + _ctx = context; + } + + //Metodos asyncronos + async Task IBookRepository.Create(Book book) + { + if (_ctx.Books == null) + return book; + + await _ctx.Books.AddAsync(book); + await _ctx.SaveChangesAsync(); + return book; + } + + async Task?> IBookRepository.Get() + { + if(_ctx.Books == null) + return null; + + return await _ctx.Books.ToListAsync(); + } + + async Task?> IBookRepository.GetByName(string title) + { + if(_ctx.Books == null) + return null; + + var books = await _ctx.Books.ToListAsync(); + List books_ = new List(); + foreach (var b in books) + { + if (b.Title == null) + continue; + + if (b.Title.Contains(title)) + books_.Add(b); + } + + return books_; + } + + async Task IBookRepository.GetById(int id) + { + if(_ctx.Books == null) + return null; + + return await _ctx.Books.FindAsync(id); + } + + + async Task IBookRepository.Delete(int id) + { + if(_ctx.Books == null) + return false; + + Book? book_for_delete = await _ctx.Books.FindAsync(id); + + if(book_for_delete == null) + return false; + + _ = _ctx.Remove(book_for_delete); + await _ctx.SaveChangesAsync(); + return true; + } + + + async Task IBookRepository.Update(Book book) + { + if(_ctx.Books == null) + return false; + + _ctx.Entry(book).State = EntityState.Modified; + await _ctx.SaveChangesAsync(); + return true; + } + } +} diff --git a/APIBook/APIBook/Repository/IBookRepository.cs b/APIBook/APIBook/Repository/IBookRepository.cs new file mode 100644 index 00000000..15e3e4bf --- /dev/null +++ b/APIBook/APIBook/Repository/IBookRepository.cs @@ -0,0 +1,16 @@ +using APIBook.Model; +using Microsoft.EntityFrameworkCore; + +namespace APIBook.Repository +{ + public interface IBookRepository + { + public Task?> Get(); + public Task?> GetByName(string title); + public Task GetById(int id); + public Task Create(Book book); + public Task Update(Book book); + public Task Delete(int id); + } + +} diff --git a/APIBook/APIBook/Repository/UserRepository.cs b/APIBook/APIBook/Repository/UserRepository.cs new file mode 100644 index 00000000..1024052b --- /dev/null +++ b/APIBook/APIBook/Repository/UserRepository.cs @@ -0,0 +1,17 @@ +namespace APIBook.Repository +{ + // Simulação de um banco de dados com usuarios simples + public static class UserRepository + { + public static User Get(string username, string password) + { + var users = new List(); + // demo user e admin + users.Add(new User { ID = 0, Username = "Admin", Password = "AIAIAIAI", Role = "admin" }); + users.Add(new User { ID = 1, Username = "shadowy", Password = "123", Role = "user" }); + return users.Where(x => x.Username.ToLower() == username.ToLower() && x.Password == password).First(); + } + + } + +} diff --git a/APIBook/APIBook/Services/DataBaseMigrateService.cs b/APIBook/APIBook/Services/DataBaseMigrateService.cs new file mode 100644 index 00000000..2e53fced --- /dev/null +++ b/APIBook/APIBook/Services/DataBaseMigrateService.cs @@ -0,0 +1,20 @@ +using APIBook.Model; +using Microsoft.EntityFrameworkCore; + + +namespace APIBook.Services +{ + public static class DataBaseMigrateService + { + public static void MigrationInitialsation(this IApplicationBuilder applicationBuilder) + { + using (var service_scope = applicationBuilder.ApplicationServices.CreateScope()) + { + var service_db = service_scope.ServiceProvider.GetService(); + + if(service_db != null) + service_db.Database.Migrate(); //migrar o banco de dados caso não exista + } + } + } +} diff --git a/APIBook/APIBook/appsettings.Development.json b/APIBook/APIBook/appsettings.Development.json new file mode 100644 index 00000000..045fa358 --- /dev/null +++ b/APIBook/APIBook/appsettings.Development.json @@ -0,0 +1,15 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + + "AllowedHosts": "*", + + "ConnectionStrings": { + "DefaultConnection": "Trust Server Certificate=True; User ID=sa; Password=shadowy123;Persist Security Info=True;Initial Catalog=booksDB; Data Source=sqldata" + + } +} diff --git a/APIBook/APIBook/appsettings.json b/APIBook/APIBook/appsettings.json new file mode 100644 index 00000000..2261aee8 --- /dev/null +++ b/APIBook/APIBook/appsettings.json @@ -0,0 +1,14 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + + "AllowedHosts": "*", + + "ConnectionStrings": { + "DefaultConnection": "Trust Server Certificate=True; Password=shadowy123;Persist Security Info=True; User ID=SA;Initial Catalog=booksDB; Data Source=sqldata" + } +} diff --git a/APIBook/Dockerfile b/APIBook/Dockerfile new file mode 100644 index 00000000..a123a5b7 --- /dev/null +++ b/APIBook/Dockerfile @@ -0,0 +1,20 @@ +FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base +WORKDIR /app +EXPOSE 80 +EXPOSE 443 + +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build +WORKDIR /src +COPY ["APIBook/APIBook.csproj", "APIBook/"] +RUN dotnet restore "APIBook/APIBook.csproj" +COPY . . +WORKDIR "/src/APIBook" +RUN dotnet build "APIBook.csproj" -c Release -o app + +FROM build AS publish +RUN dotnet publish "APIBook.csproj" -c Release -o /app/publish + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "APIBook.dll"] \ No newline at end of file diff --git a/APIBook/docker-compose.dcproj b/APIBook/docker-compose.dcproj new file mode 100644 index 00000000..038e2f90 --- /dev/null +++ b/APIBook/docker-compose.dcproj @@ -0,0 +1,18 @@ + + + + 2.1 + Linux + e51ae39f-906b-43a0-b84c-87c090cbc6fb + LaunchBrowser + {Scheme}://localhost:{ServicePort}/swagger + apibook + + + + docker-compose.yml + + + + + \ No newline at end of file diff --git a/APIBook/docker-compose.override.yml b/APIBook/docker-compose.override.yml new file mode 100644 index 00000000..73614da8 --- /dev/null +++ b/APIBook/docker-compose.override.yml @@ -0,0 +1,13 @@ +version: '3.4' + +services: + apibook: + environment: + - ASPNETCORE_ENVIRONMENT=Development + - ASPNETCORE_URLS=https://+:443;http://+:80 + ports: + - "80" + - "443" + volumes: + - ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro + - ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro \ No newline at end of file diff --git a/APIBook/docker-compose.yml b/APIBook/docker-compose.yml new file mode 100644 index 00000000..237b333b --- /dev/null +++ b/APIBook/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.4' + +services: + apibook: + image: ${DOCKER_REGISTRY-}apibook + build: + context: . + dockerfile: APIBook/Dockerfile + volumes: + - .\programlog:/programlog + depends_on: + - sqldata + + sqldata: + image: mcr.microsoft.com/mssql/server:2022-latest + environment: + - ACCEPT_EULA=Y + - MSSQL_SA_PASSWORD=shadowy123 + volumes: + - .\dbo:/var/opt/mssql/data + ports: + - "1433:1433" \ No newline at end of file diff --git a/APIBook/launchSettings.json b/APIBook/launchSettings.json new file mode 100644 index 00000000..f1261dba --- /dev/null +++ b/APIBook/launchSettings.json @@ -0,0 +1,12 @@ +{ + "profiles": { + "Docker Compose": { + "commandName": "DockerCompose", + "commandVersion": "1.0", + "serviceActions": { + "apibook": "StartDebugging", + "sqldata": "StartWithoutDebugging" + } + } + } +} \ No newline at end of file