├── .gitignore ├── README.md ├── UML ├── FacturasUML.mdj └── Facturas_UML.png ├── angular └── clientes-app │ ├── .editorconfig │ ├── .gitignore │ ├── .vscode │ └── launch.json │ ├── README.md │ ├── angular.json │ ├── browserslist │ ├── e2e │ ├── protractor.conf.js │ ├── src │ │ ├── app.e2e-spec.ts │ │ └── app.po.ts │ └── tsconfig.json │ ├── karma.conf.js │ ├── package-lock.json │ ├── package.json │ ├── src │ ├── app │ │ ├── app-routing.module.ts │ │ ├── app.component.css │ │ ├── app.component.html │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── clientes │ │ │ ├── cliente.service.ts │ │ │ ├── cliente.ts │ │ │ ├── clientes.component.html │ │ │ ├── clientes.component.ts │ │ │ ├── clientes.json.ts │ │ │ ├── detalle │ │ │ │ ├── detalle.component.css │ │ │ │ ├── detalle.component.html │ │ │ │ ├── detalle.component.ts │ │ │ │ └── modal.service.ts │ │ │ ├── form.component.html │ │ │ ├── form.component.ts │ │ │ └── region.ts │ │ ├── config │ │ │ └── config.ts │ │ ├── facturas │ │ │ ├── detalle-factura.component.html │ │ │ ├── detalle-factura.component.ts │ │ │ ├── facturas.component.html │ │ │ ├── facturas.component.ts │ │ │ ├── models │ │ │ │ ├── factura.ts │ │ │ │ ├── item-factura.ts │ │ │ │ └── producto.ts │ │ │ └── services │ │ │ │ └── factura.service.ts │ │ ├── footer │ │ │ ├── footer.component.css │ │ │ ├── footer.component.html │ │ │ └── footer.component.ts │ │ ├── header │ │ │ ├── header.component.css │ │ │ ├── header.component.html │ │ │ └── header.component.ts │ │ ├── paginator │ │ │ ├── paginator.component.html │ │ │ └── paginator.component.ts │ │ └── usuarios │ │ │ ├── auth.service.ts │ │ │ ├── guards │ │ │ ├── auth.guard.ts │ │ │ └── role.guard.ts │ │ │ ├── interceptors │ │ │ ├── auth.interceptor.ts │ │ │ └── token.interceptor.ts │ │ │ ├── login.component.html │ │ │ ├── login.component.ts │ │ │ └── usuario.ts │ ├── assets │ │ └── .gitkeep │ ├── environments │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── favicon.ico │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ ├── styles.css │ └── test.ts │ ├── tsconfig.app.json │ ├── tsconfig.json │ ├── tsconfig.spec.json │ └── tslint.json ├── postman-collection ├── Local.postman_environment.json └── RestApiSpringBoot.postman_collection.json ├── spring-boot-apirest ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── ecristobale │ │ │ └── spring │ │ │ └── boot │ │ │ └── apirest │ │ │ ├── SpringBootApirestApplication.java │ │ │ ├── auth │ │ │ ├── AuthorizationServerConfig.java │ │ │ ├── JwtConfig.java │ │ │ ├── ResourceServerConfig.java │ │ │ ├── SpringSecurityConfig.java │ │ │ └── TokenAditionalInfo.java │ │ │ ├── controllers │ │ │ ├── ClienteRestController.java │ │ │ └── FacturaRestController.java │ │ │ └── models │ │ │ ├── dao │ │ │ ├── IClienteDao.java │ │ │ ├── IFacturaDao.java │ │ │ ├── IImgPerfilDao.java │ │ │ ├── IProductoDao.java │ │ │ └── IUsuarioDao.java │ │ │ ├── entity │ │ │ ├── Cliente.java │ │ │ ├── Factura.java │ │ │ ├── ImgPerfil.java │ │ │ ├── ItemFactura.java │ │ │ ├── Producto.java │ │ │ ├── Region.java │ │ │ ├── RegionName.java │ │ │ ├── Role.java │ │ │ └── Usuario.java │ │ │ └── services │ │ │ ├── ClienteServiceImpl.java │ │ │ ├── IClienteService.java │ │ │ ├── IUploadFileService.java │ │ │ ├── IUsuarioService.java │ │ │ ├── UploadFileServiceImpl.java │ │ │ └── UsuarioService.java │ └── resources │ │ ├── application.properties │ │ ├── data.sql │ │ ├── schema.sql │ │ └── static │ │ └── images │ │ └── not-photo.png │ └── test │ └── java │ └── com │ └── ecristobale │ └── spring │ └── boot │ └── apirest │ └── SpringBootApirestApplicationTests.java └── web-app-screenshots ├── Logout_action.PNG ├── admin_client_details.PNG ├── admin_client_photo_uploaded_with_progress_bar.PNG ├── admin_form_new_invoice_validating_fields_autocomplete_product.PNG ├── admin_main_page.PNG ├── area_restrictions_based_on_roles.PNG ├── create_new_user_form_validation.PNG ├── invoice_detail.PNG ├── login_page.PNG ├── main_page.PNG ├── update_user_form.PNG ├── user_client_details.PNG ├── user_invoice_detail.PNG └── user_main_page.PNG /.gitignore: -------------------------------------------------------------------------------- 1 | angular/clientes-app/node_modules/ 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # web-app-full-stack: Spring Boot 2 & Angular 8 2 | ## Links for visiting webapp: 3 | - Google Firebase: https://clientes-app-ecristobale.web.app/clientes 4 | - Heroku (backend only): https://spring-boot-2clientes-app.herokuapp.com/ 5 | 6 | Main page without login: 7 | ![Alt text](web-app-screenshots/main_page.PNG?raw=true "Main Page") 8 | 9 | Some warnings indicating that the requested pages are in a restricted area: 10 | ![Alt text](web-app-screenshots/area_restrictions_based_on_roles.PNG?raw=true "Main Page") 11 | 12 | Login screen (ask me if you want me to share with you any user to see the whole application): 13 | ![Alt text](web-app-screenshots/login_page.PNG?raw=true "Login Page") 14 | 15 | Main page with admin role: 16 | ![Alt text](web-app-screenshots/admin_main_page.PNG?raw=true "Main Page - Admin") 17 | 18 | Main page with user role: 19 | ![Alt text](web-app-screenshots/user_main_page.PNG?raw=true "Main Page - User") 20 | 21 | Create new client with admin role (with form validation): 22 | ![Alt text](web-app-screenshots/create_new_user_form_validation.PNG?raw=true "New Client Page - Admin") 23 | 24 | Update client with admin role (with form validation): 25 | ![Alt text](web-app-screenshots/update_user_form.PNG?raw=true "Update Client Page - Admin") 26 | 27 | Create new invoice with admin role (with form validation and autocomplete in product name): 28 | ![Alt text](web-app-screenshots/admin_form_new_invoice_validating_fields_autocomplete_product.PNG?raw=true "New Invoice Page - Admin") 29 | 30 | Client details with admin role: 31 | ![Alt text](web-app-screenshots/admin_client_details.PNG?raw=true "Client Details Page - Admin") 32 | 33 | Client details upload an image (with progress bar animation) with admin role: 34 | ![Alt text](web-app-screenshots/admin_client_photo_uploaded_with_progress_bar.PNG?raw=true "Client Details Upload An Image Page - Admin") 35 | 36 | Client details with user role: 37 | ![Alt text](web-app-screenshots/user_client_details.PNG?raw=true "Client Details Page - User") 38 | 39 | Invoice details with admin role: 40 | ![Alt text](web-app-screenshots/invoice_detail.PNG?raw=true "Invoice Details Page - Admin") 41 | 42 | Invoice details with user role: 43 | ![Alt text](web-app-screenshots/user_invoice_detail.PNG?raw=true "Invoice Details Page - Admin") 44 | 45 | Logout action: 46 | ![Alt text](web-app-screenshots/Logout_action.PNG?raw=true "Logout Page") 47 | -------------------------------------------------------------------------------- /UML/Facturas_UML.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/UML/Facturas_UML.png -------------------------------------------------------------------------------- /angular/clientes-app/.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /angular/clientes-app/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | # Only exists if Bazel was run 8 | /bazel-out 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events*.json 15 | speed-measure-plugin*.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | testem.log 42 | /typings 43 | 44 | # System Files 45 | .DS_Store 46 | Thumbs.db 47 | -------------------------------------------------------------------------------- /angular/clientes-app/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "chrome", 9 | "request": "launch", 10 | "name": "Launch Chrome against localhost", 11 | "url": "http://localhost:4200", 12 | "webRoot": "${workspaceFolder}" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /angular/clientes-app/README.md: -------------------------------------------------------------------------------- 1 | # ClientesApp 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.3.23. 4 | 5 | ## Development server 6 | 7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 8 | 9 | ## Code scaffolding 10 | 11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 12 | 13 | ## Build 14 | 15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. 16 | 17 | ## Running unit tests 18 | 19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 20 | 21 | ## Running end-to-end tests 22 | 23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 24 | 25 | ## Further help 26 | 27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 28 | -------------------------------------------------------------------------------- /angular/clientes-app/angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "clientes-app": { 7 | "projectType": "application", 8 | "schematics": {}, 9 | "root": "", 10 | "sourceRoot": "src", 11 | "prefix": "app", 12 | "architect": { 13 | "build": { 14 | "builder": "@angular-devkit/build-angular:browser", 15 | "options": { 16 | "outputPath": "dist/clientes-app", 17 | "index": "src/index.html", 18 | "main": "src/main.ts", 19 | "polyfills": "src/polyfills.ts", 20 | "tsConfig": "tsconfig.app.json", 21 | "aot": false, 22 | "assets": [ 23 | "src/favicon.ico", 24 | "src/assets" 25 | ], 26 | "styles": [ 27 | "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", 28 | "node_modules/bootstrap/dist/css/bootstrap.min.css", 29 | "src/styles.css" 30 | ], 31 | "scripts": [ 32 | "node_modules/jquery/dist/jquery.min.js", 33 | "node_modules/bootstrap/dist/js/bootstrap.min.js" 34 | ] 35 | }, 36 | "configurations": { 37 | "production": { 38 | "fileReplacements": [ 39 | { 40 | "replace": "src/environments/environment.ts", 41 | "with": "src/environments/environment.prod.ts" 42 | } 43 | ], 44 | "optimization": true, 45 | "outputHashing": "all", 46 | "sourceMap": false, 47 | "extractCss": true, 48 | "namedChunks": false, 49 | "aot": true, 50 | "extractLicenses": true, 51 | "vendorChunk": false, 52 | "buildOptimizer": true, 53 | "budgets": [ 54 | { 55 | "type": "initial", 56 | "maximumWarning": "2mb", 57 | "maximumError": "5mb" 58 | }, 59 | { 60 | "type": "anyComponentStyle", 61 | "maximumWarning": "6kb", 62 | "maximumError": "10kb" 63 | } 64 | ] 65 | } 66 | } 67 | }, 68 | "serve": { 69 | "builder": "@angular-devkit/build-angular:dev-server", 70 | "options": { 71 | "browserTarget": "clientes-app:build" 72 | }, 73 | "configurations": { 74 | "production": { 75 | "browserTarget": "clientes-app:build:production" 76 | } 77 | } 78 | }, 79 | "extract-i18n": { 80 | "builder": "@angular-devkit/build-angular:extract-i18n", 81 | "options": { 82 | "browserTarget": "clientes-app:build" 83 | } 84 | }, 85 | "test": { 86 | "builder": "@angular-devkit/build-angular:karma", 87 | "options": { 88 | "main": "src/test.ts", 89 | "polyfills": "src/polyfills.ts", 90 | "tsConfig": "tsconfig.spec.json", 91 | "karmaConfig": "karma.conf.js", 92 | "assets": [ 93 | "src/favicon.ico", 94 | "src/assets" 95 | ], 96 | "styles": [ 97 | "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", 98 | "src/styles.css" 99 | ], 100 | "scripts": [] 101 | } 102 | }, 103 | "lint": { 104 | "builder": "@angular-devkit/build-angular:tslint", 105 | "options": { 106 | "tsConfig": [ 107 | "tsconfig.app.json", 108 | "tsconfig.spec.json", 109 | "e2e/tsconfig.json" 110 | ], 111 | "exclude": [ 112 | "**/node_modules/**" 113 | ] 114 | } 115 | }, 116 | "e2e": { 117 | "builder": "@angular-devkit/build-angular:protractor", 118 | "options": { 119 | "protractorConfig": "e2e/protractor.conf.js", 120 | "devServerTarget": "clientes-app:serve" 121 | }, 122 | "configurations": { 123 | "production": { 124 | "devServerTarget": "clientes-app:serve:production" 125 | } 126 | } 127 | } 128 | } 129 | } 130 | }, 131 | "defaultProject": "clientes-app" 132 | } -------------------------------------------------------------------------------- /angular/clientes-app/browserslist: -------------------------------------------------------------------------------- 1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | 5 | # You can see what browsers were selected by your queries by running: 6 | # npx browserslist 7 | 8 | > 0.5% 9 | last 2 versions 10 | Firefox ESR 11 | not dead 12 | not IE 9-11 # For IE 9-11 support, remove 'not'. -------------------------------------------------------------------------------- /angular/clientes-app/e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | // Protractor configuration file, see link for more information 3 | // https://github.com/angular/protractor/blob/master/lib/config.ts 4 | 5 | const { SpecReporter } = require('jasmine-spec-reporter'); 6 | 7 | /** 8 | * @type { import("protractor").Config } 9 | */ 10 | exports.config = { 11 | allScriptsTimeout: 11000, 12 | specs: [ 13 | './src/**/*.e2e-spec.ts' 14 | ], 15 | capabilities: { 16 | browserName: 'chrome' 17 | }, 18 | directConnect: true, 19 | baseUrl: 'http://localhost:4200/', 20 | framework: 'jasmine', 21 | jasmineNodeOpts: { 22 | showColors: true, 23 | defaultTimeoutInterval: 30000, 24 | print: function() {} 25 | }, 26 | onPrepare() { 27 | require('ts-node').register({ 28 | project: require('path').join(__dirname, './tsconfig.json') 29 | }); 30 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 31 | } 32 | }; -------------------------------------------------------------------------------- /angular/clientes-app/e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', () => { 12 | page.navigateTo(); 13 | expect(page.getTitleText()).toEqual('clientes-app app is running!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /angular/clientes-app/e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText() { 9 | return element(by.css('app-root .content span')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /angular/clientes-app/e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /angular/clientes-app/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, './coverage/clientes-app'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false, 30 | restartOnFileChange: true 31 | }); 32 | }; 33 | -------------------------------------------------------------------------------- /angular/clientes-app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "clientes-app", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "~8.2.14", 15 | "@angular/cdk": "~8.2.3", 16 | "@angular/common": "~8.2.14", 17 | "@angular/compiler": "~8.2.14", 18 | "@angular/core": "~8.2.14", 19 | "@angular/forms": "~8.2.14", 20 | "@angular/material": "^8.2.3", 21 | "@angular/material-moment-adapter": "^9.1.1", 22 | "@angular/platform-browser": "~8.2.14", 23 | "@angular/platform-browser-dynamic": "~8.2.14", 24 | "@angular/router": "~8.2.14", 25 | "bootstrap": "^4.4.1", 26 | "jquery": "^3.4.1", 27 | "moment": "^2.24.0", 28 | "popper.js": "^1.16.1", 29 | "rxjs": "~6.4.0", 30 | "sweetalert2": "^9.7.0", 31 | "tslib": "^1.10.0", 32 | "zone.js": "~0.9.1" 33 | }, 34 | "devDependencies": { 35 | "@angular-devkit/build-angular": "~0.803.23", 36 | "@angular/cli": "~8.3.23", 37 | "@angular/compiler-cli": "~8.2.14", 38 | "@angular/language-service": "~8.2.14", 39 | "@types/node": "~8.9.4", 40 | "@types/jasmine": "~3.3.8", 41 | "@types/jasminewd2": "~2.0.3", 42 | "codelyzer": "^5.0.0", 43 | "jasmine-core": "~3.4.0", 44 | "jasmine-spec-reporter": "~4.2.1", 45 | "karma": "~4.1.0", 46 | "karma-chrome-launcher": "~2.2.0", 47 | "karma-coverage-istanbul-reporter": "~2.0.1", 48 | "karma-jasmine": "~2.0.1", 49 | "karma-jasmine-html-reporter": "^1.4.0", 50 | "protractor": "~5.4.0", 51 | "ts-node": "~7.0.0", 52 | "tslint": "~5.15.0", 53 | "typescript": "~3.5.3" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | import { ClientesComponent } from './clientes/clientes.component'; 4 | import { FormComponent } from './clientes/form.component'; 5 | import { DetalleComponent } from './clientes/detalle/detalle.component'; 6 | import { LoginComponent } from './usuarios/login.component'; 7 | import { AuthGuard } from './usuarios/guards/auth.guard'; 8 | import { RoleGuard } from './usuarios/guards/role.guard'; 9 | import { DetalleFacturaComponent } from './facturas/detalle-factura.component'; 10 | import { FacturasComponent } from './facturas/facturas.component'; 11 | 12 | const routes: Routes = [ 13 | { path: '', redirectTo: '/clientes', pathMatch: 'full' }, 14 | { path: 'clientes', component: ClientesComponent }, 15 | { path: 'clientes/page/:page', component: ClientesComponent }, 16 | { path: 'clientes/form', component: FormComponent, canActivate: [AuthGuard, RoleGuard], data: {role: 'ROLE_ADMIN'} }, 17 | { path: 'clientes/form/:id', component: FormComponent, canActivate: [AuthGuard, RoleGuard], data: {role: 'ROLE_ADMIN'} }, 18 | { path: 'login', component: LoginComponent }, 19 | { path: 'facturas/:id', component: DetalleFacturaComponent, canActivate: [AuthGuard, RoleGuard], data: {role: 'ROLE_USER'} }, 20 | { path: 'facturas/form/:clienteId', component: FacturasComponent, canActivate: [AuthGuard, RoleGuard], data: {role: 'ROLE_ADMIN'} } 21 | ]; 22 | 23 | @NgModule({ 24 | imports: [RouterModule.forRoot(routes)], 25 | exports: [RouterModule] 26 | }) 27 | export class AppRoutingModule { } 28 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/app.component.css: -------------------------------------------------------------------------------- 1 | .mb-7 { 2 | margin-bottom: 6rem !important; 3 | } 4 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
6 | 7 | 8 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-root', 5 | templateUrl: './app.component.html', 6 | styleUrls: ['./app.component.css'] 7 | }) 8 | export class AppComponent { 9 | title = 'clientes-app'; 10 | 11 | inicio = 'Empezamos!!'; 12 | } 13 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule, LOCALE_ID } from '@angular/core'; 3 | 4 | import { AppComponent } from './app.component'; 5 | import { HeaderComponent } from './header/header.component'; 6 | import { FooterComponent } from './footer/footer.component'; 7 | import { ClientesComponent } from './clientes/clientes.component'; 8 | import { FormComponent } from './clientes/form.component'; 9 | import { PaginatorComponent } from './paginator/paginator.component'; 10 | 11 | import { AppRoutingModule } from './app-routing.module'; 12 | import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 13 | import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 14 | import {MatAutocompleteModule} from '@angular/material/autocomplete'; 15 | import {MatInputModule} from '@angular/material/input'; 16 | import {MatFormFieldModule} from '@angular/material/form-field'; 17 | 18 | import localeES from '@angular/common/locales/es'; 19 | import { registerLocaleData } from '@angular/common'; 20 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 21 | import { MatDatepickerModule } from '@angular/material'; 22 | import { MatMomentDateModule } from '@angular/material-moment-adapter'; 23 | import { DetalleComponent } from './clientes/detalle/detalle.component'; 24 | import { LoginComponent } from './usuarios/login.component'; 25 | import { TokenInterceptor } from './usuarios/interceptors/token.interceptor'; 26 | import { AuthInterceptor } from './usuarios/interceptors/auth.interceptor'; 27 | import { DetalleFacturaComponent } from './facturas/detalle-factura.component'; 28 | import { FacturasComponent } from './facturas/facturas.component'; 29 | 30 | registerLocaleData(localeES, 'es'); 31 | 32 | @NgModule({ 33 | declarations: [ 34 | AppComponent, 35 | HeaderComponent, 36 | FooterComponent, 37 | ClientesComponent, 38 | FormComponent, 39 | PaginatorComponent, 40 | DetalleComponent, 41 | LoginComponent, 42 | DetalleFacturaComponent, 43 | FacturasComponent 44 | ], 45 | imports: [ 46 | BrowserModule, 47 | AppRoutingModule, 48 | HttpClientModule, 49 | FormsModule, 50 | BrowserAnimationsModule, 51 | MatDatepickerModule, 52 | MatMomentDateModule, 53 | ReactiveFormsModule, MatAutocompleteModule, MatInputModule, MatFormFieldModule 54 | ], 55 | providers: [{provide: LOCALE_ID, useValue: 'es'}, 56 | { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }, 57 | { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }], 58 | bootstrap: [AppComponent] 59 | }) 60 | export class AppModule { } 61 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/clientes/cliente.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable, of, throwError } from 'rxjs'; 3 | import { map, catchError, tap } from 'rxjs/operators'; 4 | import { formatDate, DatePipe } from '@angular/common'; 5 | 6 | import { CLIENTES } from './clientes.json'; 7 | import { Cliente } from './cliente.js'; 8 | import { HttpClient, HttpRequest, HttpEvent } from '@angular/common/http'; 9 | import { Router } from '@angular/router'; 10 | import { Region } from './region'; 11 | 12 | import { URL_BACKEND } from 'src/app/config/config'; 13 | 14 | @Injectable({ 15 | providedIn: 'root' 16 | }) 17 | export class ClienteService { 18 | urlEndPoint = URL_BACKEND + '/api/clientes'; 19 | 20 | constructor(private http: HttpClient, 21 | private router: Router) { } 22 | 23 | getRegiones(): Observable { 24 | return this.http.get(this.urlEndPoint + '/regiones'); 25 | } 26 | 27 | getClientes(page: number): Observable { 28 | /* CLIENTES converted as stream by using of 29 | return of(CLIENTES); */ 30 | return this.http.get(this.urlEndPoint + '/page/' + page).pipe( 31 | tap( (response: any) => { 32 | console.log('tap 1'); 33 | (response.content as Cliente[]).forEach(cliente => { 34 | console.log(cliente.nombre); 35 | }); 36 | }), 37 | map( (response: any) => { 38 | (response.content as Cliente[]).map(cliente => { 39 | cliente.nombre = cliente.nombre.toUpperCase(); 40 | // let datePipe = new DatePipe('es'); 41 | // cliente.createdAt = datePipe.transform(cliente.createdAt, 'EEEE dd, MMMM yyyy'); 42 | // cliente.createdAt = formatDate(cliente.createdAt, 'dd-MM-yyyy', 'en_US'); 43 | return cliente; 44 | }); 45 | return response; 46 | }), 47 | tap(response => { 48 | console.log('tap 2'); 49 | (response.content as Cliente[]).forEach(cliente => { 50 | console.log(cliente.nombre); 51 | }); 52 | }) 53 | ); 54 | } 55 | 56 | create(cliente: Cliente): Observable { 57 | return this.http.post(this.urlEndPoint, cliente).pipe( 58 | map( (jsonResponse: any) => jsonResponse.cliente as Cliente), 59 | catchError(e => { 60 | if (e.status === 400) { 61 | return throwError(e); 62 | } 63 | if (e.error.mensaje) { 64 | console.error(e.error.mensaje); 65 | } 66 | return throwError(e); 67 | }) 68 | ); 69 | } 70 | 71 | getCliente(id: number): Observable { 72 | return this.http.get(`${this.urlEndPoint}/${id}`).pipe( 73 | catchError(e => { 74 | if (e.status != 401 && e.error.mensaje) { 75 | this.router.navigate(['./clientes']); 76 | console.error(e.error.mensaje); 77 | } 78 | return throwError(e); 79 | }) 80 | ); 81 | } 82 | 83 | update(cliente: Cliente): Observable { 84 | return this.http.put(`${this.urlEndPoint}/${cliente.id}`, cliente).pipe( 85 | catchError(e => { 86 | if ( e.status === 400) { 87 | return throwError(e); 88 | } 89 | if (e.error.mensaje) { 90 | console.error(e.error.mensaje); 91 | } 92 | return throwError(e); 93 | }) 94 | ); 95 | } 96 | 97 | delete(id: number): Observable { 98 | return this.http.delete(`${this.urlEndPoint}/${id}`).pipe( 99 | catchError(e => { 100 | if (e.error.mensaje) { 101 | console.error(e.error.mensaje); 102 | } 103 | return throwError(e); 104 | }) 105 | ); 106 | } 107 | 108 | uploadPhoto(photo: File, id): Observable> { 109 | let formData = new FormData(); 110 | formData.append('file', photo); 111 | formData.append('id', id); 112 | 113 | const req = new HttpRequest('POST', `${this.urlEndPoint}/upload`, formData, { 114 | reportProgress: true 115 | }); 116 | 117 | return this.http.request(req); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/clientes/cliente.ts: -------------------------------------------------------------------------------- 1 | import { Region } from './region'; 2 | import { Factura } from '../facturas/models/factura'; 3 | 4 | export class Cliente { 5 | id: number; 6 | nombre: string; 7 | apellido: string; 8 | createdAt: string; 9 | email: string; 10 | photo: string; 11 | region: Region; 12 | facturas: Array = []; 13 | } 14 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/clientes/clientes.component.html: -------------------------------------------------------------------------------- 1 | 2 |
3 |
Clientes
4 |
5 |
Listado de clientes
6 | 7 |
8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 31 | 32 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 46 | 49 | 50 | 51 |
#nombreapellidoemailfechacrear facturaeditareliminar
{{cliente.photo}} 28 | No photo 30 | {{cliente.photo}} 34 | No photo 36 | {{ cliente.nombre }}{{ cliente.apellido | uppercase }}{{ cliente.email }}{{ cliente.createdAt | date:"EEEE dd, MMMM yyyy" }} 44 | 45 | 47 | 48 |
52 | 53 |
54 | No hay registros en la base de datos. 55 |
56 |
57 |
58 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/clientes/clientes.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Cliente } from './cliente'; 3 | import { ClienteService } from './cliente.service'; 4 | import swal from 'sweetalert2'; 5 | import { tap } from 'rxjs/operators'; 6 | import { ActivatedRoute } from '@angular/router'; 7 | import { ModalService } from './detalle/modal.service'; 8 | import { AuthService } from '../usuarios/auth.service'; 9 | 10 | import { URL_BACKEND } from 'src/app/config/config'; 11 | 12 | @Component({ 13 | selector: 'app-clientes', 14 | templateUrl: './clientes.component.html' 15 | }) 16 | export class ClientesComponent implements OnInit { 17 | 18 | clientes: Cliente[]; 19 | paginator: any; 20 | selectedClient: Cliente; 21 | urlBackend: string = URL_BACKEND; 22 | 23 | constructor(private clienteService: ClienteService, 24 | private activatedRoute: ActivatedRoute, 25 | private modalService: ModalService, 26 | private authService: AuthService) { } 27 | 28 | ngOnInit() { 29 | this.activatedRoute.paramMap.subscribe( params => { 30 | let page: number = +params.get('page'); 31 | if (!page) { 32 | page = 0; 33 | } 34 | this.clienteService.getClientes(page).pipe( 35 | tap(response => { 36 | console.log('tap 3 - Cliente Component'); 37 | (response.content as Cliente[]).forEach(cliente => { 38 | console.log(cliente.nombre); 39 | }); 40 | }) 41 | ).subscribe(response => { 42 | this.clientes = response.content as Cliente[]; 43 | this.paginator = response; 44 | }); 45 | }); 46 | this.modalService.notifyUpload.subscribe( clienteUpdated => { 47 | this.clientes = this.clientes.map(cliente => { 48 | if (cliente.id === clienteUpdated.id) { 49 | cliente.photo = clienteUpdated.photo; 50 | } 51 | return cliente; 52 | }); 53 | } 54 | ); 55 | } 56 | 57 | delete(cliente: Cliente): void { 58 | swal.fire({ 59 | title: 'Estás seguro?', 60 | text: `El cliente ${cliente.nombre} ${cliente.apellido} se eliminará definitivamente`, 61 | icon: 'warning', 62 | showCancelButton: true, 63 | confirmButtonColor: '#28a745', 64 | cancelButtonColor: '#d33', 65 | confirmButtonText: 'Sí, eliminar', 66 | cancelButtonText: 'No, cancelar' 67 | }).then((result) => { 68 | if (result.value) { 69 | this.clienteService.delete(cliente.id).subscribe( 70 | response => { 71 | this.clientes = this.clientes.filter(cli => cli !== cliente); 72 | swal.fire('Cliente eliminado', `Cliente ${cliente.nombre} eliminado con éxito`, 'success'); 73 | } 74 | ); 75 | } 76 | }); 77 | } 78 | 79 | openModal(cliente: Cliente) { 80 | this.selectedClient = cliente; 81 | this.modalService.openModal(); 82 | } 83 | 84 | signInMessage() { 85 | swal.fire('Área restringida', 'Por favor, inicia sesión para ver los detalles', 'warning'); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/clientes/clientes.json.ts: -------------------------------------------------------------------------------- 1 | import { Cliente } from './cliente'; 2 | 3 | export const CLIENTES: Cliente[] = [ 4 | {id: 1, nombre: 'John', apellido: 'Doe', email: 'johndoe@johndoe.es', createdAt: '16-12-2019', photo: 'photo.png', region: {id: 3, name: 'Europe'}, facturas: []}, 5 | {id: 2, nombre: 'Mary', apellido: 'Doe', email: 'mary@johndoe.es', createdAt: '16-12-2019', photo: 'photo.png', region: {id: 3, name: 'Europe'}, facturas: []}, 6 | {id: 3, nombre: 'Edward', apellido: 'Doe', email: 'edward@johndoe.es', createdAt: '16-12-2019', photo: 'photo.png', region: {id: 3, name: 'Europe'}, facturas: []}, 7 | {id: 4, nombre: 'George', apellido: 'Doe', email: 'george@johndoe.es', createdAt: '16-12-2019', photo: 'photo.png', region: {id: 3, name: 'Europe'}, facturas: []}, 8 | {id: 5, nombre: 'Alex', apellido: 'Doe', email: 'alex@johndoe.es', createdAt: '16-12-2019', photo: 'photo.png', region: {id: 3, name: 'Europe'}, facturas: []}/*, 9 | {id: 6, nombre: 'Mad', apellido: 'Doe', email: 'mad@johndoe.es', createdAt: '16-12-2019'}, 10 | {id: 7, nombre: 'Matt', apellido: 'Doe', email: 'matt@johndoe.es', createdAt: '16-12-2019'}, 11 | {id: 8, nombre: 'Tristana', apellido: 'Doe', email: 'trist@johndoe.es', createdAt: '16-12-2019'}, 12 | {id: 9, nombre: 'Harry', apellido: 'Doe', email: 'harr@johndoe.es', createdAt: '16-12-2019'}, 13 | {id: 10, nombre: 'William', apellido: 'Doe', email: 'wil@johndoe.es', createdAt: '16-12-2019'}*/ 14 | ]; 15 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/clientes/detalle/detalle.component.css: -------------------------------------------------------------------------------- 1 | .open-modal{ 2 | background-color: rgba(0, 0, 0, 0.7); 3 | position: fixed; 4 | top: 0px; 5 | left: 0px; 6 | width: 100%; 7 | height: 100%; 8 | z-index: 1040; 9 | } 10 | 11 | .animation{ 12 | animation-duration: 2s; 13 | animation-fill-mode: both; 14 | -webkit-animation-duration: 2s; 15 | -webkit-animation-fill-mode: both; 16 | } 17 | 18 | .fadeIn{ 19 | animation-name: fadeIn; 20 | -webkit-animation-name: fadeIn; 21 | } 22 | 23 | @keyframes fadeIn{0% {opacity: 0;} to {opacity: 1;}} 24 | @-webkit-keyframes fadeIn{0% {opacity: 0;} to {opacity: 1;}} -------------------------------------------------------------------------------- /angular/clientes-app/src/app/clientes/detalle/detalle.component.html: -------------------------------------------------------------------------------- 1 |
2 | 88 |
89 | 90 | 91 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/clientes/detalle/detalle.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, Input } from '@angular/core'; 2 | import { Cliente } from '../cliente'; 3 | import { ClienteService } from '../cliente.service'; 4 | import swal from 'sweetalert2'; 5 | import { HttpEventType } from '@angular/common/http'; 6 | import { ModalService } from './modal.service'; 7 | import { AuthService } from 'src/app/usuarios/auth.service'; 8 | import { FacturaService } from 'src/app/facturas/services/factura.service'; 9 | import { Factura } from 'src/app/facturas/models/factura'; 10 | 11 | import { URL_BACKEND } from 'src/app/config/config'; 12 | 13 | @Component({ 14 | selector: 'detalle-cliente', 15 | templateUrl: './detalle.component.html', 16 | styleUrls: ['./detalle.component.css'] 17 | }) 18 | export class DetalleComponent implements OnInit { 19 | @Input() cliente: Cliente; 20 | titulo = 'Detalle del cliente'; 21 | private selectedPhoto: File; 22 | progress = 0; 23 | urlBackend: string = URL_BACKEND; 24 | 25 | constructor(private clienteService: ClienteService, 26 | private modalService: ModalService, private authService: AuthService, 27 | private facturaService: FacturaService) { } 28 | 29 | ngOnInit() {} 30 | 31 | selectPhoto(event: any) { 32 | this.selectedPhoto = event.target.files[0]; 33 | this.progress = 0; 34 | console.log(this.selectedPhoto); 35 | if (this.selectedPhoto.type.indexOf('image') < 0) { 36 | swal.fire('Error seleccionar imagen: ', 'El archivo debe ser del tipo imagen', 'error'); 37 | this.selectedPhoto = null; 38 | } 39 | } 40 | 41 | uploadPhoto() { 42 | if (!this.selectedPhoto) { 43 | swal.fire('Error Upload: ', 'Debe seleccionar una foto', 'error'); 44 | } else { 45 | this.clienteService.uploadPhoto(this.selectedPhoto, this.cliente.id).subscribe( 46 | event => { 47 | if (event.type === HttpEventType.UploadProgress) { 48 | this.progress = Math.round((event.loaded / event.total) * 100); 49 | } else if (event.type === HttpEventType.Response) { 50 | let response: any = event.body; 51 | this.cliente = response.cliente as Cliente; 52 | this.modalService.notifyUpload.emit(this.cliente); 53 | swal.fire('La foto se ha subido correctamente', response.mensaje, 'success'); 54 | } 55 | } 56 | ); 57 | } 58 | } 59 | 60 | closeModal() { 61 | this.modalService.closeModal(); 62 | this.selectedPhoto = null; 63 | this.progress = 0; 64 | } 65 | 66 | deleteInvoice(factura: Factura): void { 67 | swal.fire({ 68 | title: 'Estás seguro?', 69 | text: `La factura: ${factura.descripcion} se eliminará definitivamente`, 70 | icon: 'warning', 71 | showCancelButton: true, 72 | confirmButtonColor: '#28a745', 73 | cancelButtonColor: '#d33', 74 | confirmButtonText: 'Sí, eliminar', 75 | cancelButtonText: 'No, cancelar' 76 | }).then((result) => { 77 | if (result.value) { 78 | this.facturaService.deleteFactura(factura.id).subscribe( 79 | response => { 80 | this.cliente.facturas = this.cliente.facturas.filter(clienteFact => clienteFact !== factura); 81 | swal.fire('Factura eliminada', `Factura: ${factura.descripcion} eliminada con éxito`, 'success'); 82 | } 83 | ); 84 | } 85 | }); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/clientes/detalle/modal.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, EventEmitter } from '@angular/core'; 2 | 3 | @Injectable({ 4 | providedIn: 'root' 5 | }) 6 | export class ModalService { 7 | 8 | modal = false; 9 | private _notifyUpload = new EventEmitter(); 10 | 11 | constructor() { } 12 | 13 | get notifyUpload(): EventEmitter { 14 | return this._notifyUpload; 15 | } 16 | 17 | openModal() { 18 | this.modal = true; 19 | } 20 | 21 | closeModal() { 22 | this.modal = false; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/clientes/form.component.html: -------------------------------------------------------------------------------- 1 |
    2 |
  • 3 | {{ err }} 4 |
  • 5 |
6 |
7 |
{{ titulo }}
8 |
{{ tituloEditar }}
9 |
10 | 11 |
12 |
13 | 14 |
15 | 17 |
18 |
19 | Campo nombre requerido 20 |
21 |
22 | Campo nombre debe tener al menos 4 caracteres 23 |
24 |
25 |
26 |
27 | 28 |
29 | 30 |
31 | 33 |
34 |
35 | Campo apellido requerido 36 |
37 |
38 |
39 |
40 | 41 |
42 | 43 |
44 | 46 |
47 |
48 | Campo email requerido 49 |
50 |
51 | Campo email debe tener un formato válido 52 |
53 |
54 |
55 |
56 | 57 |
58 | 59 |
60 | 61 | 62 | 63 |
64 |
65 | 66 |
67 | 68 |
69 | 73 |
74 |
75 | 76 |
77 |
78 | 80 | 81 | 83 | 84 |
85 |
86 |
87 | 88 |
89 |
-------------------------------------------------------------------------------- /angular/clientes-app/src/app/clientes/form.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Cliente } from './cliente'; 3 | import { ClienteService } from './cliente.service'; 4 | import { Router, ActivatedRoute } from '@angular/router'; 5 | import swal from 'sweetalert2'; 6 | import { Region } from './region'; 7 | 8 | @Component({ 9 | selector: 'app-form', 10 | templateUrl: './form.component.html' 11 | }) 12 | export class FormComponent implements OnInit { 13 | private cliente: Cliente = new Cliente(); 14 | private titulo = 'Crear cliente'; 15 | private tituloEditar = 'Editar cliente'; 16 | regiones: Region[]; 17 | 18 | private errores: string[]; 19 | 20 | constructor(private clienteService: ClienteService, 21 | private router: Router, 22 | private activatedRoute: ActivatedRoute) { } 23 | 24 | ngOnInit() { 25 | this.loadCliente(); 26 | this.clienteService.getRegiones().subscribe( regiones => this.regiones = regiones ); 27 | } 28 | 29 | create(): void { 30 | this.clienteService.create(this.cliente).subscribe( 31 | cliente => { 32 | this.router.navigate(['/clientes']); 33 | swal.fire('Nuevo cliente', `Cliente ${cliente.nombre} creado con éxito`, 'success'); 34 | }, 35 | err => { 36 | this.errores = err.error.errors as string[]; 37 | console.error('Código del error desde el backend: ' + err.status); 38 | console.error(err.error.errors); 39 | } 40 | ); 41 | } 42 | 43 | loadCliente(): void { 44 | this.activatedRoute.params.subscribe( params => { 45 | const id = params.id; 46 | if (id) { 47 | this.clienteService.getCliente(id).subscribe( cliente => this.cliente = cliente); 48 | } 49 | }); 50 | } 51 | 52 | update(): void { 53 | this.cliente.facturas = null; 54 | this.clienteService.update(this.cliente).subscribe( 55 | jsonResponse => { 56 | this.router.navigate(['/clientes']); 57 | swal.fire('Cliente actualizado', `${jsonResponse.mensaje}: ${jsonResponse.cliente.nombre}`, 'success'); 58 | }, 59 | err => { 60 | this.errores = err.error.errors as string[]; 61 | console.error('Código del error desde el backend: ' + err.status); 62 | console.error(err.error.errors); 63 | } 64 | ); 65 | } 66 | 67 | compareRegion(o1: Region, o2: Region): boolean { 68 | if (o1 === undefined && o2 === undefined ) { 69 | return true; 70 | } 71 | 72 | return o1 === null || o2 === null || o1 === undefined || o2 === undefined ? false : o1.id === o2.id; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/clientes/region.ts: -------------------------------------------------------------------------------- 1 | export class Region { 2 | id: number; 3 | name: string; 4 | } 5 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/config/config.ts: -------------------------------------------------------------------------------- 1 | export const URL_BACKEND = 'https://spring-boot-2clientes-app.herokuapp.com'; 2 | //export const URL_BACKEND = 'http://localhost:8081'; 3 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/facturas/detalle-factura.component.html: -------------------------------------------------------------------------------- 1 |
2 |
{{titulo}}: {{factura.descripcion}}
3 |
4 |

5 | « volver 6 |

7 | 8 |
    9 |
  • Datos cliente
  • 10 |
  • {{factura.cliente.nombre}}
  • 11 |
  • {{factura.cliente.apellido}}
  • 12 |
13 | 14 |
    15 |
  • Datos de la factura
  • 16 |
  • Folio: {{factura.id}}
  • 17 |
  • Descripción: {{factura.descripcion}}
  • 18 |
  • Fecha: {{factura.createdAt}}
  • 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 |
ProductoPrecioCantidadTotal
{{item.producto.nombre}}{{item.producto.precio}}{{item.cantidad}}{{item.calcularImporte}}
39 |
40 | Total: {{factura.total}} 41 |
42 | 43 |
44 |
45 | Observaciones 46 |
47 |
48 |

{{factura.observacion}}

49 |

No tiene observación

50 |
51 |
52 |
53 |
54 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/facturas/detalle-factura.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { FacturaService } from './services/factura.service'; 3 | import { Factura } from './models/factura'; 4 | import { ActivatedRoute } from '@angular/router'; 5 | 6 | @Component({ 7 | selector: 'app-detalle-factura', 8 | templateUrl: './detalle-factura.component.html' 9 | }) 10 | export class DetalleFacturaComponent implements OnInit { 11 | factura: Factura; 12 | titulo = 'Factura'; 13 | 14 | constructor(private facturaService: FacturaService, private activatedRoute: ActivatedRoute) { } 15 | 16 | ngOnInit() { 17 | this.activatedRoute.paramMap.subscribe(params => { 18 | let id = +params.get('id'); 19 | this.facturaService.getFactura(id).subscribe(factura => this.factura = factura); 20 | }); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/facturas/facturas.component.html: -------------------------------------------------------------------------------- 1 |
2 |
{{titulo}}: {{factura.descripcion}}
3 |
4 |

5 | « volver 6 |

7 |
8 |
9 | 10 |
11 | 13 |
14 |
15 | 16 |
17 | 18 |
19 | 21 |
22 | La descripción es obligatoria 23 |
24 |
25 |
26 | 27 |
28 | 29 |
30 | 31 |
32 |
33 | 34 |
35 |
36 | 37 | 43 | 44 | 45 | {{producto.nombre}} 46 | 47 | 48 | 49 |
50 | La factura tiene que tener al menos una línea 51 |
52 |
53 |
54 | 55 |
56 | There is no lines asigned to invoice. You should add at least one. 57 |
58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 77 | 78 | 79 |
ProductoPrecioCantidadTotalEliminar
{{item.producto.nombre}}{{item.producto.precio}}{{item.importCalculation()}}
80 | 81 |
82 | Total {{factura.calculateTotal()}} 83 |
84 | 85 |
86 |
87 | 88 |
89 |
90 |
91 |
92 |
-------------------------------------------------------------------------------- /angular/clientes-app/src/app/facturas/facturas.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Factura } from './models/factura'; 3 | import { ClienteService } from '../clientes/cliente.service'; 4 | import { ActivatedRoute, Router } from '@angular/router'; 5 | import {FormControl} from '@angular/forms'; 6 | import {Observable} from 'rxjs'; 7 | import {map, flatMap} from 'rxjs/operators'; 8 | import { FacturaService } from './services/factura.service'; 9 | import { Producto } from './models/producto'; 10 | import { MatAutocompleteSelectedEvent } from '@angular/material'; 11 | import { ItemFactura } from './models/item-factura'; 12 | import swal from 'sweetalert2'; 13 | 14 | @Component({ 15 | selector: 'app-facturas', 16 | templateUrl: './facturas.component.html' 17 | }) 18 | export class FacturasComponent implements OnInit { 19 | titulo = 'Nueva Factura'; 20 | factura: Factura = new Factura(); 21 | autocompleteControl = new FormControl(); 22 | productosFiltrados: Observable; 23 | 24 | constructor(private clienteService: ClienteService, 25 | private activatedRoute: ActivatedRoute, 26 | private facturaService: FacturaService, 27 | private router: Router) { } 28 | 29 | ngOnInit() { 30 | this.activatedRoute.paramMap.subscribe(params => { 31 | let clienteId = +params.get('clienteId'); 32 | this.clienteService.getCliente(clienteId).subscribe(cliente => this.factura.cliente = cliente); 33 | }); 34 | this.productosFiltrados = this.autocompleteControl.valueChanges 35 | .pipe( 36 | map(value => typeof value === 'string' ? value : value.nombre), 37 | flatMap(value => value ? this._filter(value) : []) 38 | ); 39 | } 40 | 41 | private _filter(value: string): Observable { 42 | const filterValue = value.toLowerCase(); 43 | 44 | return this.facturaService.productFilter(filterValue); 45 | } 46 | 47 | showProductName(producto?: Producto): string | undefined { 48 | return producto ? producto.nombre : undefined; 49 | } 50 | 51 | productSelected(event: MatAutocompleteSelectedEvent): void { 52 | let producto = event.option.value as Producto; 53 | console.log(producto); 54 | 55 | if (this.itemExists(producto.id)) { 56 | this.incrementQuantity(producto.id); 57 | } else { 58 | let itemFactura = new ItemFactura(); 59 | itemFactura.producto = producto; 60 | this.factura.itemsFactura.push(itemFactura); 61 | } 62 | this.autocompleteControl.setValue(''); 63 | event.option.focus(); 64 | event.option.deselect(); 65 | } 66 | 67 | updateQuantity(id: number, event: any): void { 68 | let cantidad: number = event.target.value as number; 69 | if (cantidad == 0 || cantidad < 1) { 70 | return this.deleteItem(id); 71 | } 72 | this.factura.itemsFactura = this.factura.itemsFactura.map((item: ItemFactura) => { 73 | if (id === item.producto.id) { 74 | item.cantidad = cantidad; 75 | } 76 | return item; 77 | }); 78 | } 79 | 80 | itemExists(id: number): boolean { 81 | let exist = false; 82 | this.factura.itemsFactura.forEach((item: ItemFactura) => { 83 | if (id === item.producto.id) { 84 | exist = true; 85 | } 86 | }); 87 | return exist; 88 | } 89 | 90 | incrementQuantity(id: number) { 91 | this.factura.itemsFactura = this.factura.itemsFactura.map((item: ItemFactura) => { 92 | if (id === item.producto.id) { 93 | ++item.cantidad; 94 | } 95 | return item; 96 | }); 97 | } 98 | 99 | deleteItem(id: number): void { 100 | this.factura.itemsFactura = this.factura.itemsFactura.filter((item: ItemFactura) => item.producto.id !== id); 101 | } 102 | 103 | createFactura(facturaForm): void { 104 | console.log(this.factura); 105 | if (this.factura.itemsFactura.length == 0) { 106 | this.autocompleteControl.setErrors({ invalid: true}); 107 | } 108 | if (facturaForm.form.valid && this.factura.itemsFactura.length > 0) { 109 | this.facturaService.createFactura(this.factura).subscribe(factura => { 110 | swal.fire(this.titulo, `Factura: ${factura.descripcion} creada con éxito!`, 'success'); 111 | this.router.navigate(['/clientes']); 112 | }); 113 | } 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/facturas/models/factura.ts: -------------------------------------------------------------------------------- 1 | import { ItemFactura } from './item-factura'; 2 | import { Cliente } from 'src/app/clientes/cliente'; 3 | 4 | export class Factura { 5 | 6 | id: number; 7 | descripcion: string; 8 | observacion: string; 9 | itemsFactura: Array = []; 10 | cliente: Cliente; 11 | total: number; 12 | createdAt: string; 13 | 14 | calculateTotal(): number { 15 | this.total = 0; 16 | this.itemsFactura.forEach((item: ItemFactura) => { 17 | this.total += item.importCalculation(); 18 | }); 19 | return this.total; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/facturas/models/item-factura.ts: -------------------------------------------------------------------------------- 1 | import { Producto } from './producto'; 2 | 3 | export class ItemFactura { 4 | 5 | producto: Producto; 6 | cantidad = 1; 7 | calcularImporte: number; 8 | 9 | public importCalculation(): number { 10 | return this.cantidad * this.producto.precio; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/facturas/models/producto.ts: -------------------------------------------------------------------------------- 1 | export class Producto { 2 | 3 | id: number; 4 | nombre: string; 5 | precio: number; 6 | } 7 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/facturas/services/factura.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | import { Factura } from '../models/factura'; 5 | import { Producto } from '../models/producto'; 6 | 7 | import { URL_BACKEND } from 'src/app/config/config'; 8 | 9 | @Injectable({ 10 | providedIn: 'root' 11 | }) 12 | export class FacturaService { 13 | 14 | private urlEndpoint = URL_BACKEND + '/api/facturas'; 15 | 16 | constructor(private http: HttpClient) { } 17 | 18 | getFactura(id: number): Observable { 19 | return this.http.get(`${this.urlEndpoint}/${id}`); 20 | } 21 | 22 | deleteFactura(id: number): Observable { 23 | return this.http.delete(`${this.urlEndpoint}/${id}`); 24 | } 25 | 26 | productFilter(term: string): Observable { 27 | return this.http.get(`${this.urlEndpoint}/product-filter/${term}`); 28 | } 29 | 30 | createFactura(factura: Factura): Observable { 31 | return this.http.post(this.urlEndpoint, factura); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/footer/footer.component.css: -------------------------------------------------------------------------------- 1 | hr { 2 | border-top: 0.5px solid white; 3 | } 4 | 5 | /* footer social icons */ 6 | 7 | ul.social-network { 8 | list-style: none; 9 | justify-content: center; 10 | display: flex; 11 | margin-left: 0 !important; 12 | padding: 0; 13 | } 14 | 15 | ul.social-network li { 16 | display: inline; 17 | margin: 0 5px; 18 | } 19 | 20 | .social-network a.icoGithub:hover { 21 | background-color: #F39C12; 22 | } 23 | 24 | .social-network a.icoLinkedin:hover { 25 | background-color: #007bb7; 26 | } 27 | 28 | .social-network a.icoEmail:hover { 29 | background-color: #27AE60; 30 | } 31 | 32 | .social-network a.icoGithub:hover i, 33 | .social-network a.icoLinkedin:hover i, 34 | .social-network a.icoEmail:hover i { 35 | color: #fff; 36 | } 37 | 38 | .social-network a.socialIcon:hover, 39 | .socialHoverClass { 40 | color: #44BCDD; 41 | } 42 | 43 | .social-circle li a { 44 | display: inline-block; 45 | position: relative; 46 | margin: 0 auto 0 auto; 47 | -moz-border-radius: 50%; 48 | -webkit-border-radius: 50%; 49 | border-radius: 50%; 50 | text-align: center; 51 | width: 30px; 52 | height: 30px; 53 | font-size: 15px; 54 | } 55 | 56 | .social-circle li i { 57 | margin: 0; 58 | line-height: 30px; 59 | text-align: center; 60 | } 61 | 62 | .social-circle li a:hover i, 63 | .triggeredHover { 64 | -moz-transform: rotate(360deg); 65 | -webkit-transform: rotate(360deg); 66 | -ms--transform: rotate(360deg); 67 | transform: rotate(360deg); 68 | -webkit-transition: all 0.2s; 69 | -moz-transition: all 0.2s; 70 | -o-transition: all 0.2s; 71 | -ms-transition: all 0.2s; 72 | transition: all 0.2s; 73 | } 74 | 75 | .social-circle i { 76 | color: #595959; 77 | -webkit-transition: all 0.8s; 78 | -moz-transition: all 0.8s; 79 | -o-transition: all 0.8s; 80 | -ms-transition: all 0.8s; 81 | transition: all 0.8s; 82 | } 83 | 84 | .social-network a { 85 | background-color: #F9F9F9; 86 | } 87 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/footer/footer.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/footer/footer.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-footer', 5 | templateUrl: './footer.component.html', 6 | styleUrls: ['./footer.component.css'] 7 | }) 8 | export class FooterComponent implements OnInit { 9 | 10 | autor: any = {nombre: 'Eduardo', apellido: 'Cristóbal'}; 11 | 12 | constructor() { } 13 | 14 | ngOnInit() { 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/header/header.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/angular/clientes-app/src/app/header/header.component.css -------------------------------------------------------------------------------- /angular/clientes-app/src/app/header/header.component.html: -------------------------------------------------------------------------------- 1 | 30 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/header/header.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from '../usuarios/auth.service'; 3 | import swal from 'sweetalert2'; 4 | import { Router } from '@angular/router'; 5 | 6 | @Component({ 7 | selector: 'app-header', 8 | templateUrl: './header.component.html', 9 | styleUrls: ['./header.component.css'] 10 | }) 11 | export class HeaderComponent implements OnInit { 12 | 13 | title = 'Web App Angular & Spring'; 14 | 15 | constructor(private authService: AuthService, private router: Router) { } 16 | 17 | ngOnInit() { 18 | } 19 | 20 | logout(): void { 21 | let username = this.authService.usuario.username; 22 | this.authService.logout(); 23 | swal.fire('Logout', `${username} ha cerrado sesión con éxito`, 'success'); 24 | this.router.navigate(['/login']); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/paginator/paginator.component.html: -------------------------------------------------------------------------------- 1 |
    2 | 3 |
  • 4 | « 5 |
  • 6 | 7 |
  • 8 | First 9 |
  • 10 | 11 |
  • 12 | {{ page }} 13 | {{ page }} 14 |
  • 15 | 16 |
  • 17 | Last 18 |
  • 19 | 20 |
  • 21 | » 22 |
  • 23 |
24 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/paginator/paginator.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'paginator-nav', 5 | templateUrl: './paginator.component.html' 6 | }) 7 | export class PaginatorComponent implements OnInit, OnChanges { 8 | @Input() paginator: any; 9 | pages: number[]; 10 | 11 | from: number; 12 | to: number; 13 | 14 | constructor() { } 15 | 16 | ngOnInit() { 17 | this.initPaginator(); 18 | } 19 | 20 | ngOnChanges(changes: SimpleChanges) { 21 | const updatedPaginator = changes.paginator; 22 | 23 | if (updatedPaginator.previousValue) { 24 | this.initPaginator(); 25 | } 26 | } 27 | 28 | private initPaginator(): void { 29 | this.from = Math.min(Math.max(1, this.paginator.number - 4), this.paginator.totalPages - 5); 30 | this.to = Math.max(Math.min(this.paginator.totalPages, this.paginator.number + 4), 6); 31 | if (this.paginator.totalPages > 5) { 32 | this.pages = new Array(this.to - this.from + 1).fill(0).map((valor, indice) => indice + this.from); 33 | } else { 34 | this.pages = new Array(this.paginator.totalPages).fill(0).map((valor, indice) => indice + 1); 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/usuarios/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | import { HttpClient, HttpHeaders } from '@angular/common/http'; 4 | import { Usuario } from './usuario'; 5 | 6 | import { URL_BACKEND } from 'src/app/config/config'; 7 | 8 | @Injectable({ 9 | providedIn: 'root' 10 | }) 11 | export class AuthService { 12 | private _usuario: Usuario; 13 | private _token: string; 14 | 15 | constructor(private http: HttpClient) { } 16 | 17 | public get usuario(): Usuario { 18 | if (this._usuario != null) { 19 | return this._usuario; 20 | } else if (this._usuario == null && sessionStorage.getItem('usuario') != null) { 21 | this._usuario = JSON.parse(sessionStorage.getItem('usuario')) as Usuario; 22 | return this._usuario; 23 | } 24 | return new Usuario(); 25 | } 26 | 27 | public get token(): string { 28 | if (this._token != null) { 29 | return this._token; 30 | } else if (this._token == null && sessionStorage.getItem('token') != null) { 31 | this._token = sessionStorage.getItem('token'); 32 | return this._token; 33 | } 34 | return null; 35 | } 36 | 37 | login(usuario: Usuario): Observable { 38 | const urlEndpoint = URL_BACKEND + '/oauth/token'; 39 | const clientCredentials = btoa('angularapp' + ':' + '12345'); 40 | const httpHeaders = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded', 41 | 'Authorization': 'Basic ' + clientCredentials}); 42 | let params = new URLSearchParams(); 43 | params.set('grant_type', 'password'); 44 | params.set('username', usuario.username); 45 | params.set('password', usuario.password); 46 | return this.http.post(urlEndpoint, params.toString(), {headers: httpHeaders}); 47 | } 48 | 49 | saveUser(accessToken: string) { 50 | let payload = this.obtainPayload(accessToken); 51 | this._usuario = new Usuario(); 52 | this._usuario.username = payload.user_name; 53 | this._usuario.roles = payload.authorities; 54 | sessionStorage.setItem('usuario', JSON.stringify(this._usuario)); 55 | } 56 | 57 | saveAccessToken(accessToken: string) { 58 | this._token = accessToken; 59 | sessionStorage.setItem('token', accessToken); 60 | } 61 | 62 | obtainPayload(accessToken: string): any { 63 | if (accessToken != null) { 64 | return JSON.parse(atob(accessToken.split('.')[1])); 65 | } 66 | return null; 67 | } 68 | 69 | isAuthenticated(): boolean { 70 | let payload = this.obtainPayload(this.token); 71 | if (payload != null && payload.user_name && payload.user_name.length > 0) { 72 | return true; 73 | } 74 | return false; 75 | } 76 | 77 | hasRole(role: string): boolean { 78 | return this.usuario.roles.includes(role); 79 | } 80 | 81 | logout(): void { 82 | this._token = null; 83 | this._usuario = null; 84 | //sessionStorage.clear(); removes everything 85 | sessionStorage.removeItem('token'); 86 | sessionStorage.removeItem('usuario'); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/usuarios/guards/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | import { AuthService } from '../auth.service'; 5 | 6 | @Injectable({ 7 | providedIn: 'root' 8 | }) 9 | export class AuthGuard implements CanActivate { 10 | 11 | constructor(private authService: AuthService, private router: Router) {} 12 | 13 | canActivate( 14 | next: ActivatedRouteSnapshot, 15 | state: RouterStateSnapshot): Observable | Promise | boolean { 16 | if (this.authService.isAuthenticated()) { 17 | if (this.isTokenExpired()) { 18 | this.authService.logout(); 19 | this.router.navigate(['login']); 20 | return false; 21 | } 22 | return true; 23 | } 24 | this.router.navigate(['/login']); 25 | return false; 26 | } 27 | 28 | isTokenExpired(): boolean { 29 | let token = this.authService.token; 30 | let payload = this.authService.obtainPayload(token); 31 | let nowInSeconds = new Date().getTime() / 1000; 32 | return (payload.exp < nowInSeconds); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/usuarios/guards/role.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | import { AuthService } from '../auth.service'; 5 | import swal from 'sweetalert2'; 6 | 7 | @Injectable({ 8 | providedIn: 'root' 9 | }) 10 | export class RoleGuard implements CanActivate { 11 | 12 | constructor(private authService: AuthService, private router: Router) {} 13 | 14 | canActivate( 15 | next: ActivatedRouteSnapshot, 16 | state: RouterStateSnapshot): Observable | Promise | boolean { 17 | if (!this.authService.isAuthenticated()) { 18 | this.router.navigate(['/login']); 19 | return false; 20 | } 21 | let role = next.data.role as string; 22 | console.log(role); 23 | if (this.authService.hasRole(role)) { 24 | return true; 25 | } 26 | swal.fire('Access denied', `Your user (${this.authService.usuario.username}) is not allowed to access to that content.`, 'warning'); 27 | this.router.navigate(['/clientes']); 28 | return false; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/usuarios/interceptors/auth.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { 3 | HttpEvent, HttpInterceptor, HttpHandler, HttpRequest 4 | } from '@angular/common/http'; 5 | 6 | import { Observable, throwError } from 'rxjs'; 7 | import { AuthService } from '../auth.service'; 8 | import swal from 'sweetalert2'; 9 | import { catchError } from 'rxjs/operators'; 10 | import { Router } from '@angular/router'; 11 | 12 | /** Pass untouched request through to the next request handler. */ 13 | @Injectable() 14 | export class AuthInterceptor implements HttpInterceptor { 15 | 16 | constructor(private authService: AuthService, private router: Router) {} 17 | 18 | intercept(req: HttpRequest, next: HttpHandler): 19 | Observable> { 20 | return next.handle(req).pipe( 21 | catchError(e => { 22 | if (e.status == 401) { 23 | if (this.authService.isAuthenticated()) { 24 | this.authService.logout(); 25 | } 26 | this.router.navigate(['/login']); 27 | } else if (e.status == 403) { 28 | swal.fire('Access denied', 29 | `Your user (${this.authService.usuario.username}) is not allowed to access to that content.`, 30 | 'warning'); 31 | this.router.navigate(['/clientes']); 32 | } 33 | return throwError(e); 34 | }) 35 | ); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/usuarios/interceptors/token.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { 3 | HttpEvent, HttpInterceptor, HttpHandler, HttpRequest 4 | } from '@angular/common/http'; 5 | 6 | import { Observable } from 'rxjs'; 7 | import { AuthService } from '../auth.service'; 8 | 9 | /** Pass untouched request through to the next request handler. */ 10 | @Injectable() 11 | export class TokenInterceptor implements HttpInterceptor { 12 | 13 | constructor(private authService: AuthService) {} 14 | 15 | intercept(req: HttpRequest, next: HttpHandler): 16 | Observable> { 17 | let token = this.authService.token; 18 | if (token != null) { 19 | const authReq = req.clone({ 20 | headers: req.headers.set('Authorization', 'Bearer ' + token) 21 | }); 22 | console.log('TokenInterceptor => Bearer ' + token); 23 | return next.handle(authReq); 24 | } 25 | 26 | return next.handle(req); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/usuarios/login.component.html: -------------------------------------------------------------------------------- 1 |
2 |
{{titulo}}
3 |
4 |
5 |
6 | 7 |
8 | 9 |
10 | 11 |
12 | 13 |
14 | 15 |
16 |
17 |
18 |
19 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/usuarios/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Usuario } from './usuario'; 3 | import swal from 'sweetalert2'; 4 | import { AuthService } from './auth.service'; 5 | import { Router } from '@angular/router'; 6 | 7 | @Component({ 8 | selector: 'app-login', 9 | templateUrl: './login.component.html' 10 | }) 11 | export class LoginComponent implements OnInit { 12 | titulo = 'Iniciar sesión'; 13 | usuario: Usuario; 14 | 15 | constructor(private authService: AuthService, private router: Router) { 16 | this.usuario = new Usuario(); 17 | } 18 | 19 | ngOnInit() { 20 | if (this.authService.isAuthenticated()) { 21 | swal.fire('Login', `You are signed in as: ${this.authService.usuario.username}`, 'info'); 22 | this.router.navigate(['/clientes']); 23 | } 24 | } 25 | 26 | login(): void { 27 | console.log(this.usuario); 28 | if (this.usuario.username == null || this.usuario.password == null) { 29 | swal.fire('Error login', 'Username and password cannot be empty', 'error'); 30 | return; 31 | } 32 | this.authService.login(this.usuario).subscribe(response => { 33 | console.log(response); 34 | 35 | this.authService.saveUser(response.access_token); 36 | this.authService.saveAccessToken(response.access_token); 37 | let usuario = this.authService.usuario; 38 | this.router.navigate(['/clientes']); 39 | swal.fire('Login', `Bienvenido ${usuario.username}`, 'success'); 40 | }, err => { 41 | if (err.status == 400) { 42 | swal.fire('Error login', 'Username or password invalid!', 'error'); 43 | } 44 | }); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /angular/clientes-app/src/app/usuarios/usuario.ts: -------------------------------------------------------------------------------- 1 | export class Usuario { 2 | id: number; 3 | username: string; 4 | password: string; 5 | roles: string[] = []; 6 | } 7 | -------------------------------------------------------------------------------- /angular/clientes-app/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/angular/clientes-app/src/assets/.gitkeep -------------------------------------------------------------------------------- /angular/clientes-app/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /angular/clientes-app/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false 7 | }; 8 | 9 | /* 10 | * For easier debugging in development mode, you can import the following file 11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 12 | * 13 | * This import should be commented out in production mode because it will have a negative impact 14 | * on performance if an error is thrown. 15 | */ 16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /angular/clientes-app/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/angular/clientes-app/src/favicon.ico -------------------------------------------------------------------------------- /angular/clientes-app/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ClientesApp 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /angular/clientes-app/src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /angular/clientes-app/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags.ts'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js/dist/zone'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /angular/clientes-app/src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | html { 3 | position: relative; 4 | min-height: 100%; 5 | } 6 | body { 7 | margin-bottom: 60px; 8 | } 9 | 10 | .wrap { 11 | padding-bottom: 60px; 12 | } 13 | html, body { height: 100%; } 14 | body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; } 15 | -------------------------------------------------------------------------------- /angular/clientes-app/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/zone-testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting() 16 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /angular/clientes-app/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/app", 5 | "types": [] 6 | }, 7 | "files": [ 8 | "src/main.ts", 9 | "src/polyfills.ts" 10 | ], 11 | "include": [ 12 | "src/**/*.ts" 13 | ], 14 | "exclude": [ 15 | "src/test.ts", 16 | "src/**/*.spec.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /angular/clientes-app/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "downlevelIteration": true, 9 | "experimentalDecorators": true, 10 | "module": "esnext", 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es2015", 14 | "typeRoots": [ 15 | "node_modules/@types" 16 | ], 17 | "lib": [ 18 | "es2018", 19 | "dom" 20 | ] 21 | }, 22 | "angularCompilerOptions": { 23 | "fullTemplateTypeCheck": true, 24 | "strictInjectionParameters": true 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /angular/clientes-app/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /angular/clientes-app/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "array-type": false, 5 | "arrow-parens": false, 6 | "deprecation": { 7 | "severity": "warning" 8 | }, 9 | "component-class-suffix": true, 10 | "contextual-lifecycle": true, 11 | "directive-class-suffix": true, 12 | "directive-selector": [ 13 | true, 14 | "attribute", 15 | "app", 16 | "camelCase" 17 | ], 18 | "component-selector": [ 19 | true, 20 | "element", 21 | "app", 22 | "kebab-case" 23 | ], 24 | "import-blacklist": [ 25 | true, 26 | "rxjs/Rx" 27 | ], 28 | "interface-name": false, 29 | "max-classes-per-file": false, 30 | "max-line-length": [ 31 | true, 32 | 140 33 | ], 34 | "member-access": false, 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-consecutive-blank-lines": false, 47 | "no-console": [ 48 | true, 49 | "debug", 50 | "info", 51 | "time", 52 | "timeEnd", 53 | "trace" 54 | ], 55 | "no-empty": false, 56 | "no-inferrable-types": [ 57 | true, 58 | "ignore-params" 59 | ], 60 | "no-non-null-assertion": true, 61 | "no-redundant-jsdoc": true, 62 | "no-switch-case-fall-through": true, 63 | "no-var-requires": false, 64 | "object-literal-key-quotes": [ 65 | true, 66 | "as-needed" 67 | ], 68 | "object-literal-sort-keys": false, 69 | "ordered-imports": false, 70 | "quotemark": [ 71 | true, 72 | "single" 73 | ], 74 | "trailing-comma": false, 75 | "no-conflicting-lifecycle": true, 76 | "no-host-metadata-property": true, 77 | "no-input-rename": true, 78 | "no-inputs-metadata-property": true, 79 | "no-output-native": true, 80 | "no-output-on-prefix": true, 81 | "no-output-rename": true, 82 | "no-outputs-metadata-property": true, 83 | "template-banana-in-box": true, 84 | "template-no-negated-async": true, 85 | "use-lifecycle-interface": true, 86 | "use-pipe-transform-interface": true 87 | }, 88 | "rulesDirectory": [ 89 | "codelyzer" 90 | ] 91 | } -------------------------------------------------------------------------------- /postman-collection/Local.postman_environment.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "54e85a9e-d468-4819-b66a-caa3a66a66ec", 3 | "name": "Local", 4 | "values": [ 5 | { 6 | "key": "urlHost", 7 | "value": "http://localhost:8081", 8 | "enabled": true 9 | } 10 | ], 11 | "_postman_variable_scope": "environment", 12 | "_postman_exported_at": "2020-03-28T00:47:19.436Z", 13 | "_postman_exported_using": "Postman/7.20.1" 14 | } -------------------------------------------------------------------------------- /postman-collection/RestApiSpringBoot.postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "e8c15e6c-3a86-4eac-a632-12f264bed88d", 4 | "name": "RestApiSpringBoot", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" 6 | }, 7 | "item": [ 8 | { 9 | "name": "http://localhost:8081/oauth/token", 10 | "event": [ 11 | { 12 | "listen": "test", 13 | "script": { 14 | "id": "9ef8befb-69d0-4155-b959-d70078fde620", 15 | "exec": [ 16 | "var data = pm.response.json();\r", 17 | "pm.collectionVariables.set(\"accessToken\", data.access_token);" 18 | ], 19 | "type": "text/javascript" 20 | } 21 | } 22 | ], 23 | "request": { 24 | "auth": { 25 | "type": "basic", 26 | "basic": [ 27 | { 28 | "key": "password", 29 | "value": "{{clienteAppSecret}}", 30 | "type": "string" 31 | }, 32 | { 33 | "key": "username", 34 | "value": "{{clienteApp}}", 35 | "type": "string" 36 | } 37 | ] 38 | }, 39 | "method": "POST", 40 | "header": [], 41 | "body": { 42 | "mode": "urlencoded", 43 | "urlencoded": [ 44 | { 45 | "key": "username", 46 | "value": "{{username}}", 47 | "type": "text" 48 | }, 49 | { 50 | "key": "password", 51 | "value": "{{pwd}}", 52 | "type": "text" 53 | }, 54 | { 55 | "key": "grant_type", 56 | "value": "{{grantTypeLogin}}", 57 | "type": "text" 58 | } 59 | ] 60 | }, 61 | "url": { 62 | "raw": "{{urlHost}}/oauth/token", 63 | "host": [ 64 | "{{urlHost}}" 65 | ], 66 | "path": [ 67 | "oauth", 68 | "token" 69 | ] 70 | } 71 | }, 72 | "response": [] 73 | }, 74 | { 75 | "name": "http://localhost:8081/api/clientes", 76 | "request": { 77 | "method": "GET", 78 | "header": [], 79 | "url": { 80 | "raw": "{{urlHost}}{{restApiService}}/clientes", 81 | "host": [ 82 | "{{urlHost}}{{restApiService}}" 83 | ], 84 | "path": [ 85 | "clientes" 86 | ] 87 | } 88 | }, 89 | "response": [] 90 | }, 91 | { 92 | "name": "http://localhost:8081/api/clientes/regiones", 93 | "request": { 94 | "auth": { 95 | "type": "bearer", 96 | "bearer": [ 97 | { 98 | "key": "token", 99 | "value": "{{accessToken}}", 100 | "type": "string" 101 | } 102 | ] 103 | }, 104 | "method": "GET", 105 | "header": [], 106 | "url": { 107 | "raw": "{{urlHost}}{{restApiService}}/clientes/regiones", 108 | "host": [ 109 | "{{urlHost}}{{restApiService}}" 110 | ], 111 | "path": [ 112 | "clientes", 113 | "regiones" 114 | ] 115 | } 116 | }, 117 | "response": [] 118 | }, 119 | { 120 | "name": "http://localhost:8081/api/clientes/upload", 121 | "event": [ 122 | { 123 | "listen": "test", 124 | "script": { 125 | "id": "0cfd3f1a-1d0c-4258-b8a4-7a18cb90f5cb", 126 | "exec": [ 127 | "var data = pm.response.json();\r", 128 | "pm.collectionVariables.set(\"photo\", data.cliente.photo);" 129 | ], 130 | "type": "text/javascript" 131 | } 132 | } 133 | ], 134 | "request": { 135 | "auth": { 136 | "type": "bearer", 137 | "bearer": [ 138 | { 139 | "key": "token", 140 | "value": "{{accessToken}}", 141 | "type": "string" 142 | } 143 | ] 144 | }, 145 | "method": "POST", 146 | "header": [], 147 | "body": { 148 | "mode": "formdata", 149 | "formdata": [ 150 | { 151 | "key": "file", 152 | "type": "file", 153 | "src": "/C:/profile.png" 154 | }, 155 | { 156 | "key": "id", 157 | "value": "1", 158 | "type": "text" 159 | } 160 | ] 161 | }, 162 | "url": { 163 | "raw": "{{urlHost}}{{restApiService}}/clientes/upload", 164 | "host": [ 165 | "{{urlHost}}{{restApiService}}" 166 | ], 167 | "path": [ 168 | "clientes", 169 | "upload" 170 | ] 171 | } 172 | }, 173 | "response": [] 174 | }, 175 | { 176 | "name": "http://localhost:8081/api/uploads/img/{{photo}}", 177 | "request": { 178 | "auth": { 179 | "type": "bearer", 180 | "bearer": [ 181 | { 182 | "key": "token", 183 | "value": "{{accessToken}}", 184 | "type": "string" 185 | } 186 | ] 187 | }, 188 | "method": "GET", 189 | "header": [], 190 | "url": { 191 | "raw": "{{urlHost}}{{restApiService}}/uploads/img/{{photo}}", 192 | "host": [ 193 | "{{urlHost}}{{restApiService}}" 194 | ], 195 | "path": [ 196 | "uploads", 197 | "img", 198 | "{{photo}}" 199 | ] 200 | } 201 | }, 202 | "response": [] 203 | }, 204 | { 205 | "name": "http://localhost:8081/api/clientes/page/{page} FIRST", 206 | "request": { 207 | "auth": { 208 | "type": "bearer", 209 | "bearer": [ 210 | { 211 | "key": "token", 212 | "value": "{{accessToken}}", 213 | "type": "string" 214 | } 215 | ] 216 | }, 217 | "method": "GET", 218 | "header": [], 219 | "url": { 220 | "raw": "{{urlHost}}{{restApiService}}/clientes/page/0", 221 | "host": [ 222 | "{{urlHost}}{{restApiService}}" 223 | ], 224 | "path": [ 225 | "clientes", 226 | "page", 227 | "0" 228 | ] 229 | } 230 | }, 231 | "response": [] 232 | }, 233 | { 234 | "name": "http://localhost:8081/api/clientes/{id}", 235 | "request": { 236 | "auth": { 237 | "type": "bearer", 238 | "bearer": [ 239 | { 240 | "key": "token", 241 | "value": "{{accessToken}}", 242 | "type": "string" 243 | } 244 | ] 245 | }, 246 | "method": "GET", 247 | "header": [], 248 | "url": { 249 | "raw": "{{urlHost}}{{restApiService}}/clientes/3", 250 | "host": [ 251 | "{{urlHost}}{{restApiService}}" 252 | ], 253 | "path": [ 254 | "clientes", 255 | "3" 256 | ] 257 | } 258 | }, 259 | "response": [] 260 | }, 261 | { 262 | "name": "http://localhost:8081/api/clientes/{id} WITHOUT AUTH", 263 | "request": { 264 | "auth": { 265 | "type": "noauth" 266 | }, 267 | "method": "GET", 268 | "header": [], 269 | "url": { 270 | "raw": "{{urlHost}}{{restApiService}}/clientes/1", 271 | "host": [ 272 | "{{urlHost}}{{restApiService}}" 273 | ], 274 | "path": [ 275 | "clientes", 276 | "1" 277 | ] 278 | } 279 | }, 280 | "response": [] 281 | }, 282 | { 283 | "name": "http://localhost:8081/api/facturas/{id} WITHOUT AUTH Copy", 284 | "request": { 285 | "auth": { 286 | "type": "noauth" 287 | }, 288 | "method": "GET", 289 | "header": [], 290 | "url": { 291 | "raw": "{{urlHost}}{{restApiService}}/facturas/1", 292 | "host": [ 293 | "{{urlHost}}{{restApiService}}" 294 | ], 295 | "path": [ 296 | "facturas", 297 | "1" 298 | ] 299 | } 300 | }, 301 | "response": [] 302 | }, 303 | { 304 | "name": "http://localhost:8081/api/facturas/product-filter/{term} WITHOUT AUTH", 305 | "request": { 306 | "auth": { 307 | "type": "noauth" 308 | }, 309 | "method": "GET", 310 | "header": [], 311 | "url": { 312 | "raw": "{{urlHost}}{{restApiService}}/facturas/product-filter/son", 313 | "host": [ 314 | "{{urlHost}}{{restApiService}}" 315 | ], 316 | "path": [ 317 | "facturas", 318 | "product-filter", 319 | "son" 320 | ] 321 | } 322 | }, 323 | "response": [] 324 | }, 325 | { 326 | "name": "http://localhost:8081/api/clientes/{id} NOT FOUND", 327 | "request": { 328 | "auth": { 329 | "type": "bearer", 330 | "bearer": [ 331 | { 332 | "key": "token", 333 | "value": "{{accessToken}}", 334 | "type": "string" 335 | } 336 | ] 337 | }, 338 | "method": "GET", 339 | "header": [], 340 | "url": { 341 | "raw": "{{urlHost}}{{restApiService}}/clientes/130", 342 | "host": [ 343 | "{{urlHost}}{{restApiService}}" 344 | ], 345 | "path": [ 346 | "clientes", 347 | "130" 348 | ] 349 | } 350 | }, 351 | "response": [] 352 | }, 353 | { 354 | "name": "http://localhost:8081/api/clientes", 355 | "request": { 356 | "auth": { 357 | "type": "bearer", 358 | "bearer": [ 359 | { 360 | "key": "token", 361 | "value": "{{accessToken}}", 362 | "type": "string" 363 | } 364 | ] 365 | }, 366 | "method": "POST", 367 | "header": [ 368 | { 369 | "key": "Content-Type", 370 | "name": "Content-Type", 371 | "value": "application/json", 372 | "type": "text" 373 | } 374 | ], 375 | "body": { 376 | "mode": "raw", 377 | "raw": "{\r\n \"nombre\": \"Eduardo\",\r\n \"apellido\": \"User\",\r\n \"email\": \"newuser@gmail.com\",\r\n \"createdAt\": \"2019-12-16T16:50:12.646+0100\",\r\n \"region\": {\r\n \"id\": 3,\r\n \"name\": \"Europe\"\r\n }\r\n}", 378 | "options": { 379 | "raw": { 380 | "language": "json" 381 | } 382 | } 383 | }, 384 | "url": { 385 | "raw": "{{urlHost}}{{restApiService}}/clientes", 386 | "host": [ 387 | "{{urlHost}}{{restApiService}}" 388 | ], 389 | "path": [ 390 | "clientes" 391 | ] 392 | } 393 | }, 394 | "response": [] 395 | }, 396 | { 397 | "name": "http://localhost:8081/api/clientes JSON empty", 398 | "request": { 399 | "auth": { 400 | "type": "bearer", 401 | "bearer": [ 402 | { 403 | "key": "token", 404 | "value": "{{accessToken}}", 405 | "type": "string" 406 | } 407 | ] 408 | }, 409 | "method": "POST", 410 | "header": [ 411 | { 412 | "key": "Content-Type", 413 | "name": "Content-Type", 414 | "type": "text", 415 | "value": "application/json" 416 | } 417 | ], 418 | "body": { 419 | "mode": "raw", 420 | "raw": "{}", 421 | "options": { 422 | "raw": { 423 | "language": "json" 424 | } 425 | } 426 | }, 427 | "url": { 428 | "raw": "{{urlHost}}{{restApiService}}/clientes", 429 | "host": [ 430 | "{{urlHost}}{{restApiService}}" 431 | ], 432 | "path": [ 433 | "clientes" 434 | ] 435 | } 436 | }, 437 | "response": [] 438 | }, 439 | { 440 | "name": "http://localhost:8081/api/clientes JSON wrong email format", 441 | "request": { 442 | "auth": { 443 | "type": "bearer", 444 | "bearer": [ 445 | { 446 | "key": "token", 447 | "value": "{{accessToken}}", 448 | "type": "string" 449 | } 450 | ] 451 | }, 452 | "method": "POST", 453 | "header": [ 454 | { 455 | "key": "Content-Type", 456 | "name": "Content-Type", 457 | "type": "text", 458 | "value": "application/json" 459 | } 460 | ], 461 | "body": { 462 | "mode": "raw", 463 | "raw": "{\n\t\"email\": \"asdf\"\n}", 464 | "options": { 465 | "raw": { 466 | "language": "json" 467 | } 468 | } 469 | }, 470 | "url": { 471 | "raw": "{{urlHost}}{{restApiService}}/clientes", 472 | "host": [ 473 | "{{urlHost}}{{restApiService}}" 474 | ], 475 | "path": [ 476 | "clientes" 477 | ] 478 | } 479 | }, 480 | "response": [] 481 | }, 482 | { 483 | "name": "http://localhost:8081/api/clientes JSON wrong name size", 484 | "request": { 485 | "auth": { 486 | "type": "bearer", 487 | "bearer": [ 488 | { 489 | "key": "token", 490 | "value": "{{accessToken}}", 491 | "type": "string" 492 | } 493 | ] 494 | }, 495 | "method": "POST", 496 | "header": [ 497 | { 498 | "key": "Content-Type", 499 | "name": "Content-Type", 500 | "type": "text", 501 | "value": "application/json" 502 | } 503 | ], 504 | "body": { 505 | "mode": "raw", 506 | "raw": "{\n\t\"nombre\": \"Ed\",\n\t\"apellido\": \"C.\",\n\t\"email\": \"asdf@gmail.com\"\n}", 507 | "options": { 508 | "raw": { 509 | "language": "json" 510 | } 511 | } 512 | }, 513 | "url": { 514 | "raw": "{{urlHost}}{{restApiService}}/clientes", 515 | "host": [ 516 | "{{urlHost}}{{restApiService}}" 517 | ], 518 | "path": [ 519 | "clientes" 520 | ] 521 | } 522 | }, 523 | "response": [] 524 | }, 525 | { 526 | "name": "http://localhost:8081/api/clientes email DUPLICADO", 527 | "request": { 528 | "auth": { 529 | "type": "bearer", 530 | "bearer": [ 531 | { 532 | "key": "token", 533 | "value": "{{accessToken}}", 534 | "type": "string" 535 | } 536 | ] 537 | }, 538 | "method": "POST", 539 | "header": [ 540 | { 541 | "key": "Content-Type", 542 | "name": "Content-Type", 543 | "type": "text", 544 | "value": "application/json" 545 | } 546 | ], 547 | "body": { 548 | "mode": "raw", 549 | "raw": "{\r\n\t\"nombre\": \"Eduardo\",\r\n \"apellido\": \"User\",\r\n \"email\": \"unemail@gmail.com\",\r\n \"createdAt\": \"2019-12-16T16:50:12.646+0100\",\r\n \"region\": {\r\n \"id\": 3,\r\n \"name\": \"Europe\"\r\n }\r\n}", 550 | "options": { 551 | "raw": { 552 | "language": "json" 553 | } 554 | } 555 | }, 556 | "url": { 557 | "raw": "{{urlHost}}{{restApiService}}/clientes", 558 | "host": [ 559 | "{{urlHost}}{{restApiService}}" 560 | ], 561 | "path": [ 562 | "clientes" 563 | ] 564 | } 565 | }, 566 | "response": [] 567 | }, 568 | { 569 | "name": "http://localhost:8081/api/clientes/{id}", 570 | "request": { 571 | "auth": { 572 | "type": "bearer", 573 | "bearer": [ 574 | { 575 | "key": "token", 576 | "value": "{{accessToken}}", 577 | "type": "string" 578 | } 579 | ] 580 | }, 581 | "method": "PUT", 582 | "header": [ 583 | { 584 | "key": "Content-Type", 585 | "name": "Content-Type", 586 | "value": "application/json", 587 | "type": "text" 588 | } 589 | ], 590 | "body": { 591 | "mode": "raw", 592 | "raw": "\t{\r\n \"nombre\": \"Client\",\r\n \"apellido\": \"Updated\",\r\n \"email\": \"updated@gmail.com\",\r\n \"createdAt\": \"2019-12-16T15:50:12.646+0000\",\r\n \t\"region\": {\r\n \"id\": 3,\r\n \"name\": \"Europe\"\r\n }\r\n }", 593 | "options": { 594 | "raw": { 595 | "language": "json" 596 | } 597 | } 598 | }, 599 | "url": { 600 | "raw": "{{urlHost}}{{restApiService}}/clientes/2", 601 | "host": [ 602 | "{{urlHost}}{{restApiService}}" 603 | ], 604 | "path": [ 605 | "clientes", 606 | "2" 607 | ] 608 | } 609 | }, 610 | "response": [] 611 | }, 612 | { 613 | "name": "http://localhost:8081/api/clientes/{id} EMAIL duplicado", 614 | "request": { 615 | "auth": { 616 | "type": "bearer", 617 | "bearer": [ 618 | { 619 | "key": "token", 620 | "value": "{{accessToken}}", 621 | "type": "string" 622 | } 623 | ] 624 | }, 625 | "method": "PUT", 626 | "header": [ 627 | { 628 | "key": "Content-Type", 629 | "name": "Content-Type", 630 | "type": "text", 631 | "value": "application/json" 632 | } 633 | ], 634 | "body": { 635 | "mode": "raw", 636 | "raw": "\t{\r\n \"nombre\": \"Client\",\r\n \"apellido\": \"Updated\",\r\n \"email\": \"unemail@gmail.com\",\r\n \"createdAt\": \"2019-12-16T15:50:12.646+0000\",\r\n \t\"region\": {\r\n \"id\": 3,\r\n \"name\": \"Europe\"\r\n }\r\n }", 637 | "options": { 638 | "raw": { 639 | "language": "json" 640 | } 641 | } 642 | }, 643 | "url": { 644 | "raw": "{{urlHost}}{{restApiService}}/clientes/3", 645 | "host": [ 646 | "{{urlHost}}{{restApiService}}" 647 | ], 648 | "path": [ 649 | "clientes", 650 | "3" 651 | ] 652 | } 653 | }, 654 | "response": [] 655 | }, 656 | { 657 | "name": "http://localhost:8081/api/clientes/{id} NOT FOUND", 658 | "request": { 659 | "auth": { 660 | "type": "bearer", 661 | "bearer": [ 662 | { 663 | "key": "token", 664 | "value": "{{accessToken}}", 665 | "type": "string" 666 | } 667 | ] 668 | }, 669 | "method": "PUT", 670 | "header": [ 671 | { 672 | "key": "Content-Type", 673 | "name": "Content-Type", 674 | "type": "text", 675 | "value": "application/json" 676 | } 677 | ], 678 | "body": { 679 | "mode": "raw", 680 | "raw": "\t{\r\n \"nombre\": \"Client\",\r\n \"apellido\": \"Updated\",\r\n \"email\": \"updated@gmail.com\",\r\n \t\"region\": {\r\n \"id\": 3,\r\n \"name\": \"Europe\"\r\n }\r\n }", 681 | "options": { 682 | "raw": { 683 | "language": "json" 684 | } 685 | } 686 | }, 687 | "url": { 688 | "raw": "{{urlHost}}{{restApiService}}/clientes/146", 689 | "host": [ 690 | "{{urlHost}}{{restApiService}}" 691 | ], 692 | "path": [ 693 | "clientes", 694 | "146" 695 | ] 696 | } 697 | }, 698 | "response": [] 699 | }, 700 | { 701 | "name": "http://localhost:8081/api/clientes/{id} nombre NULL", 702 | "request": { 703 | "auth": { 704 | "type": "bearer", 705 | "bearer": [ 706 | { 707 | "key": "token", 708 | "value": "{{accessToken}}", 709 | "type": "string" 710 | } 711 | ] 712 | }, 713 | "method": "PUT", 714 | "header": [ 715 | { 716 | "key": "Content-Type", 717 | "name": "Content-Type", 718 | "type": "text", 719 | "value": "application/json" 720 | } 721 | ], 722 | "body": { 723 | "mode": "raw", 724 | "raw": "\t{\r\n \"apellido\": \"Updated\",\r\n \"email\": \"updated@gmail.com\",\r\n \t\"region\": {\r\n \"id\": 3,\r\n \"name\": \"Europe\"\r\n }\r\n }", 725 | "options": { 726 | "raw": { 727 | "language": "json" 728 | } 729 | } 730 | }, 731 | "url": { 732 | "raw": "{{urlHost}}{{restApiService}}/clientes/2", 733 | "host": [ 734 | "{{urlHost}}{{restApiService}}" 735 | ], 736 | "path": [ 737 | "clientes", 738 | "2" 739 | ] 740 | } 741 | }, 742 | "response": [] 743 | }, 744 | { 745 | "name": "http://localhost:8081/api/clientes/{id}", 746 | "request": { 747 | "auth": { 748 | "type": "bearer", 749 | "bearer": [ 750 | { 751 | "key": "token", 752 | "value": "{{accessToken}}", 753 | "type": "string" 754 | } 755 | ] 756 | }, 757 | "method": "DELETE", 758 | "header": [ 759 | { 760 | "key": "Content-Type", 761 | "name": "Content-Type", 762 | "type": "text", 763 | "value": "application/json" 764 | } 765 | ], 766 | "url": { 767 | "raw": "{{urlHost}}{{restApiService}}/clientes/5", 768 | "host": [ 769 | "{{urlHost}}{{restApiService}}" 770 | ], 771 | "path": [ 772 | "clientes", 773 | "5" 774 | ] 775 | } 776 | }, 777 | "response": [] 778 | }, 779 | { 780 | "name": "http://localhost:8081/api/clientes/{id} NOT FOUND", 781 | "request": { 782 | "auth": { 783 | "type": "bearer", 784 | "bearer": [ 785 | { 786 | "key": "token", 787 | "value": "{{accessToken}}", 788 | "type": "string" 789 | } 790 | ] 791 | }, 792 | "method": "DELETE", 793 | "header": [ 794 | { 795 | "key": "Content-Type", 796 | "name": "Content-Type", 797 | "type": "text", 798 | "value": "application/json" 799 | } 800 | ], 801 | "url": { 802 | "raw": "{{urlHost}}{{restApiService}}/clientes/157", 803 | "host": [ 804 | "{{urlHost}}{{restApiService}}" 805 | ], 806 | "path": [ 807 | "clientes", 808 | "157" 809 | ] 810 | } 811 | }, 812 | "response": [] 813 | } 814 | ], 815 | "event": [ 816 | { 817 | "listen": "prerequest", 818 | "script": { 819 | "id": "527c9ead-5e01-4700-a017-e95b621249d4", 820 | "type": "text/javascript", 821 | "exec": [ 822 | "" 823 | ] 824 | } 825 | }, 826 | { 827 | "listen": "test", 828 | "script": { 829 | "id": "93a49e24-6960-4275-b730-63bd09e7677e", 830 | "type": "text/javascript", 831 | "exec": [ 832 | "" 833 | ] 834 | } 835 | } 836 | ], 837 | "variable": [ 838 | { 839 | "id": "7e331e4f-425c-45d1-80c0-c84d29d8e761", 840 | "key": "restApiService", 841 | "value": "/api", 842 | "type": "string" 843 | }, 844 | { 845 | "id": "6a529cca-5aa6-417b-ac75-5bd2cce3f263", 846 | "key": "username", 847 | "value": "admin", 848 | "type": "string" 849 | }, 850 | { 851 | "id": "000e5e43-be48-4c09-88fc-5f14fa22f6c9", 852 | "key": "pwd", 853 | "value": "12345", 854 | "type": "string" 855 | }, 856 | { 857 | "id": "8beb9e49-a594-4ec6-aa8f-58738c699ac0", 858 | "key": "clienteApp", 859 | "value": "angularapp", 860 | "type": "string" 861 | }, 862 | { 863 | "id": "a830c9cd-e95e-4fe9-8d9f-80e41d8f6df0", 864 | "key": "clienteAppSecret", 865 | "value": "12345", 866 | "type": "string" 867 | }, 868 | { 869 | "id": "55f5b95a-6af8-4f10-a5c0-c3e5b55017f2", 870 | "key": "grantTypeLogin", 871 | "value": "password", 872 | "type": "string" 873 | }, 874 | { 875 | "id": "bd4df74f-e34c-4b07-85af-87aa6f88b004", 876 | "key": "accessToken", 877 | "value": "", 878 | "type": "string" 879 | }, 880 | { 881 | "id": "49ec63f9-8ae7-4246-a722-11d18ef118d9", 882 | "key": "photo", 883 | "value": "", 884 | "type": "string" 885 | } 886 | ], 887 | "protocolProfileBehavior": {} 888 | } -------------------------------------------------------------------------------- /spring-boot-apirest/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /spring-boot-apirest/.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.5"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /spring-boot-apirest/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/spring-boot-apirest/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-apirest/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.2/apache-maven-3.6.2-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar 3 | -------------------------------------------------------------------------------- /spring-boot-apirest/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /spring-boot-apirest/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /spring-boot-apirest/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.2.2.RELEASE 9 | 10 | 11 | com.ecristobale.spring.boot.apirest 12 | spring-boot-apirest 13 | 0.0.1-SNAPSHOT 14 | spring-boot-apirest 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 3.1.1 20 | 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-data-jpa 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-devtools 35 | runtime 36 | true 37 | 38 | 39 | com.h2database 40 | h2 41 | runtime 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-test 46 | test 47 | 48 | 49 | org.junit.vintage 50 | junit-vintage-engine 51 | 52 | 53 | 54 | 55 | org.springframework.security.oauth 56 | spring-security-oauth2 57 | 2.4.0.RELEASE 58 | 59 | 60 | org.springframework.security 61 | spring-security-jwt 62 | 1.1.0.RELEASE 63 | 64 | 65 | 66 | 67 | 68 | 69 | org.springframework.boot 70 | spring-boot-maven-plugin 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | org.springframework.cloud 79 | spring-cloud-dependencies 80 | Hoxton.SR3 81 | pom 82 | import 83 | 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/SpringBootApirestApplication.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.CommandLineRunner; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 8 | 9 | @SpringBootApplication 10 | public class SpringBootApirestApplication {// implements CommandLineRunner{ 11 | 12 | // @Autowired 13 | // private BCryptPasswordEncoder passwordEncoder; 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(SpringBootApirestApplication.class, args); 17 | } 18 | 19 | // @Override 20 | // public void run(String... args) throws Exception { 21 | // String pwd = "12345"; 22 | // for(int i=0; i< 4; i++) { 23 | // String pwdBCrypt = passwordEncoder.encode(pwd); 24 | // System.out.println(pwdBCrypt); 25 | // } 26 | // } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/auth/AuthorizationServerConfig.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.auth; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Qualifier; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.security.authentication.AuthenticationManager; 10 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 11 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 12 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 13 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 14 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 15 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; 16 | import org.springframework.security.oauth2.provider.token.TokenEnhancerChain; 17 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 18 | import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; 19 | 20 | @Configuration 21 | @EnableAuthorizationServer 22 | public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { 23 | 24 | @Autowired 25 | private TokenAditionalInfo tokenAditionalInfo; 26 | 27 | @Autowired 28 | private BCryptPasswordEncoder passwordEncoder; 29 | 30 | @Autowired 31 | @Qualifier("authenticationManager") 32 | private AuthenticationManager authenticationManager; 33 | 34 | // oauth2 endpoints permissions: endpoint1: authenticate, init session and create token <-- public, permitAll 35 | // endpoint2: JWT token validation when a protected page is requested <-- only authenticated users 36 | @Override 37 | public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { 38 | security.tokenKeyAccess("permitAll()") // endpoint1: /outh/token/ --> generate Token --> bearer 39 | .checkTokenAccess("isAuthenticated()"); // endpoint2: /ouath/check_token --> validate Token 40 | } 41 | 42 | // Configure clients who are going to use this api rest (angular app) and their permissions 43 | @Override 44 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 45 | clients.inMemory().withClient("angularapp") 46 | .secret(passwordEncoder.encode("12345")) // basic, not bearer 47 | .scopes("read", "write") 48 | .authorizedGrantTypes("password", "refresh_token") // via login, request for updated access token 49 | .accessTokenValiditySeconds(3600) // lifetime of token: 1h 50 | .refreshTokenValiditySeconds(3600); // lifetime of refresh token: 1h 51 | } 52 | 53 | // Login and Token validation endpoints 54 | @Override 55 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 56 | TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); 57 | tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenAditionalInfo, accessTokenConverter())); 58 | 59 | endpoints.authenticationManager(authenticationManager) 60 | .tokenStore(tokenStore()) 61 | .accessTokenConverter(accessTokenConverter()) 62 | .tokenEnhancer(tokenEnhancerChain); 63 | } 64 | 65 | @Bean 66 | public JwtTokenStore tokenStore() { 67 | return new JwtTokenStore(accessTokenConverter()); 68 | } 69 | 70 | // JWT implementation, code and decode data from JWT 71 | @Bean 72 | public JwtAccessTokenConverter accessTokenConverter() { 73 | JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter(); 74 | jwtAccessTokenConverter.setSigningKey(JwtConfig.PRIVATE_RSA); 75 | jwtAccessTokenConverter.setVerifierKey(JwtConfig.PUBLIC_RSA); 76 | return jwtAccessTokenConverter; 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/auth/JwtConfig.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.auth; 2 | 3 | public class JwtConfig { 4 | 5 | public static final String SECRET_KEY = "some.important.key.1234567"; 6 | 7 | public static final String PRIVATE_RSA = "-----BEGIN RSA PRIVATE KEY-----\r\n" + 8 | "MIIEowIBAAKCAQEAw3ryNOEJQfzs9WoHUyVyoKaIXCBe2V312d1EgmuVsMYzgiCi\r\n" + 9 | "Gs/mq3x/X/tsZFPOL0ZCDiEiQ1kIidlAGt+AjWlzIIJRi1kG7/z3zIX+/+wY7Jxs\r\n" + 10 | "3syG2g8RKRQ1Bp49S5enaHQk1YHc9lWYwS/EDUNVhpGIz30QLaJFZHmvrCZo05Ah\r\n" + 11 | "DZo6gC2XUrZvrscgXJ2cEEX7ez4MeHaAg3y9gSbtTjD5Md2kl/TXEasVOHJtg8Cr\r\n" + 12 | "dQDBJYiU0GN2C2r2voEfR/688GSmVfQnsTJSUtyK+WqqH1au9kG282DHYgPWEKRo\r\n" + 13 | "nRcVxwOsNen/tE8A8/SUjBGz3mWbNbZ1SleqsQIDAQABAoIBAQCywYkfZfHrT/j4\r\n" + 14 | "at8L36C029SyOj/CEjQx6C8v/GXEY1rS0jiqwBc2FgD8qpPyItjXTi41cYM9hvtR\r\n" + 15 | "40LF0EBkEFvhDIq5HM5FQ1TuyFHpgeNA68J68xkV6tVMdVgQF0ACEkpaMGtGexyu\r\n" + 16 | "fpPThXSIlFxvVEKBSuIyeMNwH/7PMi8SRFBdRIra1AvAzp+dTB9su47nPEUy3rJZ\r\n" + 17 | "CYCkyX4vTYiahgzAZ9OLz+gprMcsxZqF8R+TfWKhGg53J7G5VGDGCxqLLCjBvhd8\r\n" + 18 | "4Z3qzc+Yt+mt8vsiH4OHg8mxt2zOSWQXOV/6VGdrlQw7/DvOKb3YlDVoDus0RHCV\r\n" + 19 | "v5BPN3aBAoGBAOiwIAq6IoMz+4T6au+fs1+18fW4/LvlzRXilodp/+LrmuVqz4OS\r\n" + 20 | "RxqqPqTfVKiLj9xBgV5Sp+A5QXDqzFGdPmyjz3vp8GX+j1PJiSaPL/RAO8LrEQoI\r\n" + 21 | "IIgV/CQ6Fj/mGxZyK3BSKxjHmd92ozDDqK92vXbLCRZwNYIe5CYWMcGZAoGBANcQ\r\n" + 22 | "iL2QHNckJjg45Y0dB4y0QjocbSMNhI5tOfyTUIkcooaVyaO6yZXQV5ih8XkmhW5t\r\n" + 23 | "/7/vuVlbFOG/2p0Q4XXjlxMUE5pEK4Tj2Gxxhd0+/tmc9elwUL125KCMiVq8Rgf8\r\n" + 24 | "mKtAHOiE/Fxjyv2/QRa1uG+ssv9FkxXpBS87ORDZAoGAKg4zLF0qAbayff1YuIiP\r\n" + 25 | "vfu/iJ7vpvJI1+zFMiJZamUU8OQWL3yPt2UPv3LR9UiMLs30GN0tlFwk1MjLNvEJ\r\n" + 26 | "qE8PICFPHtAcjZM+Y6a7jxTQ+FDOGpcPcikvEkkhXlkziiIGcd2YBnmE+RuTMSwb\r\n" + 27 | "3+LBKahWsySCt0roB245ffkCgYBbrJCdPXENxDsGfDpdjKJLOAuC+dsLthdrHuQ4\r\n" + 28 | "5hLOX4ZoGDF7uYN0ePrd9SoZmnIGQJ1kE6vOiyS7lix6B1gUCI+9cjFo8OYcH4OB\r\n" + 29 | "tmJ5jQDVgjLQ7y97k9KhHUbvhpHTlbj+RrYL56QrPd6pi30TUSLtd5BVgDLShCHR\r\n" + 30 | "oE0TAQKBgDt4Vx7GGwDbXYUZQ1K2DtMvb/jpQTcHHyszzBHwNGOblIVhfM1lpe/N\r\n" + 31 | "zQNGXVOiu+LvSyvNuA36mru5LJb8CXEzg/NhV+myXsAnurs0jNMJHqR+dc1pC3ze\r\n" + 32 | "SiWUH4cUEL69vjoFLz5DmLYaqUXQnqnatDPv1cX6sYXVsKp3MqTG\r\n" + 33 | "-----END RSA PRIVATE KEY-----"; 34 | 35 | public static final String PUBLIC_RSA = "-----BEGIN PUBLIC KEY-----\r\n" + 36 | "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw3ryNOEJQfzs9WoHUyVy\r\n" + 37 | "oKaIXCBe2V312d1EgmuVsMYzgiCiGs/mq3x/X/tsZFPOL0ZCDiEiQ1kIidlAGt+A\r\n" + 38 | "jWlzIIJRi1kG7/z3zIX+/+wY7Jxs3syG2g8RKRQ1Bp49S5enaHQk1YHc9lWYwS/E\r\n" + 39 | "DUNVhpGIz30QLaJFZHmvrCZo05AhDZo6gC2XUrZvrscgXJ2cEEX7ez4MeHaAg3y9\r\n" + 40 | "gSbtTjD5Md2kl/TXEasVOHJtg8CrdQDBJYiU0GN2C2r2voEfR/688GSmVfQnsTJS\r\n" + 41 | "UtyK+WqqH1au9kG282DHYgPWEKRonRcVxwOsNen/tE8A8/SUjBGz3mWbNbZ1Sleq\r\n" + 42 | "sQIDAQAB\r\n" + 43 | "-----END PUBLIC KEY-----"; 44 | } 45 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/auth/ResourceServerConfig.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.auth; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.core.Ordered; 9 | import org.springframework.http.HttpMethod; 10 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 11 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 12 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 13 | import org.springframework.web.cors.CorsConfiguration; 14 | import org.springframework.web.cors.CorsConfigurationSource; 15 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 16 | import org.springframework.web.filter.CorsFilter; 17 | 18 | //Serves the requested page after token validation 19 | @Configuration 20 | @EnableResourceServer 21 | public class ResourceServerConfig extends ResourceServerConfigurerAdapter{ 22 | 23 | // Security rules of our resources endpoints 24 | @Override 25 | public void configure(HttpSecurity http) throws Exception { 26 | http.authorizeRequests().antMatchers(HttpMethod.GET, "/api/clientes", "/api/clientes/page/**", "/api/uploads/img/**", "/images/**").permitAll() // public route 27 | // .antMatchers(HttpMethod.GET, "/api/clientes/{id}").hasAnyRole("ADMIN", "USER") 28 | // .antMatchers(HttpMethod.POST, "/api/clientes/upload").hasAnyRole("ADMIN", "USER") 29 | // .antMatchers(HttpMethod.POST, "/api/clientes").hasRole("ADMIN") 30 | // .antMatchers("/api/clientes/**").hasRole("ADMIN") 31 | .antMatchers("/h2-console/**").permitAll() 32 | .anyRequest().authenticated() // all other urls can be access by any authenticated role 33 | .and().headers().frameOptions().sameOrigin() 34 | .and().cors().configurationSource(corsConfigurationSource()); //allow use of frame to same origin urls. routes need authentication 35 | } 36 | 37 | @Bean 38 | CorsConfigurationSource corsConfigurationSource() { 39 | CorsConfiguration configuration = new CorsConfiguration(); 40 | configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200")); 41 | configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "OPTIONS")); 42 | configuration.setAllowCredentials(true); 43 | configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization")); 44 | 45 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 46 | source.registerCorsConfiguration("/**", configuration); 47 | return source; 48 | } 49 | 50 | @Bean 51 | public FilterRegistrationBean corsFilter() { 52 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new CorsFilter(corsConfigurationSource())); 53 | filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); 54 | return filterRegistrationBean; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/auth/SpringSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.auth; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.security.authentication.AuthenticationManager; 7 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 8 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 11 | import org.springframework.security.config.http.SessionCreationPolicy; 12 | import org.springframework.security.core.userdetails.UserDetailsService; 13 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 14 | 15 | @EnableGlobalMethodSecurity(securedEnabled = true) 16 | @Configuration 17 | public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { 18 | 19 | @Autowired 20 | private UserDetailsService usuarioService; 21 | 22 | @Bean 23 | public BCryptPasswordEncoder passwordEncoder() { 24 | return new BCryptPasswordEncoder(); 25 | } 26 | 27 | @Override 28 | @Autowired 29 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 30 | auth.userDetailsService(usuarioService).passwordEncoder(passwordEncoder()); 31 | } 32 | 33 | @Bean 34 | @Override 35 | protected AuthenticationManager authenticationManager() throws Exception { 36 | return super.authenticationManager(); 37 | } 38 | 39 | @Override 40 | public void configure(HttpSecurity http) throws Exception { 41 | http.authorizeRequests() 42 | .anyRequest().authenticated() // all other urls can be access by any authenticated role 43 | .and().csrf().disable() //don't apply CSRF protection 44 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // without session management 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/auth/TokenAditionalInfo.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.auth; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; 8 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 9 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 10 | import org.springframework.security.oauth2.provider.token.TokenEnhancer; 11 | import org.springframework.stereotype.Component; 12 | 13 | import com.ecristobale.spring.boot.apirest.models.entity.Usuario; 14 | import com.ecristobale.spring.boot.apirest.models.services.IUsuarioService; 15 | 16 | @Component 17 | public class TokenAditionalInfo implements TokenEnhancer { 18 | 19 | @Autowired 20 | IUsuarioService usuarioService; 21 | 22 | @Override 23 | public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { 24 | Usuario usuario = usuarioService.findByUsername(authentication.getName()); 25 | 26 | Map info = new HashMap<>(); 27 | info.put("aditional_info", "user: " + authentication.getName()); 28 | info.put("user", usuario.getId() + ": " + usuario.getUsername()); 29 | 30 | ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info); 31 | return accessToken; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/controllers/ClienteRestController.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.controllers; 2 | 3 | import java.io.IOException; 4 | import java.net.MalformedURLException; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.stream.Collectors; 9 | 10 | import javax.validation.Valid; 11 | 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.core.io.ByteArrayResource; 14 | import org.springframework.core.io.Resource; 15 | import org.springframework.dao.DataAccessException; 16 | import org.springframework.data.domain.Page; 17 | import org.springframework.data.domain.PageRequest; 18 | import org.springframework.http.HttpHeaders; 19 | import org.springframework.http.HttpStatus; 20 | import org.springframework.http.MediaType; 21 | import org.springframework.http.ResponseEntity; 22 | import org.springframework.security.access.annotation.Secured; 23 | import org.springframework.validation.BindingResult; 24 | import org.springframework.web.bind.annotation.CrossOrigin; 25 | import org.springframework.web.bind.annotation.DeleteMapping; 26 | import org.springframework.web.bind.annotation.GetMapping; 27 | import org.springframework.web.bind.annotation.PathVariable; 28 | import org.springframework.web.bind.annotation.PostMapping; 29 | import org.springframework.web.bind.annotation.PutMapping; 30 | import org.springframework.web.bind.annotation.RequestBody; 31 | import org.springframework.web.bind.annotation.RequestMapping; 32 | import org.springframework.web.bind.annotation.RequestParam; 33 | import org.springframework.web.bind.annotation.RestController; 34 | import org.springframework.web.multipart.MultipartFile; 35 | 36 | import com.ecristobale.spring.boot.apirest.models.entity.Cliente; 37 | import com.ecristobale.spring.boot.apirest.models.entity.ImgPerfil; 38 | import com.ecristobale.spring.boot.apirest.models.entity.Region; 39 | import com.ecristobale.spring.boot.apirest.models.services.IClienteService; 40 | import com.ecristobale.spring.boot.apirest.models.services.IUploadFileService; 41 | 42 | @CrossOrigin(origins = {"http://localhost:4200"}) 43 | @RestController 44 | @RequestMapping("/api") 45 | public class ClienteRestController { 46 | 47 | @Autowired 48 | IClienteService clienteService; 49 | 50 | @Autowired 51 | IUploadFileService uploadFileService; 52 | 53 | @GetMapping("/clientes") 54 | public List index() { 55 | return clienteService.findAll(); 56 | } 57 | 58 | @GetMapping("/clientes/page/{page}") 59 | public Page index(@PathVariable Integer page) { 60 | return clienteService.findAll(PageRequest.of(page, 4)); 61 | } 62 | 63 | @Secured({"ROLE_ADMIN", "ROLE_USER"}) 64 | @GetMapping("/clientes/{id}") 65 | public ResponseEntity show(@PathVariable Long id) { 66 | Cliente cliente = null; 67 | Map response = new HashMap<>(); 68 | try { 69 | cliente = clienteService.findById(id); 70 | } catch(DataAccessException dae) { 71 | response.put("mensaje", "Error al realizar la consulta en la base de datos."); 72 | response.put("error", dae.getMessage().concat(": ").concat(dae.getMostSpecificCause().getMessage())); 73 | return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); 74 | } 75 | 76 | if(cliente == null) { 77 | response.put("mensaje", "El cliente ID: ".concat(id.toString()) 78 | .concat(" no existe en la base de datos.")); 79 | return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); 80 | } 81 | return new ResponseEntity<>(cliente, HttpStatus.OK); 82 | } 83 | 84 | @Secured("ROLE_ADMIN") 85 | @PostMapping("/clientes") 86 | public ResponseEntity create(@Valid @RequestBody Cliente cliente, BindingResult result) { 87 | Cliente newCliente = null; 88 | Map response = new HashMap<>(); 89 | 90 | if(result.hasErrors()) { 91 | List errors = result.getFieldErrors().stream() 92 | .map(err -> "El campo '" + err.getField() + "' " + err.getDefaultMessage() 93 | ).collect(Collectors.toList()); 94 | 95 | response.put("errors", errors); 96 | return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); 97 | } 98 | 99 | try { 100 | newCliente = clienteService.save(cliente); 101 | } catch(DataAccessException dae) { 102 | response.put("mensaje", "Error al realizar la inserción en la base de datos."); 103 | response.put("error", dae.getMessage().concat(": ").concat(dae.getMostSpecificCause().getMessage())); 104 | return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); 105 | } 106 | 107 | response.put("mensaje", "El cliente ha sido creado con éxito"); 108 | response.put("cliente", newCliente); 109 | return new ResponseEntity<>(response, HttpStatus.CREATED); 110 | } 111 | 112 | @Secured("ROLE_ADMIN") 113 | @PutMapping("/clientes/{id}") 114 | public ResponseEntity update(@Valid @PathVariable Long id, @RequestBody Cliente cliente, 115 | BindingResult result) { 116 | Cliente clienteActual = clienteService.findById(id); 117 | Cliente clienteUpdated = null; 118 | Map response = new HashMap<>(); 119 | 120 | if(result.hasErrors()) { 121 | List errors = result.getFieldErrors().stream() 122 | .map(err -> "El campo '" + err.getField() + "' " + err.getDefaultMessage() 123 | ).collect(Collectors.toList()); 124 | 125 | response.put("errors", errors); 126 | return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); 127 | } 128 | 129 | if(clienteActual == null) { 130 | response.put("mensaje", "Error al actualizar. El cliente ID: ".concat(id.toString()) 131 | .concat(" no existe en la base de datos.")); 132 | return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); 133 | } 134 | 135 | try { 136 | clienteActual.setNombre(cliente.getNombre()); 137 | clienteActual.setApellido(cliente.getApellido()); 138 | clienteActual.setEmail(cliente.getEmail()); 139 | clienteActual.setCreatedAt(cliente.getCreatedAt()); 140 | clienteActual.setRegion(cliente.getRegion()); 141 | 142 | clienteUpdated = clienteService.save(clienteActual); 143 | } catch(DataAccessException dae) { 144 | response.put("mensaje", "Error al actualizar en la base de datos."); 145 | response.put("error", dae.getMessage().concat(": ").concat(dae.getMostSpecificCause().getMessage())); 146 | return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); 147 | } 148 | 149 | response.put("mensaje", "El cliente ha sido actualizado con éxito"); 150 | response.put("cliente", clienteUpdated); 151 | return new ResponseEntity<>(response, HttpStatus.CREATED); 152 | } 153 | 154 | @Secured("ROLE_ADMIN") 155 | @DeleteMapping("/clientes/{id}") 156 | public ResponseEntity delete(@PathVariable Long id) { 157 | Map response = new HashMap<>(); 158 | 159 | try{ 160 | Cliente cliente = clienteService.findById(id); 161 | uploadFileService.deleteFile(cliente.getPhoto()); 162 | clienteService.delete(id); 163 | } catch(DataAccessException dae) { 164 | response.put("mensaje", "Error al eliminar en la base de datos."); 165 | response.put("error", dae.getMessage().concat(": ").concat(dae.getMostSpecificCause().getMessage())); 166 | return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); 167 | } 168 | response.put("mensaje", "El cliente se eliminó con éxito"); 169 | return new ResponseEntity<>(response, HttpStatus.OK); 170 | } 171 | 172 | @Secured({"ROLE_ADMIN", "ROLE_USER"}) 173 | @PostMapping("/clientes/upload") 174 | public ResponseEntity upload(@RequestParam("file") MultipartFile file, @RequestParam("id") Long id){ 175 | Map response = new HashMap<>(); 176 | Cliente cliente = clienteService.findById(id); 177 | if(!file.isEmpty()) { 178 | String filename = null; 179 | try { 180 | filename = uploadFileService.uploadFile(file); 181 | } catch (IOException e) { 182 | response.put("mensaje", "Error al subir la imagen"); 183 | response.put("error", e.getMessage().concat(": ").concat(e.getCause().getMessage())); 184 | return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); 185 | } 186 | 187 | uploadFileService.deleteFile(cliente.getPhoto()); 188 | 189 | cliente.setPhoto(filename); 190 | clienteService.save(cliente); 191 | 192 | response.put("cliente", cliente); 193 | response.put("mensaje", "Has subido correctamente la imagen: " + filename); 194 | } 195 | 196 | return new ResponseEntity<>(response, HttpStatus.CREATED); 197 | } 198 | 199 | // Used when the images are retrieved from folder location 200 | // @GetMapping("/uploads/img/{filename:.+}") 201 | // public ResponseEntity showPhoto(@PathVariable String filename) { 202 | // Resource resource = null; 203 | // try { 204 | // resource = uploadFileService.loadFile(filename); 205 | // } catch (MalformedURLException e) { 206 | // e.printStackTrace(); 207 | // } 208 | // HttpHeaders headers = new HttpHeaders(); 209 | // headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\""); 210 | // return new ResponseEntity<>(resource, headers, HttpStatus.OK); 211 | // } 212 | 213 | @GetMapping("/uploads/img/{filename:.+}") 214 | public ResponseEntity showPhoto(@PathVariable String filename) { 215 | ImgPerfil imgPerfil = null; 216 | try { 217 | imgPerfil = uploadFileService.loadFile(filename); 218 | } catch (MalformedURLException e) { 219 | e.printStackTrace(); 220 | } 221 | if( imgPerfil != null ) { 222 | return ResponseEntity.ok() 223 | .contentType(MediaType.parseMediaType(imgPerfil.getFileType())) 224 | .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + imgPerfil.getFilename() + "\"") 225 | .body(new ByteArrayResource(imgPerfil.getImg())); 226 | } else { 227 | Resource resource = null; 228 | try { 229 | resource = uploadFileService.loadFileDefaultImage(filename); 230 | } catch (MalformedURLException e) { 231 | e.printStackTrace(); 232 | } 233 | HttpHeaders headers = new HttpHeaders(); 234 | headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\""); 235 | return new ResponseEntity<>(resource, headers, HttpStatus.OK); 236 | } 237 | } 238 | 239 | @Secured("ROLE_ADMIN") 240 | @GetMapping("clientes/regiones") 241 | public List getRegionsList(){ 242 | return clienteService.findAllRegions(); 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/controllers/FacturaRestController.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.controllers; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.security.access.annotation.Secured; 8 | import org.springframework.web.bind.annotation.CrossOrigin; 9 | import org.springframework.web.bind.annotation.DeleteMapping; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.PathVariable; 12 | import org.springframework.web.bind.annotation.PostMapping; 13 | import org.springframework.web.bind.annotation.RequestBody; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | import org.springframework.web.bind.annotation.ResponseStatus; 16 | import org.springframework.web.bind.annotation.RestController; 17 | 18 | import com.ecristobale.spring.boot.apirest.models.entity.Factura; 19 | import com.ecristobale.spring.boot.apirest.models.entity.Producto; 20 | import com.ecristobale.spring.boot.apirest.models.services.IClienteService; 21 | 22 | @CrossOrigin(origins = {"http://localhost:4200"}) 23 | @RestController 24 | @RequestMapping("/api") 25 | public class FacturaRestController { 26 | 27 | @Autowired 28 | private IClienteService clienteService; 29 | 30 | @Secured({"ROLE_ADMIN", "ROLE_USER"}) 31 | @GetMapping("/facturas/{id}") 32 | @ResponseStatus(code=HttpStatus.OK) 33 | public Factura show(@PathVariable("id") Long id) { 34 | return clienteService.findFacturaById(id); 35 | } 36 | 37 | @Secured({"ROLE_ADMIN"}) 38 | @DeleteMapping("/facturas/{id}") 39 | @ResponseStatus(code=HttpStatus.NO_CONTENT) 40 | public void delete(@PathVariable("id") Long id) { 41 | clienteService.deleteFactura(id); 42 | } 43 | 44 | @Secured({"ROLE_ADMIN"}) 45 | @GetMapping("/facturas/product-filter/{term}") 46 | @ResponseStatus(code=HttpStatus.OK) 47 | public List productFilter(@PathVariable("term") String term) { 48 | return clienteService.findProductoByNombre(term); 49 | } 50 | 51 | @Secured({"ROLE_ADMIN"}) 52 | @PostMapping("/facturas") 53 | @ResponseStatus(code=HttpStatus.CREATED) 54 | public Factura createInvoice(@RequestBody Factura factura) { 55 | return clienteService.save(factura); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/dao/IClienteDao.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.dao; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.Query; 7 | 8 | import com.ecristobale.spring.boot.apirest.models.entity.Cliente; 9 | import com.ecristobale.spring.boot.apirest.models.entity.Region; 10 | 11 | public interface IClienteDao extends JpaRepository { 12 | 13 | @Query("from Region") 14 | public List findAllRegions(); 15 | } 16 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/dao/IFacturaDao.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.dao; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | import com.ecristobale.spring.boot.apirest.models.entity.Factura; 6 | 7 | public interface IFacturaDao extends CrudRepository { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/dao/IImgPerfilDao.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.dao; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | import com.ecristobale.spring.boot.apirest.models.entity.ImgPerfil; 6 | 7 | public interface IImgPerfilDao extends JpaRepository { 8 | 9 | Long deleteByFilename(String filename); 10 | 11 | ImgPerfil findByFilename(String filename); 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/dao/IProductoDao.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.dao; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.jpa.repository.Query; 6 | import org.springframework.data.repository.CrudRepository; 7 | import org.springframework.data.repository.query.Param; 8 | 9 | import com.ecristobale.spring.boot.apirest.models.entity.Producto; 10 | 11 | public interface IProductoDao extends CrudRepository { 12 | 13 | // @Query("select p from Producto p where p.nombre like %?1%") 14 | // public List findByNombre(String term); 15 | 16 | // public List findByNombreStartingWithIgnoreCase(String term); 17 | 18 | public List findByNombreContainingIgnoreCase(String term); 19 | } 20 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/dao/IUsuarioDao.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.dao; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | import com.ecristobale.spring.boot.apirest.models.entity.Usuario; 6 | 7 | public interface IUsuarioDao extends CrudRepository{ 8 | 9 | public Usuario findByUsername(String username); 10 | 11 | // @Query("SELECT u FROM Usuario WHERE u.username = ?1") 12 | // public Usuario findByUsername2(String username); 13 | } 14 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/entity/Cliente.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.entity; 2 | 3 | import java.io.Serializable; 4 | import java.util.ArrayList; 5 | import java.util.Date; 6 | import java.util.List; 7 | 8 | import javax.persistence.CascadeType; 9 | import javax.persistence.Column; 10 | import javax.persistence.Entity; 11 | import javax.persistence.FetchType; 12 | import javax.persistence.GeneratedValue; 13 | import javax.persistence.GenerationType; 14 | import javax.persistence.Id; 15 | import javax.persistence.JoinColumn; 16 | import javax.persistence.ManyToOne; 17 | import javax.persistence.OneToMany; 18 | import javax.persistence.Table; 19 | import javax.persistence.Temporal; 20 | import javax.persistence.TemporalType; 21 | import javax.validation.constraints.Email; 22 | import javax.validation.constraints.NotEmpty; 23 | import javax.validation.constraints.NotNull; 24 | import javax.validation.constraints.Size; 25 | 26 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 27 | 28 | @Entity 29 | @Table(name = "clientes") 30 | public class Cliente implements Serializable { 31 | 32 | public Cliente() { 33 | this.facturas = new ArrayList<>(); 34 | } 35 | 36 | @Id 37 | @GeneratedValue(strategy = GenerationType.IDENTITY) 38 | private Long id; 39 | 40 | @NotEmpty(message = "no puede estar vacío") 41 | @Size(min = 4, max = 12, message = "el tamaño tiene que estar entre 4 y 12 caracteres") 42 | @Column(nullable = false) 43 | private String nombre; 44 | 45 | @NotEmpty(message = "no puede estar vacío") 46 | @Column(nullable = false) 47 | private String apellido; 48 | 49 | @NotEmpty(message = "no puede estar vacío") 50 | @Email(message = "no tiene un formato válido") 51 | @Column(nullable = false, unique = true) 52 | private String email; 53 | 54 | @NotNull(message = "no puede estar vacío") 55 | @Column(name = "created_at") 56 | @Temporal(TemporalType.TIMESTAMP) 57 | private Date createdAt; 58 | 59 | // @PrePersist 60 | // public void prePersist() { 61 | // createdAt = new Date(); 62 | // } 63 | 64 | private String photo; 65 | 66 | @NotNull(message = "no puede estar vacía") 67 | @ManyToOne(fetch = FetchType.LAZY) 68 | @JoinColumn(name = "region_id") 69 | @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) 70 | private Region region; 71 | 72 | @OneToMany(fetch = FetchType.LAZY, mappedBy = "cliente", cascade = CascadeType.ALL) 73 | @JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler", "cliente"}, allowSetters = true) 74 | private List facturas; 75 | 76 | public Long getId() { 77 | return id; 78 | } 79 | public void setId(Long id) { 80 | this.id = id; 81 | } 82 | public String getNombre() { 83 | return nombre; 84 | } 85 | public void setNombre(String nombre) { 86 | this.nombre = nombre; 87 | } 88 | public String getApellido() { 89 | return apellido; 90 | } 91 | public void setApellido(String apellido) { 92 | this.apellido = apellido; 93 | } 94 | public String getEmail() { 95 | return email; 96 | } 97 | public void setEmail(String email) { 98 | this.email = email; 99 | } 100 | public Date getCreatedAt() { 101 | return createdAt; 102 | } 103 | public void setCreatedAt(Date createdAt) { 104 | this.createdAt = createdAt; 105 | } 106 | public String getPhoto() { 107 | return photo; 108 | } 109 | public void setPhoto(String photo) { 110 | this.photo = photo; 111 | } 112 | public Region getRegion() { 113 | return region; 114 | } 115 | public void setRegion(Region region) { 116 | this.region = region; 117 | } 118 | public List getFacturas() { 119 | return facturas; 120 | } 121 | public void setFacturas(List facturas) { 122 | this.facturas = facturas; 123 | } 124 | 125 | private static final long serialVersionUID = 1L; 126 | } 127 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/entity/Factura.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.entity; 2 | 3 | import java.io.Serializable; 4 | import java.util.ArrayList; 5 | import java.util.Date; 6 | import java.util.List; 7 | 8 | import javax.persistence.CascadeType; 9 | import javax.persistence.Column; 10 | import javax.persistence.Entity; 11 | import javax.persistence.FetchType; 12 | import javax.persistence.GeneratedValue; 13 | import javax.persistence.GenerationType; 14 | import javax.persistence.Id; 15 | import javax.persistence.JoinColumn; 16 | import javax.persistence.ManyToOne; 17 | import javax.persistence.OneToMany; 18 | import javax.persistence.PrePersist; 19 | import javax.persistence.Table; 20 | import javax.persistence.Temporal; 21 | import javax.persistence.TemporalType; 22 | 23 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 24 | 25 | @Entity 26 | @Table(name="facturas") 27 | public class Factura implements Serializable{ 28 | 29 | public Factura() { 30 | itemsFactura = new ArrayList<>(); 31 | } 32 | 33 | @Id 34 | @GeneratedValue(strategy = GenerationType.IDENTITY) 35 | private Long id; 36 | private String descripcion; 37 | private String observacion; 38 | 39 | @Column(name="created_at") 40 | @Temporal(TemporalType.DATE) 41 | private Date createdAt; 42 | 43 | @PrePersist 44 | public void prePersist() { 45 | createdAt = new Date(); 46 | } 47 | 48 | @ManyToOne(fetch = FetchType.LAZY) 49 | @JoinColumn(name="cliente_id") 50 | @JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler", "facturas"}, allowSetters = true) 51 | private Cliente cliente; 52 | 53 | @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) 54 | @JoinColumn(name="factura_id") 55 | @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) 56 | private List itemsFactura; 57 | 58 | public Long getId() { 59 | return id; 60 | } 61 | public void setId(Long id) { 62 | this.id = id; 63 | } 64 | 65 | public String getDescripcion() { 66 | return descripcion; 67 | } 68 | public void setDescripcion(String descripcion) { 69 | this.descripcion = descripcion; 70 | } 71 | 72 | public String getObservacion() { 73 | return observacion; 74 | } 75 | public void setObservacion(String observacion) { 76 | this.observacion = observacion; 77 | } 78 | 79 | public Date getCreatedAt() { 80 | return createdAt; 81 | } 82 | public void setCreatedAt(Date createdAt) { 83 | this.createdAt = createdAt; 84 | } 85 | 86 | public Cliente getCliente() { 87 | return cliente; 88 | } 89 | public void setCliente(Cliente cliente) { 90 | this.cliente = cliente; 91 | } 92 | 93 | public List getItemsFactura() { 94 | return itemsFactura; 95 | } 96 | public void setItemsFactura(List itemsFactura) { 97 | this.itemsFactura = itemsFactura; 98 | } 99 | 100 | public Double getTotal() { 101 | Double total = 0.00; 102 | for(ItemFactura item: itemsFactura) { 103 | total += item.getCalcularImporte(); 104 | } 105 | return total; 106 | } 107 | 108 | private static final long serialVersionUID = -5351768005322962590L; 109 | } 110 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/entity/ImgPerfil.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.GenerationType; 9 | import javax.persistence.Id; 10 | import javax.persistence.Lob; 11 | import javax.persistence.Table; 12 | 13 | @Entity 14 | @Table(name="img_perfiles") 15 | public class ImgPerfil implements Serializable { 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private Long id; 20 | private String filename; 21 | 22 | @Column(name = "file_type") 23 | private String fileType; 24 | 25 | @Lob 26 | private byte[] img; 27 | 28 | public Long getId() { 29 | return id; 30 | } 31 | public void setId(Long id) { 32 | this.id = id; 33 | } 34 | 35 | public String getFilename() { 36 | return filename; 37 | } 38 | public void setFilename(String filename) { 39 | this.filename = filename; 40 | } 41 | 42 | public byte[] getImg() { 43 | return img; 44 | } 45 | public void setImg(byte[] img) { 46 | this.img = img; 47 | } 48 | 49 | public String getFileType() { 50 | return fileType; 51 | } 52 | public void setFileType(String fileType) { 53 | this.fileType = fileType; 54 | } 55 | 56 | private static final long serialVersionUID = 1876317499955148677L; 57 | 58 | } 59 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/entity/ItemFactura.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.FetchType; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.GenerationType; 9 | import javax.persistence.Id; 10 | import javax.persistence.JoinColumn; 11 | import javax.persistence.ManyToOne; 12 | import javax.persistence.Table; 13 | 14 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 15 | 16 | @Entity 17 | @Table(name="facturas_items") 18 | public class ItemFactura implements Serializable{ 19 | 20 | @Id 21 | @GeneratedValue(strategy = GenerationType.IDENTITY) 22 | private Long id; 23 | private Integer cantidad; 24 | 25 | @ManyToOne(fetch = FetchType.LAZY) 26 | @JoinColumn(name="producto_id") 27 | @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) 28 | private Producto producto; 29 | 30 | public Long getId() { 31 | return id; 32 | } 33 | public void setId(Long id) { 34 | this.id = id; 35 | } 36 | 37 | public Integer getCantidad() { 38 | return cantidad; 39 | } 40 | public void setCantidad(Integer cantidad) { 41 | this.cantidad = cantidad; 42 | } 43 | 44 | public Producto getProducto() { 45 | return producto; 46 | } 47 | public void setProducto(Producto producto) { 48 | this.producto = producto; 49 | } 50 | 51 | public Double getCalcularImporte() { 52 | return cantidad.doubleValue() * producto.getPrecio(); 53 | } 54 | 55 | private static final long serialVersionUID = 7045632490005235923L; 56 | } 57 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/entity/Producto.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.entity; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.GenerationType; 10 | import javax.persistence.Id; 11 | import javax.persistence.PrePersist; 12 | import javax.persistence.Table; 13 | import javax.persistence.Temporal; 14 | import javax.persistence.TemporalType; 15 | 16 | @Entity 17 | @Table(name="productos") 18 | public class Producto implements Serializable { 19 | 20 | @Id 21 | @GeneratedValue(strategy = GenerationType.IDENTITY) 22 | private Long id; 23 | private String nombre; 24 | private Double precio; 25 | 26 | @Column(name="created_at") 27 | @Temporal(TemporalType.TIMESTAMP) 28 | private Date createdAt; 29 | 30 | @PrePersist 31 | public void prePersist() { 32 | createdAt = new Date(); 33 | } 34 | 35 | public Long getId() { 36 | return id; 37 | } 38 | public void setId(Long id) { 39 | this.id = id; 40 | } 41 | 42 | public String getNombre() { 43 | return nombre; 44 | } 45 | public void setNombre(String nombre) { 46 | this.nombre = nombre; 47 | } 48 | 49 | public Double getPrecio() { 50 | return precio; 51 | } 52 | public void setPrecio(Double precio) { 53 | this.precio = precio; 54 | } 55 | 56 | public Date getCreatedAt() { 57 | return createdAt; 58 | } 59 | public void setCreatedAt(Date createdAt) { 60 | this.createdAt = createdAt; 61 | } 62 | 63 | private static final long serialVersionUID = 4203298557029975022L; 64 | } 65 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/entity/Region.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.GenerationType; 8 | import javax.persistence.Id; 9 | import javax.persistence.Table; 10 | 11 | @Entity 12 | @Table(name="regions") 13 | public class Region implements Serializable { 14 | 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private Long id; 18 | private String name; 19 | 20 | public Long getId() { 21 | return id; 22 | } 23 | public void setId(Long id) { 24 | this.id = id; 25 | } 26 | public String getName() { 27 | return name; 28 | } 29 | public void setName(String name) { 30 | this.name = name; 31 | } 32 | 33 | private static final long serialVersionUID = 9088799141558336624L; 34 | 35 | } 36 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/entity/RegionName.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.entity; 2 | 3 | public enum RegionName { EUROPE, ASIA, AMERICA } -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/entity/Role.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.GenerationType; 9 | import javax.persistence.Id; 10 | import javax.persistence.Table; 11 | 12 | @Entity 13 | @Table(name = "roles") 14 | public class Role implements Serializable { 15 | 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private Long id; 19 | 20 | @Column(unique = true, length = 30) 21 | private String nombre; 22 | 23 | public Long getId() { 24 | return id; 25 | } 26 | public void setId(Long id) { 27 | this.id = id; 28 | } 29 | 30 | public String getNombre() { 31 | return nombre; 32 | } 33 | public void setNombre(String nombre) { 34 | this.nombre = nombre; 35 | } 36 | 37 | private static final long serialVersionUID = -4880723802867757689L; 38 | 39 | } 40 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/entity/Usuario.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.entity; 2 | 3 | import java.io.Serializable; 4 | import java.util.List; 5 | 6 | import javax.persistence.CascadeType; 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.FetchType; 10 | import javax.persistence.GeneratedValue; 11 | import javax.persistence.GenerationType; 12 | import javax.persistence.Id; 13 | import javax.persistence.JoinColumn; 14 | import javax.persistence.JoinTable; 15 | import javax.persistence.ManyToMany; 16 | import javax.persistence.ManyToOne; 17 | import javax.persistence.Table; 18 | import javax.persistence.UniqueConstraint; 19 | 20 | @Entity 21 | @Table(name = "usuarios") 22 | public class Usuario implements Serializable { 23 | 24 | @Id 25 | @GeneratedValue(strategy = GenerationType.IDENTITY) 26 | private Long id; 27 | 28 | @Column(unique = true, length = 20) 29 | private String username; 30 | 31 | @Column(length = 60) 32 | private String password; 33 | 34 | private Boolean enabled; 35 | 36 | @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) 37 | @JoinTable(name = "usuarios_roles", joinColumns = @JoinColumn(name="usuario_id"), inverseJoinColumns = @JoinColumn(name="role_id"), 38 | uniqueConstraints = {@UniqueConstraint(columnNames = {"usuario_id", "role_id"})}) 39 | private List roles; 40 | 41 | public Long getId() { 42 | return id; 43 | } 44 | public void setId(Long id) { 45 | this.id = id; 46 | } 47 | 48 | public String getUsername() { 49 | return username; 50 | } 51 | public void setUsername(String username) { 52 | this.username = username; 53 | } 54 | 55 | public String getPassword() { 56 | return password; 57 | } 58 | public void setPassword(String password) { 59 | this.password = password; 60 | } 61 | 62 | public Boolean getEnabled() { 63 | return enabled; 64 | } 65 | public void setEnabled(Boolean enabled) { 66 | this.enabled = enabled; 67 | } 68 | 69 | public List getRoles() { 70 | return roles; 71 | } 72 | public void setRoles(List roles) { 73 | this.roles = roles; 74 | } 75 | 76 | private static final long serialVersionUID = -8936646686806991238L; 77 | } 78 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/services/ClienteServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.services; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.data.domain.Page; 7 | import org.springframework.data.domain.Pageable; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import com.ecristobale.spring.boot.apirest.models.dao.IClienteDao; 12 | import com.ecristobale.spring.boot.apirest.models.dao.IFacturaDao; 13 | import com.ecristobale.spring.boot.apirest.models.dao.IProductoDao; 14 | import com.ecristobale.spring.boot.apirest.models.entity.Cliente; 15 | import com.ecristobale.spring.boot.apirest.models.entity.Factura; 16 | import com.ecristobale.spring.boot.apirest.models.entity.Producto; 17 | import com.ecristobale.spring.boot.apirest.models.entity.Region; 18 | 19 | @Service 20 | public class ClienteServiceImpl implements IClienteService { 21 | 22 | @Autowired 23 | IClienteDao clienteDao; 24 | 25 | @Autowired 26 | IFacturaDao facturaDao; 27 | 28 | @Autowired 29 | IProductoDao productoDao; 30 | 31 | @Override 32 | @Transactional(readOnly = true) 33 | public List findAll() { 34 | return (List) clienteDao.findAll(); 35 | } 36 | 37 | @Override 38 | @Transactional(readOnly = true) 39 | public Page findAll(Pageable pageable) { 40 | return clienteDao.findAll(pageable); 41 | } 42 | 43 | @Override 44 | @Transactional(readOnly = true) 45 | public Cliente findById(Long id) { 46 | return clienteDao.findById(id).orElse(null); 47 | } 48 | 49 | @Override 50 | @Transactional 51 | public Cliente save(Cliente cliente) { 52 | return clienteDao.save(cliente); 53 | } 54 | 55 | @Override 56 | @Transactional 57 | public void delete(Long id) { 58 | clienteDao.deleteById(id); 59 | } 60 | 61 | @Override 62 | @Transactional(readOnly = true) 63 | public List findAllRegions() { 64 | return clienteDao.findAllRegions(); 65 | } 66 | 67 | @Override 68 | @Transactional(readOnly = true) 69 | public Factura findFacturaById(Long id) { 70 | return facturaDao.findById(id).orElse(null); 71 | } 72 | 73 | @Override 74 | @Transactional 75 | public Factura save(Factura factura) { 76 | return facturaDao.save(factura); 77 | } 78 | 79 | @Override 80 | @Transactional 81 | public void deleteFactura(Long id) { 82 | facturaDao.deleteById(id); 83 | } 84 | 85 | @Override 86 | @Transactional(readOnly = true) 87 | public List findProductoByNombre(String term) { 88 | return productoDao.findByNombreContainingIgnoreCase(term); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/services/IClienteService.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.services; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.domain.Page; 6 | import org.springframework.data.domain.Pageable; 7 | 8 | import com.ecristobale.spring.boot.apirest.models.entity.Cliente; 9 | import com.ecristobale.spring.boot.apirest.models.entity.Factura; 10 | import com.ecristobale.spring.boot.apirest.models.entity.Producto; 11 | import com.ecristobale.spring.boot.apirest.models.entity.Region; 12 | 13 | public interface IClienteService { 14 | 15 | public List findAll(); 16 | 17 | public Page findAll(Pageable pageable); 18 | 19 | public Cliente findById(Long id); 20 | 21 | public Cliente save(Cliente cliente); 22 | 23 | public void delete(Long id); 24 | 25 | public List findAllRegions(); 26 | 27 | public Factura findFacturaById(Long id); 28 | 29 | public Factura save(Factura factura); 30 | 31 | public void deleteFactura(Long id); 32 | 33 | public List findProductoByNombre(String term); 34 | } 35 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/services/IUploadFileService.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.services; 2 | 3 | import java.io.IOException; 4 | import java.net.MalformedURLException; 5 | import java.nio.file.Path; 6 | 7 | import org.springframework.core.io.Resource; 8 | import org.springframework.web.multipart.MultipartFile; 9 | 10 | import com.ecristobale.spring.boot.apirest.models.entity.ImgPerfil; 11 | 12 | public interface IUploadFileService { 13 | 14 | public ImgPerfil loadFile(String filename) throws MalformedURLException; 15 | public String uploadFile(MultipartFile file) throws IOException; 16 | public boolean deleteFile(String filename); 17 | // public Path getPath(String filename); 18 | public Resource loadFileDefaultImage(String filename) throws MalformedURLException; 19 | } 20 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/services/IUsuarioService.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.services; 2 | 3 | import com.ecristobale.spring.boot.apirest.models.entity.Usuario; 4 | 5 | public interface IUsuarioService { 6 | 7 | public Usuario findByUsername(String username); 8 | } 9 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/services/UploadFileServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.services; 2 | 3 | import java.io.IOException; 4 | import java.net.MalformedURLException; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.UUID; 8 | 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.core.io.Resource; 13 | import org.springframework.core.io.UrlResource; 14 | import org.springframework.stereotype.Service; 15 | import org.springframework.transaction.annotation.Transactional; 16 | import org.springframework.web.multipart.MultipartFile; 17 | 18 | import com.ecristobale.spring.boot.apirest.models.dao.IImgPerfilDao; 19 | import com.ecristobale.spring.boot.apirest.models.entity.ImgPerfil; 20 | 21 | @Service 22 | public class UploadFileServiceImpl implements IUploadFileService { 23 | 24 | @Autowired 25 | private IImgPerfilDao imgPerfilDao; 26 | 27 | // private static final String PATH_UPLOADS = "uploads"; 28 | private final Logger log = LoggerFactory.getLogger(UploadFileServiceImpl.class); 29 | 30 | // Load file (DB storage) 31 | @Override 32 | public ImgPerfil loadFile(String filename) throws MalformedURLException { 33 | return imgPerfilDao.findByFilename(filename); 34 | } 35 | 36 | @Override 37 | public Resource loadFileDefaultImage(String filename) throws MalformedURLException { 38 | Path filePath = Paths.get("src/main/resources/static/images").resolve("not-photo.png").toAbsolutePath(); 39 | Resource resource = new UrlResource(filePath.toUri()); 40 | log.error("Error al cargar la imagen: " + filename); 41 | return resource; 42 | } 43 | 44 | // Upload file (DB storage) 45 | @Override 46 | @Transactional 47 | public String uploadFile(MultipartFile file) throws IOException { 48 | String filename = UUID.randomUUID().toString() + "_" + file.getOriginalFilename().replace(" ", ""); 49 | ImgPerfil imgPerfil = new ImgPerfil(); 50 | imgPerfil.setFilename(filename); 51 | imgPerfil.setImg(file.getBytes()); 52 | imgPerfil.setFileType(file.getContentType()); 53 | imgPerfilDao.save(imgPerfil); 54 | log.info(filename); 55 | return filename; 56 | } 57 | 58 | @Override 59 | @Transactional 60 | public boolean deleteFile(String oldFilename) { 61 | if(oldFilename != null && oldFilename.length() > 0) { 62 | Long deleted = imgPerfilDao.deleteByFilename(oldFilename); 63 | return deleted == 1; 64 | } 65 | return false; 66 | } 67 | 68 | // Upload file (folder storage) 69 | // @Override 70 | // public String uploadFile(MultipartFile file) throws IOException { 71 | // String filename = UUID.randomUUID().toString() + "_" + file.getOriginalFilename().replace(" ", ""); 72 | // Path filePath = getPath(filename); 73 | // log.info(filePath.toString()); 74 | // Files.copy(file.getInputStream(), filePath); 75 | // return filename; 76 | // } 77 | 78 | // Load file (folder storage) 79 | // @Override 80 | // public Resource loadFile(String filename) throws MalformedURLException { 81 | // Path filePath = getPath(filename); 82 | // log.info(filePath.toString()); 83 | // Resource resource = new UrlResource(filePath.toUri()); 84 | // 85 | // if(!resource.exists() && !resource.isReadable()) { 86 | // filePath = Paths.get("src/main/resources/static/images").resolve("not-photo.png").toAbsolutePath(); 87 | // 88 | // resource = new UrlResource(filePath.toUri()); 89 | // 90 | // log.error("Error al cargar la imagen: " + filename); 91 | // } 92 | // return resource; 93 | // } 94 | 95 | // Delete file (folder storage) 96 | // @Override 97 | // public boolean deleteFile(String oldFilename) { 98 | // if(oldFilename != null && oldFilename.length() > 0) { 99 | // Path oldFilePath = Paths.get("uploads").resolve(oldFilename).toAbsolutePath(); 100 | // File oldPhotoFile = oldFilePath.toFile(); 101 | // if(oldPhotoFile.exists() && oldPhotoFile.canRead()) { 102 | // oldPhotoFile.delete(); 103 | // return true; 104 | // } 105 | // } 106 | // return false; 107 | // } 108 | 109 | // @Override 110 | // public Path getPath(String filename) { 111 | // // Relative path, for absolute: C://Temp//uploads .. \\opt\\uploads 112 | // return Paths.get(PATH_UPLOADS).resolve(filename).toAbsolutePath(); 113 | // } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/java/com/ecristobale/spring/boot/apirest/models/services/UsuarioService.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest.models.services; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.security.core.GrantedAuthority; 10 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 11 | import org.springframework.security.core.userdetails.User; 12 | import org.springframework.security.core.userdetails.UserDetails; 13 | import org.springframework.security.core.userdetails.UserDetailsService; 14 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 15 | import org.springframework.stereotype.Service; 16 | import org.springframework.transaction.annotation.Transactional; 17 | 18 | import com.ecristobale.spring.boot.apirest.models.dao.IUsuarioDao; 19 | import com.ecristobale.spring.boot.apirest.models.entity.Usuario; 20 | 21 | @Service 22 | public class UsuarioService implements UserDetailsService, IUsuarioService { 23 | 24 | @Autowired 25 | private IUsuarioDao usuarioDao; 26 | 27 | private Logger log = LoggerFactory.getLogger(UsuarioService.class); 28 | 29 | @Override 30 | @Transactional(readOnly = true) 31 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 32 | Usuario usuario = usuarioDao.findByUsername(username); 33 | 34 | if(usuario == null) { 35 | log.error("Error en el login: usuario: '" + username + "' inexistente"); 36 | throw new UsernameNotFoundException("Error en el login: usuario: '" + username + "' inexistente"); 37 | } 38 | 39 | List authorities = usuario.getRoles().stream() 40 | .map(role -> new SimpleGrantedAuthority(role.getNombre())) 41 | .peek(authority -> log.info("Role: " + authority.getAuthority())) 42 | .collect(Collectors.toList()); 43 | 44 | return new User(usuario.getUsername(), usuario.getPassword(), usuario.getEnabled(), true, true, true, authorities); 45 | } 46 | 47 | @Override 48 | @Transactional(readOnly = true) 49 | public Usuario findByUsername(String username) { 50 | return usuarioDao.findByUsername(username); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8081 2 | spring.datasource.url=jdbc:h2:mem:testdb 3 | spring.datasource.username=sa 4 | spring.datasource.password=password 5 | spring.datasource.driverClassName=org.h2.Driver 6 | spring.jpa.database-platform=org.hibernate.dialect.H2Dialect 7 | # H2 Console 8 | spring.h2.console.enabled=true 9 | spring.h2.console.path=/h2-console 10 | # Avoid Spring boot configuration to Hibernate to create your schema (use schema.sql) 11 | spring.jpa.hibernate.ddl-auto=none 12 | # Debug purposes 13 | spring.jpa.show-sql=true 14 | logging.level.org.hibernate.SQL=debug 15 | 16 | spring.jackson.time-zone=Europe/Madrid 17 | spring.jackson.locale=es_ES 18 | 19 | spring.servlet.multipart.max-file-size=10MB 20 | spring.servlet.multipart.max-request-size=10MB -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO regions (id, name) 2 | VALUES 3 | (1, 'Africa'), 4 | (2, 'Asia/Pacific'), 5 | (3, 'Europe'), 6 | (4, 'Latin America'), 7 | (5, 'North America'), 8 | (6, 'Middle East'); 9 | 10 | INSERT INTO clientes (nombre, apellido, email, created_at, region_id) 11 | VALUES 12 | ('Eduardo', 'Cristóbal', 'edu_ce_1988@hotmail.com', '2019-12-16 16:50:12.646', 3), 13 | ('Jonh', 'Doe', 'johndoe@gmail.com', '2019-12-16 16:51:12.646', 5), 14 | ('Cris', 'Doe', 'crisdoe@gmail.com', '2019-12-16 16:52:12.646', 5), 15 | ('Alex', 'Harrys', 'aharrys@gmail.com', '2020-01-30 23:52:12.646', 3), 16 | ('Trist', 'Adec', 'adctrist@gmail.com', '2020-01-30 23:52:12.646', 3), 17 | ('Matt', 'John', 'mj@gmail.com', '2020-01-30 23:52:12.646', 5), 18 | ('Harry', 'Patt', 'patt@gmail.com', '2020-01-30 23:52:12.646', 3), 19 | ('Mark', 'Lend', 'mlenders@gmail.com', '2020-01-30 23:52:12.646', 2), 20 | ('Tom', 'Jerr', 'jerryt@gmail.com', '2020-01-30 23:52:12.646', 5), 21 | ('Jony', 'Skinner', 'jskinner@gmail.com', '2020-01-30 23:52:12.646', 4), 22 | ('Paul', 'Golden', 'pgold@gmail.com', '2020-01-30 23:52:12.646', 2), 23 | ('Juan', 'Banin', 'jbann@gmail.com', '2020-01-30 23:52:12.646', 1), 24 | ('Stein', 'Faann', 'jbann1@gmail.com', '2020-01-30 23:52:12.646', 2), 25 | ('Marc', 'Born', 'jbann2@gmail.com', '2020-01-30 23:52:12.646', 3), 26 | ('Rob', 'Bjarn', 'jbann3@gmail.com', '2020-01-30 23:52:12.646', 4), 27 | ('Rober', 'Bib', 'jbann4@gmail.com', '2020-01-30 23:52:12.646', 5), 28 | ('Victor', 'Webber', 'jbann5@gmail.com', '2020-01-30 23:52:12.646', 6), 29 | ('Guille', 'Rest', 'jbann6@gmail.com', '2020-01-30 23:52:12.646', 1), 30 | ('Agus', 'Dak', 'jbann7@gmail.com', '2020-01-30 23:52:12.646', 2), 31 | ('Paula', 'Roberts', 'jban7n8@gmail.com', '2020-01-30 23:52:12.646', 3), 32 | ('Javi', 'Weah', 'jbann9@gmail.com', '2020-01-30 23:52:12.646', 4), 33 | ('Myriam', 'Bang', 'jbanna11@gmail.com', '2020-01-30 23:52:12.646', 5), 34 | ('Angy', 'First', 'jban7n22q@gmail.com', '2020-01-30 23:52:12.646', 6), 35 | ('Gustav', 'Orange', 'jba7nn33w@gmail.com', '2020-01-30 23:52:12.646', 1), 36 | ('Carlos', 'Support', 'jba7nn44e@gmail.com', '2020-01-30 23:52:12.646', 2), 37 | ('Manuel', 'Age', 'jba7n55nr@gmail.com', '2020-01-30 23:52:12.646', 3), 38 | ('David', 'Happy', 'jba777nnt@gmail.com', '2020-01-30 23:52:12.646', 4), 39 | ('Jorge', 'Broth', 'jbann66y@gmail.com', '2020-01-30 23:52:12.646', 5), 40 | ('Ale', 'Only', 'jb7an77nu@gmail.com', '2020-01-30 23:52:12.646', 6), 41 | ('Diego', 'Rememb', 'jba7t88nni@gmail.com', '2020-01-30 23:52:12.646', 1), 42 | ('Alberto', 'Part', 'jban799no@gmail.com', '2020-01-30 23:52:12.646', 2), 43 | ('Doraemon', 'Nice', 'jbann12p@gmail.com', '2020-01-30 23:52:12.646', 3), 44 | ('Adri', 'Laugh', 't@gma23il.com', '2020-01-30 23:52:12.646', 4), 45 | ('Alberto', 'Futur', 'jbann34f@gmail.com', '2020-01-30 23:52:12.646', 5), 46 | ('Carlos', 'Past', 'jban45ng@gmail.com', '2020-01-30 23:52:12.646', 6), 47 | ('Pablo', 'Frake', 'jba67n7nh@gmail.com', '2020-01-30 23:52:12.646', 1), 48 | ('Rivaul', 'Vohn', 'jba87nnj@gmail.com', '2020-01-30 23:52:12.646', 2), 49 | ('David', 'Mc Nult', 'jba98nnk@gmail.com', '2020-01-30 23:52:12.646', 3), 50 | ('Ignacio', 'Rememb', 'jban90nl@gmail.com', '2020-01-30 23:52:12.646', 4), 51 | ('Joan', 'Terret', 'jba09nnñ@gmail.com', '2020-01-30 23:52:12.646', 5), 52 | ('David', 'Flanagan', 'jba987nnz@gmail.com', '2020-01-30 23:52:12.646', 6), 53 | ('Fer', 'Growth', 'jba87nnx@gmail.com', '2020-01-30 23:52:12.646', 1), 54 | ('Laura', 'Kind', 'jba76nnc@gmail.com', '2020-01-30 23:52:12.646', 2), 55 | ('Marta', 'Craz', 'jba65nnv@gmail.com', '2020-01-30 23:52:12.646', 3), 56 | ('Danny', 'Self', 'jba54nnb@gmail.com', '2020-01-30 23:52:12.646', 4), 57 | ('Jose', 'Fred', 'jba437nnn@gmail.com', '2020-01-30 23:52:12.646', 5), 58 | ('Carlos', 'Hard', 'jba32nnm@gmail.com', '2020-01-30 23:52:12.646', 6), 59 | ('Lux', 'Cont', 'jba21nnqq@gmail.com', '2020-01-30 23:52:12.646', 1), 60 | ('Jinx', 'Explos', 'jbadnnwx@gmail.com', '2020-01-30 23:52:12.646', 2), 61 | ('Lucian', 'Funnk', 'jbangn6df@gmail.com', '2020-01-30 23:52:12.646', 3), 62 | ('Alistar', 'Rock', 'jbasnnty@gmail.com', '2020-01-30 23:52:12.646', 4), 63 | ('Jony', 'Marak', 'jbasnnhj@gmail.com', '2020-01-30 23:52:12.646', 5), 64 | ('Omar', 'Danc', 'jbacnnkj@gmail.com', '2020-01-30 23:52:12.646', 6), 65 | ('Oli', 'Champ', 'jbagnn6lk@gmail.com', '2020-01-30 23:52:12.646', 1), 66 | ('Mark', 'Streng', 'jbafnnñl@gmail.com', '2020-01-30 23:52:12.646', 2), 67 | ('Sivir', 'Lear', 'jbangnvo@gmail.com', '2020-01-30 23:52:12.646', 3), 68 | ('Ashe', 'Bann', 'jbahnnyx@gmail.com', '2020-01-30 23:52:12.646', 4), 69 | ('Ander', 'Ground', 'jbasdnn6mq@gmail.com', '2020-01-30 23:52:12.646', 5), 70 | ('Javi', 'Birs', 'jbajnnql@gmail.com', '2020-01-30 23:52:12.646', 6), 71 | ('Alex', 'Smell', 'jbasnnkqt@gmail.com', '2020-01-30 23:52:12.646', 1), 72 | ('Never', 'Virtual', 'jbann5oqz@gmail.com', '2020-01-30 23:52:12.646', 2), 73 | ('Shawn', 'Bye', 'jbannwqs@gmail.com', '2020-01-30 23:52:12.646', 3), 74 | ('Bart', 'Simpson', 'jbannaev@gmail.com', '2020-01-30 23:52:12.646', 4), 75 | ('Homer', 'Simpson', 'jba5nznrf@gmail.com', '2020-01-30 23:52:12.646', 5), 76 | ('Lisa', 'Simpson', 'jbanxnvf@gmail.com', '2020-01-30 23:52:12.646', 6), 77 | ('Marge', 'Simpson', 'jbacnnty@gmail.com', '2020-01-30 23:52:12.646', 1), 78 | ('Steve', 'Capt', 'jbanvnsdfg@gmail.com', '2020-01-30 23:52:12.646', 2), 79 | ('Roger', 'Contint', 'jbanhngsdf@gmail.com', '2020-01-30 23:52:12.646', 3), 80 | ('Rafa', 'Winr', 'jbanenddd@gmail.com', '2020-01-30 23:52:12.646', 4), 81 | ('Marcos', 'Overmars', 'jban25ngg@gmail.com', '2020-01-30 23:52:12.646', 5), 82 | ('Alberto', 'Ace', 'jba3nnqq@gmail.com', '2020-01-30 23:52:12.646', 6), 83 | ('Alen', 'Peternac', 'jban5nww@gmail.com', '2020-01-30 23:52:12.646', 1), 84 | ('Victor', 'Fernandez', 'jban63nee@gmail.com', '2020-01-30 23:52:12.646', 2), 85 | ('John', 'Ascit', 'jban7n3rr@gmail.com', '2020-01-30 23:52:12.646', 3), 86 | ('Juanma', 'Chrismore', 'jba8n5n3tt@gmail.com', '2020-01-30 23:52:12.646', 4), 87 | ('Juanpe', 'Beach', 'jba9nnyy@gmail.com', '2020-01-30 23:52:12.646', 5), 88 | ('Ismael', 'Cry', 'jba0nnu3u@gmail.com', '2020-01-30 23:52:12.646', 6), 89 | ('Miguel', 'Sern', 'jba1nnii@3gmail.com', '2020-01-30 23:52:12.646', 1), 90 | ('Marta', 'Time', 'jbabnnuu@gmail.com', '2020-01-30 23:52:12.646', 2), 91 | ('Vicent', 'More', 'jbafnniii3@gmail.com', '2020-01-30 23:52:12.646', 3), 92 | ('Samanta', 'Goes', 'jbaddnn@g3ggmail.com', '2020-01-30 23:52:12.646', 4), 93 | ('Elsa', 'Sur', 'jbadnnsdf3gg@gmail.com', '2020-01-30 23:52:12.646', 5), 94 | ('Lucia', 'Name', 'jbassnngd3fg@gmail.com', '2020-01-30 23:52:12.646', 6), 95 | ('Inma', 'Smith', 'jbanaansfdg3sdf@gmail.com', '2020-01-30 23:52:12.646', 1), 96 | ('Kobe', 'Legend', 'jbannaasdfgs3dfg@gmail.com', '2020-01-30 23:52:12.646', 2); 97 | 98 | INSERT INTO usuarios (username, password, enabled) 99 | VALUES 100 | ('eduardo', '$2a$10$LhX3sOD9hJnO4HYwEdmKuOW3JYCh/CPFRYxW7R2whwetfIV/wZdqq', 1), 101 | ('admin', '$2a$10$8CmHTgDYdCgFC6VHahNGgugnIOY/LiC37L1jaK2vmu4MJUPzDKTlS', 1); 102 | 103 | INSERT INTO roles (nombre) 104 | VALUES 105 | ('ROLE_USER'), 106 | ('ROLE_ADMIN'); 107 | 108 | INSERT INTO usuarios_roles (usuario_id, role_id) 109 | VALUES 110 | (1, 1), 111 | (2, 1), 112 | (2, 2); 113 | 114 | -- SELECT * FROM usuarios u LEFT JOIN usuarios_roles ur ON u.id = ur.usuario_id LEFT JOIN roles r ON ur.role_id = r.id; -- see users & roles 115 | 116 | /* Populate tabla productos */ 117 | INSERT INTO productos (nombre, precio, created_at) 118 | VALUES 119 | ('Panasonic Pantalla LCD', 259990, NOW()), 120 | ('Sony Camara digital DSC-W320B', 123490, NOW()), 121 | ('Apple iPod shuffle', 1499990, NOW()), 122 | ('Sony Notebook Z110', 37990, NOW()), 123 | ('Hewlett Packard Multifuncional F2280', 69990, NOW()), 124 | ('Bianchi Bicicleta Aro 26', 69990, NOW()), 125 | ('Mica Comoda 5 Cajones', 299990, NOW()); 126 | 127 | /* Creamos algunas facturas */ 128 | INSERT INTO facturas (descripcion, observacion, cliente_id, created_at) 129 | VALUES 130 | ('Factura equipos de oficina', null, 1, NOW()), 131 | ('Factura Bicicleta', 'Alguna nota importante!', 1, NOW()); 132 | 133 | INSERT INTO facturas_items (cantidad, factura_id, producto_id) 134 | VALUES 135 | (1, 1, 1), 136 | (2, 1, 4), 137 | (1, 1, 5), 138 | (1, 1, 7), 139 | (3, 2, 6); -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/resources/schema.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE IF EXISTS regions; 2 | 3 | CREATE TABLE regions( 4 | id BIGINT AUTO_INCREMENT PRIMARY KEY, 5 | name VARCHAR (250) 6 | ); 7 | 8 | DROP TABLE IF EXISTS clientes; 9 | 10 | CREATE TABLE clientes( 11 | id BIGINT AUTO_INCREMENT PRIMARY KEY, 12 | nombre VARCHAR (250) NOT NULL, 13 | apellido VARCHAR (250) NOT NULL, 14 | email VARCHAR (250) NOT NULL UNIQUE, 15 | created_at TIMESTAMP NOT NULL, 16 | photo VARCHAR (250), 17 | region_id BIGINT NOT NULL, 18 | FOREIGN KEY (region_id) REFERENCES regions 19 | ); 20 | 21 | DROP TABLE IF EXISTS facturas; 22 | 23 | CREATE TABLE facturas( 24 | id BIGINT AUTO_INCREMENT PRIMARY KEY, 25 | descripcion VARCHAR (250), 26 | observacion VARCHAR (250), 27 | created_at DATE, 28 | cliente_id BIGINT NOT NULL, 29 | FOREIGN KEY (cliente_id) REFERENCES clientes 30 | ); 31 | 32 | DROP TABLE IF EXISTS productos; 33 | 34 | CREATE TABLE productos( 35 | id BIGINT AUTO_INCREMENT PRIMARY KEY, 36 | nombre VARCHAR (250), 37 | precio DOUBLE, 38 | created_at TIMESTAMP NOT NULL 39 | ); 40 | 41 | DROP TABLE IF EXISTS facturas_items; 42 | 43 | CREATE TABLE facturas_items( 44 | id BIGINT AUTO_INCREMENT PRIMARY KEY, 45 | cantidad BIGINT, 46 | factura_id BIGINT, 47 | producto_id BIGINT NOT NULL, 48 | FOREIGN KEY (factura_id) REFERENCES facturas, 49 | FOREIGN KEY (producto_id) REFERENCES productos 50 | ); 51 | 52 | DROP TABLE IF EXISTS img_perfiles; 53 | 54 | CREATE TABLE img_perfiles( 55 | id BIGINT AUTO_INCREMENT PRIMARY KEY, 56 | filename VARCHAR (250) NOT NULL UNIQUE, 57 | file_type VARCHAR (250) NOT NULL, 58 | img BLOB NOT NULL 59 | ); 60 | 61 | DROP TABLE IF EXISTS roles; 62 | DROP TABLE IF EXISTS usuarios; 63 | DROP TABLE IF EXISTS usuarios_roles; 64 | 65 | CREATE TABLE roles( 66 | id BIGINT AUTO_INCREMENT PRIMARY KEY, 67 | nombre VARCHAR (30) UNIQUE 68 | ); 69 | 70 | CREATE TABLE usuarios( 71 | id BIGINT AUTO_INCREMENT PRIMARY KEY, 72 | enabled BOOLEAN, 73 | username VARCHAR (20) UNIQUE, 74 | password VARCHAR (60) 75 | ); 76 | 77 | CREATE TABLE usuarios_roles( 78 | usuario_id BIGINT NOT NULL, 79 | role_id BIGINT NOT NULL, 80 | PRIMARY KEY (usuario_id, role_id), 81 | FOREIGN KEY (role_id) REFERENCES roles, 82 | FOREIGN KEY (usuario_id) REFERENCES usuarios 83 | ); 84 | -------------------------------------------------------------------------------- /spring-boot-apirest/src/main/resources/static/images/not-photo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/spring-boot-apirest/src/main/resources/static/images/not-photo.png -------------------------------------------------------------------------------- /spring-boot-apirest/src/test/java/com/ecristobale/spring/boot/apirest/SpringBootApirestApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.ecristobale.spring.boot.apirest; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class SpringBootApirestApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /web-app-screenshots/Logout_action.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/Logout_action.PNG -------------------------------------------------------------------------------- /web-app-screenshots/admin_client_details.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/admin_client_details.PNG -------------------------------------------------------------------------------- /web-app-screenshots/admin_client_photo_uploaded_with_progress_bar.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/admin_client_photo_uploaded_with_progress_bar.PNG -------------------------------------------------------------------------------- /web-app-screenshots/admin_form_new_invoice_validating_fields_autocomplete_product.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/admin_form_new_invoice_validating_fields_autocomplete_product.PNG -------------------------------------------------------------------------------- /web-app-screenshots/admin_main_page.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/admin_main_page.PNG -------------------------------------------------------------------------------- /web-app-screenshots/area_restrictions_based_on_roles.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/area_restrictions_based_on_roles.PNG -------------------------------------------------------------------------------- /web-app-screenshots/create_new_user_form_validation.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/create_new_user_form_validation.PNG -------------------------------------------------------------------------------- /web-app-screenshots/invoice_detail.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/invoice_detail.PNG -------------------------------------------------------------------------------- /web-app-screenshots/login_page.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/login_page.PNG -------------------------------------------------------------------------------- /web-app-screenshots/main_page.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/main_page.PNG -------------------------------------------------------------------------------- /web-app-screenshots/update_user_form.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/update_user_form.PNG -------------------------------------------------------------------------------- /web-app-screenshots/user_client_details.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/user_client_details.PNG -------------------------------------------------------------------------------- /web-app-screenshots/user_invoice_detail.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/user_invoice_detail.PNG -------------------------------------------------------------------------------- /web-app-screenshots/user_main_page.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecristobale/web-app-full-stack/5acc3d7cd5961cd8958a8f26c5ca5e77eb7c2d65/web-app-screenshots/user_main_page.PNG --------------------------------------------------------------------------------