// Path: src/main/java/se/kth/csc/model/Account.java
// @Entity
// @Table(name = "account")
// public class Account {
//     @Id
//     @GeneratedValue(strategy = GenerationType.SEQUENCE)
//     @Column(name = "id", updatable = false)
//     private int id;
// 
//     @Column(name = "principal_name", unique = true)
//     private String principalName;
// 
//     @Column(name = "name")
//     private String name;
// 
//     @Column(name = "admin")
//     private boolean admin;
// 
//     @OneToMany(fetch = FetchType.EAGER, mappedBy = "account", cascade = CascadeType.ALL)
//     private Set<QueuePosition> positions = Sets.newHashSet();
// 
//     @ManyToMany(fetch = FetchType.EAGER, mappedBy = "owners", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST})
//     private Set<Queue> ownedQueues = Sets.newHashSet();
// 
//     @ManyToMany(fetch = FetchType.EAGER, mappedBy = "moderators", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST})
//     private Set<Queue> moderatedQueues = Sets.newHashSet();
// 
//     public int getId() {
//         return id;
//     }
// 
//     public String getPrincipalName() {
//         return principalName;
//     }
// 
//     public void setPrincipalName(String principalName) {
//         this.principalName = principalName;
//     }
// 
//     public String getName() {
//         return name;
//     }
// 
//     public void setName(String name) {
//         this.name = name;
//     }
// 
//     public boolean isAdmin() { return admin; }
// 
//     public boolean canEditQueue(Queue queue) {
//         if(isAdmin()) {
//             return true;
//         }
//         return ownedQueues.contains(queue);
//     }
// 
//     public boolean canModerateQueue(Queue queue) {
//         if(isAdmin()) {
//             return true;
//         }
//         if(ownedQueues.contains(queue)) {return true;}
//         return moderatedQueues.contains(queue);
//     }
// 
//     public void setAdmin(boolean admin) {
//         this.admin = admin;
//     }
// 
//     @JsonView(Account.class)
//     public Set<QueuePosition> getPositions() {
//         return positions;
//     }
// 
//     public void setPositions(Set<QueuePosition> positions) {
//         this.positions = Sets.newHashSet(positions);
//     }
// 
//     @JsonView(Account.class)
//     public Set<Queue> getOwnedQueues() {
//         return ownedQueues;
//     }
// 
//     @JsonView(Account.class)
//     public Set<Queue> getModeratedQueues() {
//         return moderatedQueues;
//     }
// 
//     public void setOwnedQueues(Set<Queue> queues) {
//         this.ownedQueues = Sets.newHashSet(queues);
//     }
// 
//     public void setModeratedQueues(Set<Queue> queues) {
//         this.moderatedQueues = Sets.newHashSet(queues);
//     }
// 
//     @Override
//     public boolean equals(Object o) {
//         if (this == o) return true;
//         if (o == null || getClass() != o.getClass()) return false;
// 
//         Account account = (Account) o;
// 
//         if (!principalName.equals(account.principalName)) return false;
// 
//         return true;
//     }
// 
//     @Override
//     public int hashCode() {
//         return principalName.hashCode();
//     }
// }
// 
// Path: src/main/java/se/kth/csc/persist/AccountStore.java
// public interface AccountStore {
//     public Account fetchAccountWithId(int id);
// 
//     public Account fetchAccountWithPrincipalName(String principalName);
// 
//     public Account fetchNewestAccount();
// 
//     public void storeAccount(Account account);
// 
//     public Iterable<Account> findAccounts(boolean onlyAdmin, String query);
// }


import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import se.kth.csc.model.Account;
import se.kth.csc.persist.AccountStore;
import java.util.Collection;
import com.google.common.collect.ImmutableSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
            throw new UsernameNotFoundException("This username is not in the u1 realm and was probably forged");
        }

        Account account = accountStore.fetchAccountWithPrincipalName(token.getName());

        if (account == null) {
            account = new Account();
            account.setPrincipalName(token.getName());
            for (GrantedAuthority grantedAuthority : token.getAuthorities()) {
                if (Role.ADMIN.getAuthority().equals(grantedAuthority.getAuthority())) {
                    account.setAdmin(true);
                    break;
                }
            }
            accountStore.storeAccount(account);

            log.info("Created user called \"{}\" with id {} and principal {}",
                    account.getName(), account.getId(), account.getPrincipalName());
        }
        String name = nameService.nameUser(token.getName());

        if (account.getName() == null || !account.getName().equals(name)) {
            account.setName(name);
            log.info("User with id {} and principal {} is now called \"{}\"",
                    account.getId(), account.getPrincipalName(), name);
        }

        return createUser(account);
    }

// Path: src/main/java/se/kth/csc/model/Account.java
// @Entity
// @Table(name = "account")
// public class Account {
//     @Id
//     @GeneratedValue(strategy = GenerationType.SEQUENCE)
//     @Column(name = "id", updatable = false)
//     private int id;
// 
//     @Column(name = "principal_name", unique = true)
//     private String principalName;
// 
//     @Column(name = "name")
//     private String name;
// 
//     @Column(name = "admin")
//     private boolean admin;
// 
//     @OneToMany(fetch = FetchType.EAGER, mappedBy = "account", cascade = CascadeType.ALL)
//     private Set<QueuePosition> positions = Sets.newHashSet();
// 
//     @ManyToMany(fetch = FetchType.EAGER, mappedBy = "owners", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST})
//     private Set<Queue> ownedQueues = Sets.newHashSet();
// 
//     @ManyToMany(fetch = FetchType.EAGER, mappedBy = "moderators", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST})
//     private Set<Queue> moderatedQueues = Sets.newHashSet();
// 
//     public int getId() {
//         return id;
//     }
// 
//     public String getPrincipalName() {
//         return principalName;
//     }
// 
//     public void setPrincipalName(String principalName) {
//         this.principalName = principalName;
//     }
// 
//     public String getName() {
//         return name;
//     }
// 
//     public void setName(String name) {
//         this.name = name;
//     }
// 
//     public boolean isAdmin() { return admin; }
// 
//     public boolean canEditQueue(Queue queue) {
//         if(isAdmin()) {
//             return true;
//         }
//         return ownedQueues.contains(queue);
//     }
// 
//     public boolean canModerateQueue(Queue queue) {
//         if(isAdmin()) {
//             return true;
//         }
//         if(ownedQueues.contains(queue)) {return true;}
//         return moderatedQueues.contains(queue);
//     }
// 
//     public void setAdmin(boolean admin) {
//         this.admin = admin;
//     }
// 
//     @JsonView(Account.class)
//     public Set<QueuePosition> getPositions() {
//         return positions;
//     }
// 
//     public void setPositions(Set<QueuePosition> positions) {
//         this.positions = Sets.newHashSet(positions);
//     }
// 
//     @JsonView(Account.class)
//     public Set<Queue> getOwnedQueues() {
//         return ownedQueues;
//     }
// 
//     @JsonView(Account.class)
//     public Set<Queue> getModeratedQueues() {
//         return moderatedQueues;
//     }
// 
//     public void setOwnedQueues(Set<Queue> queues) {
//         this.ownedQueues = Sets.newHashSet(queues);
//     }
// 
//     public void setModeratedQueues(Set<Queue> queues) {
//         this.moderatedQueues = Sets.newHashSet(queues);
//     }
// 
//     @Override
//     public boolean equals(Object o) {
//         if (this == o) return true;
//         if (o == null || getClass() != o.getClass()) return false;
// 
//         Account account = (Account) o;
// 
//         if (!principalName.equals(account.principalName)) return false;
// 
//         return true;
//     }
// 
//     @Override
//     public int hashCode() {
//         return principalName.hashCode();
//     }
// }
// 
// Path: src/main/java/se/kth/csc/persist/AccountStore.java
// public interface AccountStore {
//     public Account fetchAccountWithId(int id);
// 
//     public Account fetchAccountWithPrincipalName(String principalName);
// 
//     public Account fetchNewestAccount();
// 
//     public void storeAccount(Account account);
// 
//     public Iterable<Account> findAccounts(boolean onlyAdmin, String query);
// }


// Path: src/main/java/se/kth/csc/auth/UserService.java
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import se.kth.csc.model.Account;
import se.kth.csc.persist.AccountStore;
import java.util.Collection;
import com.google.common.collect.ImmutableSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;

            throw new UsernameNotFoundException("This username is not in the u1 realm and was probably forged");
        }

        Account account = accountStore.fetchAccountWithPrincipalName(token.getName());

        if (account == null) {
            account = new Account();
            account.setPrincipalName(token.getName());
            for (GrantedAuthority grantedAuthority : token.getAuthorities()) {
                if (Role.ADMIN.getAuthority().equals(grantedAuthority.getAuthority())) {
                    account.setAdmin(true);
                    break;
                }
            }
            accountStore.storeAccount(account);

            log.info("Created user called \"{}\" with id {} and principal {}",
                    account.getName(), account.getId(), account.getPrincipalName());
        }
        String name = nameService.nameUser(token.getName());

        if (account.getName() == null || !account.getName().equals(name)) {
            account.setName(name);
            log.info("User with id {} and principal {} is now called \"{}\"",
                    account.getId(), account.getPrincipalName(), name);
        }

        return createUser(account);
    }

    private UserDetails createUser(Account account) {