Gnome-shell stop alt-tab grouping

https://superuser.com/questions/394376/how-to-prevent-gnome-shells-alttab-from-grouping-windows-from-similar-apps/481202

  • Open dconf-editor
  • Go to org/gnome/desktop/wm/keybindings
  • Move the value '<Alt>Tab' from switch-applications to switch-windows
  • Optionally move '<Shift><Alt>Tab' from switch-applications-backward to switch-windows-backward
  • If you want switch-windows to work across desktops, not just in the current desktop, you can also uncheck org/gnome/shell/window-switcher/current-workspace-only (Courtesy of @CharlBotha)
  • Close dconf-editor
  • Press <Alt>F2, then type r to restart Gnome.

The last step does not always appear to be necessary, but it should not hurt (especially since it does not close any of your running applications).

Anúncios

Summary of Josh Long Youtube video about Security OAuth and other resources for OAuth in Spring

About the video in: https://www.youtube.com/watch?v=EoK5a99Bmjc&list=WL&index=12

After the description of the video I specify on how to use a separate Resource server that “authenticates” against the Authorization server, also specify about the token store usage and an Example on how to do a @Query using the Authenticated user has a filter.

First go to spring Initializr

In the dependencies you will place “Cloud OAuth2”, “Web”, “JPA”, “H2”, “Lombok”

Artifact has “auth-service”

Hit(click) Generate

Download and Extract the file into a directory.

Open your editor (idea will point to pom.xml )

In file resources/application.properties he setup the service name

spring.application.name=auth-service

# Ideally you use a config server in a micro service architecture

# Set the server port to 9191

server.port=9091

# Set the contextPath from where all the oauth requests will be served

server.contextPath=/waa

# No explanation for the bellow see the following Url http://www.baeldung.com/spring-security-session

security.sessions=if-required

Will now create on the AuthServiceApplication a Entity Account

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
class Account {
   @Id @GeneratedValue
   private Long id;

   private String username;

   private String password;

   private boolean active;
public Account(String username, String password, boolean active) {
   this.username = username;
   this.password = password;
   this.active = active;
}
}

Now he creates a Interface to Manage the Repository interface AccountRepository extends JpaRepository<Account, Long>

interface AccountRepository extends JpaRepository<Account, Long> {
   
}

Now he will persist some usernames to the database so he will create a CommandLineRunner

@SpringBootApplication
public class AuthServiceApplication {
   @Bean
   CommandLineRunner demo (AccountRepository accountRepository){
      return args-> Stream.of("jlong,spring", "dsier,cloud").map(tpl -> tpl.split(","))
            .forEach(tpl -> accountRepository.save(new Account(tpl[0], tpl[1], true)));
   }

   public static void main(String[] args) {
      SpringApplication.run(AuthServiceApplication.class, args);
   }
}

He also added a constructor to the Account Entity I placed it above in the Entity

Now he teaches Spring Security about our database, with an implementation of UserDetailsService, this Interface is a method of how Spring Security will “transform” our internal Account into a User understandable Username Password and all other details related to Spring Security.

loadByUsername also expects a Exception of type UsernameNotFoundException to be thrown in case the username is not found.

@Service
class AccountUserDetailService implements UserDetailsService {


   private final AccountRepository accountRepository;

   public AccountUserDetailService(AccountRepository accountRepository) {
      this.accountRepository = accountRepository;
   }

   @Override
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      return accountRepository.findByUsername(username).map(account -> new User(account.getUsername(), account.getPassword(),
            account.isActive(), account.isActive(), account.isActive(), account.isActive(),
            AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN")))
            .orElseThrow( () -> new UsernameNotFoundException("Could not find the username "+ username +" ."));
   }
}

In the next step he informs OAuth service how he will delegate the authorization step into the Spring Security using AuthServiceConfiguration

@Configuration
@EnableAuthorizationServer
class AuthServiceConfiguration extends AuthorizationServerConfigurerAdapter {

   private final AuthenticationManager authenticationManager;

   AuthServiceConfiguration(AuthenticationManager authenticationManager) {
      this.authenticationManager = authenticationManager;
   }

   /**
    * Specify what clients we want to authorize
    *
    * @param clients
    * @throws Exception
    */
   @Override
   public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
      clients.inMemory()
            .withClient("html5")
            .secret("password")
            .authorizedGrantTypes("password")
            .scopes("openId");
   }

   /**
    * indicate what authentication manager we want to use
    *
    * @param endpoints
    * @throws Exception
    */
   @Override
   public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
      endpoints.authenticationManager(authenticationManager);
   }
}

 

And now he runs the application.

Also https://gigsterous.github.io/engineering/2017/03/01/spring-boot-4.html has some aditional explanation.

Even more  https://spring.io/guides/tutorials/spring-boot-oauth2/

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-security.html

Setup a Resource Server separate from the Authorization Server

I’ve managed to setup a Resource Server separated from the Authorization server it’s very easy, just placing the annotation in the main class @EnableResourceServer and in application.properties specify the URI of the user information in the remote Authorization Server.

security.oauth2.resource.userInfoUri=http://localhost:9191/uaa/user

This /user address has to be setup in the Authorization Server of Long example like so:

@RequestMapping("/user")
public Principal user(Principal user) {
   return user;
}

This is placed inside the AuthServiceApplication class. And have to place the class AuthServiceApplication has a @RestController

New code will look like this:

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.security.Principal;
import java.util.stream.Stream;

import far.botshop.security.backend.authservice.entity.*;
import far.botshop.security.backend.authservice.repository.*;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableResourceServer
@RestController
public class AuthServiceApplication {

   @Bean
   CommandLineRunner demo (AccountRepository accountRepository){
      return args-> Stream.of("jlong,spring", "dsier,cloud").map(tpl -> tpl.split(","))
            .forEach(tpl -> {
               accountRepository.save(new Account(tpl[0], tpl[1], true));
            });
   }

   public static void main(String[] args) {
      SpringApplication.run(AuthServiceApplication.class, args);
   }

   @RequestMapping("/user")
   public Principal user(Principal user) {
      return user;
   }
}

 

The authentication against the Resource Server is made using the token obtained from the Authorization server has previous examples from Long.

curl -X GET "http://localhost:8080/products" -H "Authorization: Bearer 22e70fcf-eb60-483c-9105-xxxx"

That’s it. Now for a JdbcTokenStore so the tokens can be reused…

First in the auth-service we create the dataSource and storeToken

@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
 DataSource tokenDataSource = DataSourceBuilder.create()
 /*
 .driverClassName(oauthClass)
 .username("root")
 .password("")
I used a JDBC URL and ignored this from the example I got
 */
 .url(System.getenv().get("JDBC_DATABASE_URL")) // Here I'm using a JDBC url
 .build();
 return new JdbcTokenStore(tokenDataSource);
}

We change the configure method to use the tokenStore

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(authenticationManager);
    endpoints.userDetailsService(accountUserDetailService);
    endpoints.tokenStore(tokenStore());
}

Add the two tables that will have the tokens stored into them, if your using Postgresql I replaced the Blob type for a bytea type.

create table oauth_access_token (
  token_id VARCHAR(256),
  token BLOB,
  authentication_id VARCHAR(256) PRIMARY KEY,
  user_name VARCHAR(256),
  client_id VARCHAR(256),
  authentication BLOB,
  refresh_token VARCHAR(256)
);

create table oauth_refresh_token (
  token_id VARCHAR(256),
  token BLOB,
  authentication BLOB
);


Remove the CommandLineRunner @Bean from the AuthServiceApplication class.
Create the account table in the SQL Storage your using or place this

spring.jpa.hibernate.ddl-auto=update

in resources/application.properties if you do it the table will be create automatically on the system boot. If not you have to create it by hand.

This bellow was for postgresql

\d account
Table “public.account”
Column | Type | Modifiers
———-+————————+———–
id | bigint | not null
active | boolean | not null
password | character varying(255) |
username | character varying(255) |
Indexes:
“account_pkey” PRIMARY KEY, btree (id)

I was provided with the following link in freenode to github that has the full DB schema for the oauth part.

https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/test/resources/schema.sql

Missing in this is the encoding of the User password…

For user jlong password spring

update account set password = ‘$2a$06$.D77Cpf92IZx/L84TUiVAuqTAcV9F1MUblFL26COWDNlvb6dFVCVu’ where id = 1;
UPDATE 1

For password cloud

update account set password = ‘$2a$06$iDAlgXOdcZX1Wm8j0KR1rOi1XyQprLsc78RwH2ikn0to9W9HzM5ci’ where id = 2;
UPDATE 1

Generated using http://bcrypthashgenerator.apphb.com/?PlainText=cloud

Uncomment the

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

in

public class AuthServiceConfiguration extends AuthorizationServerConfigurerAdapter {

And had to remove the constructor I had accepting the authenticationManager, and left it only to be inserted by Autowire.

Getting the Principal on the Resource Server…Using the Principal (Active User)to limit the data returned:

Using the Principal on the Resource Server , for this I had to extend the User Object to my own implementation, I didn’t want to touch to much on the Database side of Accounts so I created a new Object UserInfo

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;

public class UserInfo extends User {

    private Long Id;

    public UserInfo(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, Long id) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        Id = id;
    }

    public Long getId() {
        return Id;
    }
}

Has seen this above has a aditional field Id wich I use to relate the Account to the item being managed in the Resource Server (I’m also returning Roles in this (done by default)). To the Account Entity I added the following method and private class to manage the GrantedAuthority types.

public UserInfo getUser() {
    List authorities = new ArrayList();

    authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));

    return new UserInfo(this.getUsername(), this.getPassword(), this.isActive(), this.isActive(), this.isActive(),
            this.isActive(), authorities, this.id);
}

private class GrantedAuthorityImpl implements GrantedAuthority {

    private String auth;

    public GrantedAuthorityImpl(String auth) {
        this.auth = auth;
    }

    @Override
    public String getAuthority() {
        return auth;
    }
}

And in the AccountUserDetailService.java I changed what was returned in the loadByUsername method.

return ac.map(account ->
        account.getUser()
    ).orElseThrow( () -> new UsernameNotFoundException("Could not find the username "+ username +" ."));

For my case this is all I need in the Authorization Server.

Extracting the Principal in the Resource Server

http://javahotpot.blogspot.com.br/2013/12/spring-security-adding-more-information.html

I had to place my custom UserInfo in the ResourceServer

public class UserInfo {

    private String id;

    private String username;

    private String email;

    public String getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id.toString();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Username: " + this.getUsername() + " ID: " + this.getId();
    }
}

And created an Extractor PrincipalExtractor Implementation to retrieve this new representation on the Resource Server

import far.botshop.backend.model.UserInfo;
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class myPrincipalExtractor implements PrincipalExtractor {

    @Override
    public UserInfo extractPrincipal(Map<String, Object> map) {

        Map<String,Object> principal = null;

        if (map.containsKey("principal")) {
            principal = (Map<String, Object>) map.get("principal");
        }

        UserInfo user = new UserInfo();

        if (principal != null ) {
            if (principal.containsKey("id")) {
                user.setId(Long.parseLong(principal.get("id").toString()));
            }

            if (principal.containsKey("username")) {
                user.setUsername(principal.get("username").toString());
            }

            if (principal.containsKey("email")) {
                user.setEmail(principal.get("email").toString());
            }
        }

        System.out.println("----> " + user.getUsername() + " -> " + user.getId());

        return user;
    }
}

 

Using the Principal in the @Query annotation of the Repository to filter only items related to this Account.

For this one I had a few hiccups… https://stackoverflow.com/questions/45901014/spring-using-spel-principal

https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions

I created the SecurityEvaluationContextExtension you can read the details on the link above.

@Service
public class SecurityEvaluationContextExtension extends EvaluationContextExtensionSupport {

    @Override
    public String getExtensionId() {
        return "security";
    }

    @Override
    public SecurityExpressionRoot getRootObject() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        System.out.println("SER >>>>> " + authentication.getPrincipal().toString() + " -- " );

        return new SecurityExpressionRoot(authentication) {
            @Override
            public UserInfo getPrincipal() {
                System.out.println("Fetching the principal has user " + authentication.getPrincipal().toString());
                return (UserInfo) authentication.getPrincipal();
            }
        };
    }
}
@Configuration
@EnableJpaRepositories
public class SecurityConfiguration {

    @Bean
    EvaluationContextExtension securityExtension() {
        return new SecurityEvaluationContextExtension();
    }

}

And the related Repository and Query

@CrossOrigin
public interface StoreRepository extends CrudRepository<Store, Long>
{
    @Query("select p , p.store, p.category from Product p JOIN p.store s " +
            " JOIN p.category c " +
            " WHERE p.store.id = :id AND p.keywords LIKE %:keyword% AND p.store.ownerId = ?#{#security.principal.id} ")
    List<Product> findByKeywordIgnoreCase(@Param("id") Long id , @Param("keyword") String keyword);
}

This #security.principal is not in the main docs but I’ve been told in Twitter by JPA Lead Developer ( Oliver Gierke @olivergierke ) that it can be a related bug solved in version 2.x of DATA JPA details in the stackoverflow link.

That’s it, if you do the Authentication to the authorization server and use the Bearer token to access the Resource Server you should have access to your Resource.

Side Note: Make gnome-shell only alt+tab between current window apps

There is a Gnome Shell extension that does this: Alt Tab Workspace.

You could also directly enable this behavior in the default switcher by running:

gsettings set org.gnome.shell.app-switcher current-workspace-only true

which is what the extension does under the hood.

 

 

https://askubuntu.com/questions/54994/force-alttab-show-only-active-desktop-apps-in-gnome-shell

 

Enable Gnome-shell resize on alt+right click

https://unix.stackexchange.com/questions/28514/how-to-get-altright-mouse-to-resize-windows-again

Java and Scala Dynamic Load of a Class

I was in the need to dynamically create a Object from the Database and execute a method to run a task. This object can be different based on the requirements from user input.

/**
  * Handle Execution returned from database
  *
  * @param ex
  * @param text
  * @param sender
  */
def handleExecution(ex: Execution, text: String, sender: Sender): Unit = {

  if (ex.execution.split(":").size == 3 ) {
    val cname = ex.execution.split(":")(1)
    val fname = ex.execution.split(":")(2)

    try {
      val theclass = Class.forName(cname).newInstance().asInstanceOf[TExecutionService]

      if (theclass.isInstanceOf[TExecutionService]) {
        val output = theclass.run(text)
        Logger.debug("Output from " + cname + ".run " + text + " -- " + output)
        handleOutput(output, sender)
      }
    } catch {
      case exception: Throwable => {
        Logger.debug("Error in HandleExecution " + ex + " with exception " + exception)
        throw exception
      }
    }
  }

 

Although Scala is a Typed Language it was not difficult to assure that I would have a run method for the returned class and execute this code dynamically.

 

Playframework 2.5.0 and slick Log SQL Statements/Queries

In playframework 2.5.x in your logback.xml file add the following line.

<logger name="slick.jdbc.JdbcBackend.statement" level="DEBUG" />

Playframework 2.5. correct postgres configuration

In application.conf at the end of the file do:

slick.dbs.default.driver = "slick.driver.PostgresDriver$"
slick.dbs.default.db.driver = "org.postgresql.Driver"
slick.dbs.default.db.url = "jdbc:postgresql://localhost:5432/database"
slick.dbs.default.db.user = "username"
slick.dbs.default.db.password = "password"

Search vs List all in Angular 2

Handling search and the List of all items in Angular 2 in the same Component

Using the tutorial of Angular 2 for hero search was the base for this, although I wanted that the same table to show the All the items when the search was inactive without having to do a new component (one for searching and another one for listing all products).

On the template I setup the call of the enableSearch and disableSearch events

Search:&nbsp;
<input id=”search-box” (keyup)=”enableSearch()” [(ngModel)]=”searchValue” />
<button (click)=”disableSearch()”>clear search</button>

the enableSearch is fired on keyup meaning someone is starting to search for a name or keyword.

the disableSearch is fired on click of the button “clear search”

I used the two way binding of searchValue so I can clear the searched text when I disable the search

In the component method enableSearch I set a flag searchEnable = true and setup the Observable relation to this.products this way if the search is Enabled I wont set it up again and kill the observable with this new call.

products: Observable<Product[]>;
private searchTerms = new Subject<string>();

parents : Product[];

selectedCategory: Product;

db: Product[];

searchValue : string = ”;

private searchEnabled:boolean = false;

Initially I make the call for the full items list using getProducts

ngOnInit() :void {
this.products = this.productService.getProducts();
}

When the search is enabled by the keyup event this is executed

    enableSearch() {
if (!this.searchEnabled) {
this.products = this.searchTerms
.debounceTime(500)        // wait for n ms pause in events
.distinctUntilChanged()   // ignore if next search term is same as previous
.switchMap( term => term   // switch to new observable each time
// return the http search observable
? this.productService.search(term)
// or the observable of empty products if no search term
: this.productService.getProducts()
)
.catch(error => {
// TODO: real error handling
console.log(error);
return Observable.of<Product[]>([]);
});
}

this.search(this.searchValue);

this.searchEnabled = true;
}

// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}

 

if the search wasn’t enable I set up the observable and put the search term into the observable stream 😡 . The ternary operator would only fire the list if I had the search typed so to get always a result list I had to make these changes, so the table would be filled when a search was on and when there was no search.

And the code bellow disables the search and displays all the products available

disableSearch() {
this.searchValue = ”;
this.searchEnabled = false;
this.products = this.productService.getProducts();
}

I set the searchValue to an empty string and disable the searchEnabled value and getProducts from the Service.