niedziela, 9 grudnia 2018

Uploading files in JHipster app

When you trying to add uploading files using this guide walks: https://spring.io/guides/gs/uploading-files/, you may see that kind of errors:


***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in finbarre.storage.FileSystemStorageService required a bean of type 'finbarre.storage.StorageProperties' that could not be found.


Action:

Consider defining a bean of type 'finbarre.storage.StorageProperties' in your configuration.



To fix it, add @Component annotation to StorageProperties class:



package finbarre.storage;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties("storage")
public class StorageProperties {

    /**
     * Folder location for storing files
     */
    private String location = "upload-dir";

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

}

środa, 7 listopada 2018

How to deploy simple Angular page on AWS with MEAN AMI and secure it with HTTPS

Let assume you have:
  • Your Angular app built with   ng build --prod
  • AWS account
  • Registered domain


Go to  https://console.aws.amazon.com/ec2/ , launch new instance.

On page Choose an Amazon Machine Image search for angular, select MEAN Certified by Bitnami.



Run this instance.

Obtain password for your linux instance from Instances - Actions - Instance settings - Get System log - look for

[   35.807016] bitnami[1112]: #########################################################################
[   35.832098] bitnami[1112]: #                                                                       #
[   35.853029] bitnami[1112]: #        Setting Bitnami application password to *************************         #
[   35.872600] bitnami[1112]: #        (the default application username is 'root')                   #
[   35.894473] bitnami[1112]: #                                                                       #
[   35.908585] bitnami[1112]: #########################################################################

Username is ubuntu however.

Login to your instance with Filezilla, go to /opt/bitnami/apache2/htdocs and copy there angular files from /dist/your-app folder.

Edit /opt/bitnami/apache2/conf/bitnami/bitnami.conf:
In <VirtualHost _default_:80> section add:

 RewriteEngine On
 RewriteCond %{HTTP:X-Forwarded-Proto} =http
 RewriteRule . https://barfitter.net[L,R=permanent]

And comment out all SSL lines, like Listen 443, <VirtualHost _default_:443> section, etc.

Save and restart apache:
sudo /opt/bitnami/ctlscript.sh restart apache

Now go to AWS page, Route 53, create or change your domain settings:
Type A, Alias: Yes, Alias target: choose your instance.

Go to EC2 - Load balancer - create new Application Load Balancer and follow https://docs.bitnami.com/aws/how-to/configure-elb-ssl-aws/



Redirect www.domain.com to domain.com

Edit /opt/bitnami/apache2/conf/bitnami/bitnami.conf:

In <VirtualHost _default_:80> section add:
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://%1$1 [R=permanent,L]

and in Route 53, create new record set:
Name: www.domain.com,
Type A, Alias: Yes, Alias target: choose your instance.

wtorek, 23 października 2018

How to redirect http to https in Spring Boot JHipster app

Here is how to redirect all traffic to https.

Let's assume in application-prod.yml file got:


server:
    port: 443
    compression:
        enabled: true
        mime-types: text/html,text/xml,text/plain,text/css, application/javascript, application/json
        min-response-size: 1024


In SecurityConfiguration.java add:

        @Value("${spring.profiles.active}")
 private String activeProfile; 

then in configure(HttpSecurity http) method add:


        if(activeProfile=="prod") {
         http.requiresChannel().anyRequest().requiresSecure()
            .and()
                .portMapper()               
                .http(80).mapsTo(443);
        }

Without activeProfile condition, in dev profile it generates ERR_TOO_MANY_REDIRECTS error.





wtorek, 28 sierpnia 2018

How to add reCaptcha to Angular 5 Spring Boot app

Here are a few steps how to add Google reCaptcha to JHipster app.


Let's assume that you have already a domain - it’s not possible to do it in test environment.


And choose reCaptcha v.2 [Validate requests with the “I’m not a robot” checkbox].


You’ll get site key like ‘6LfedWkUhkjgkyUGkjhg1OxiWuJVu7_2PWnFID68’.

In index.html file add:

<script src='https://www.google.com/recaptcha/api.js?render=explicit" async defer'></script>



In register.component.html file add:


<div #recaptchaDiv></div>


Change:

<button type="submit" [disabled]="registerForm.form.invalid" class="btn btn-primary" jhiTranslate="register.form.button">Register</button>

to:

<button type="submit" [disabled]="registerForm.form.invalid || !recaptchaVerified" class="btn btn-primary" jhiTranslate="register.form.button">Register</button>


In register.component.ts file add on top:


  recaptchaVerified: boolean;
  errormsg: string;
  @ViewChild('recaptchaDiv') recaptchaDiv: ElementRef;
  private _reCaptchaId: number;
  private SITE_ID = '6LfedWkUhkjgkyUGkjhg1OxiWuJVu7_2PWnFID68';
  window['onloadCallback'] = this.onloadCallback.bind(this);

In ngOnInit() add:
this.recaptchaVerified = false;

Then add 3 methods:


  onloadCallback(response) {
//    console.log('verifyCallback=' + response);
    const grecaptcha = (window as any).grecaptcha;
    if (grecaptcha) {
      this._reCaptchaId = grecaptcha.render(this.recaptchaDiv.nativeElement, {
        'sitekey': this.SITE_ID,
        'callback': (resonse) => this.reCapchaSuccess(resonse),
        'expired-callback': () => this.reCapchaExpired()
      });
    }
  }

  reCapchaSuccess(data: any) {
    if (data) {
//      console.log('Congratulation! reCAPTCHA verified.');
      this.recaptchaVerified = true;
    }
  }

  reCapchaExpired() {
//    console.log('Oops! reCAPTCHA expired.');
    this.recaptchaVerified = false;
  }


Thanks to: https://stackoverflow.com/questions/48902711/how-to-add-recaptcha-in-angular-2-application

piątek, 6 lipca 2018

How to setup Let's Encrypt certyficate on JHipster Spring Boot app on Tomcat 8

Prequisitions
Let’s assume you have:

  • Spring boot app deployed on tomcat on path ~/tomcat/webapps/myApp
  • Your domain is pointing on IP of your server
  • Port 80 is redirected to 8080 - you can do it by:

sudo iptables -A PREROUTING -t nat -p tcp --dport 80 -j REDIRECT --to-ports 8080
sudo apt-get install iptables-persistent


  • You have host defined in server.xml like:
     <Host name="myApp.com" appBase="webapps" unpackWARs="false" autoDeploy="false">
    <Alias>www.myApp.com</Alias>
    <Context path="" docBase="/opt/tomcat/webapps/myApp" debug="0" privileged="true" />
    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" 
    prefix="myApp_access_log." suffix=".txt" 
    pattern="%h %l %u %t &quot;%r&quot; %s %b" resolveHosts="false" />
    </Host>
    

So finally address www.myApp.biz points directly to ~/tomcat/webapps/myApp.
More details here: https://codefitter2.blogspot.com/2018/07/how-to-deploy-spring-boot-jhipster-app.html



Generate Let’s Encrypt certificate
Install Certbot:
$ sudo apt-get update
$ sudo apt-get install software-properties-common
$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt-get update
$ sudo apt-get install python-certbot-apache
Then:
sudo certbot certonly --webroot -w ~/tomcat/webapps/myApp -d myApp.biz,www.myApp.biz

You should see:



IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
...

Redirect ports for https:
sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8443

Now you can see iptables list:
sudo iptables -t nat -L --line-numbers

and remove some line if necessary with
sudo iptables -t nat -D PREROUTING 1
where 1 at the end is line number

-----------------------------
Configure apache:
Edit /etc/apache2/sites-available/default-ssl.conf:
Add:
  ServerAdmin youremail@myApp.biz
  ServerName myApp.biz

...
  SSLCertificateFile /etc/letsencrypt/live/myApp.biz/fullchain.pem
  SSLCertificateKeyFile   /etc/letsencrypt/live/myApp.biz/privkey.pem
  SSLCertificateChainFile /etc/letsencrypt/live/myApp.biz/chain.pem

...


Enable the SSL module:
sudo a2enmod ssl

Enable the site just edited:
sudo a2ensite default-ssl.conf

Restart Apache:
sudo service apache2 restart



Now, redirect http to https.
In server.xml add:

    <Connector port="8080"
           enableLookups="false"
           redirectPort="443" />

    <Connector port="443" protocol="HTTP/1.1"
           enableLookups="false"
           redirectPort="8443" />

In web.xml add:
<security-constraint>
  <web-resource-collection>
    <web-resource-name>Restricted URLs</web-resource-name>
    <url-pattern>/*</url-pattern>
  </web-resource-collection>
  <user-data-constraint>
    <transport-guarantee>CONFIDENTIAL</transport-guarantee>
  </user-data-constraint>
</security-constraint>


On AWS EC2 -> Instances - Security groups click view inbound rules and make sure port 443 is available.

poniedziałek, 2 lipca 2018

How to deploy Spring Boot, JHipster app to tomcat 8 and redirect domain to this app

This is, how to do it on Ubuntu 16 on AWS EC2.


  1. In /opt/tomcat/webapps/ create myApp folder [assuming you have myApp.war file to deploy]
  2. Redirect your domain to ip of your server.
  3. Redirect port 8080 to 80:
    sudo iptables -A PREROUTING -t nat -p tcp --dport 80 -j REDIRECT --to-ports 8080
    
    And make it persistent:
    sudo apt-get install iptables-persistent
    
  4. For now, copy to /opt/tomcat/webapps/myApp index.jsp from /opt/tomcat/webapps/ROOT.
  5. Change ownership of /opt/tomcat/webapps/myApp and its content to tomcat
  6. In /opt/tomcat/conf/server.xml, before </Engine> tag, add:
     <Host name="myApp.com" appBase="webapps" unpackWARs="false" autoDeploy="false">
    <Alias>www.myApp.com</Alias>
    <Context path="" docBase="/opt/tomcat/webapps/myApp" debug="0" privileged="true" />
    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" 
    prefix="myApp_access_log." suffix=".txt" 
    pattern="%h %l %u %t &quot;%r&quot; %s %b" resolveHosts="false" />
    </Host>
    
  7. sudo systemctl restart tomcat
  8. Go to www.myApp.com and you should see tomcat home page, as it was copied in point 5.
  9. Copy myApp.war to /opt/tomcat/webapps/ - it will override existing files and deploy your app


Points 5-10 are necessarily, because tomcat seeing your app in server.xml Host section, trying to redeploy it, causing hang.

czwartek, 28 czerwca 2018

How to update database in JHipster

After entity update, run:

./mvnw liquibase:diff

then

for dev database:

./mvnw liquibase:clearCheckSums



for prod database find in pom.xml:

<changeLogFile>src/main/resources/config/liquibase/master.xml</changeLogFile>
                    <diffChangeLogFile>src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml</diffChangeLogFile>
                    <driver>com.mysql.jdbc.Driver</driver>
                    <url>jdbc:mysql://xxxxxxxxx.com:3306/dbase-dev</url>
                    <defaultSchemaName>dbase-dev</defaultSchemaName> 


change <url> and <defaultSchemaName> to production database:


<changeLogFile>src/main/resources/config/liquibase/master.xml</changeLogFile>
                    <diffChangeLogFile>src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml</diffChangeLogFile>
                    <driver>com.mysql.jdbc.Driver</driver>
                    <url>jdbc:mysql://xxxxxxxxx.com:3306/dbase-prod</url>
                    <defaultSchemaName>dbase-prod</defaultSchemaName> 

and run:

./mvnw liquibase:clearCheckSums


After all change pom.xml to dev.