001 package org.nakedobjects.applib.security;
002
003 import java.util.ArrayList;
004 import java.util.Arrays;
005 import java.util.List;
006
007 import org.nakedobjects.applib.annotation.MemberOrder;
008 import org.nakedobjects.applib.annotation.NotPersistable;
009
010 /**
011 * Details, obtained from the container, about the user and his roles. Read-only.
012 */
013 @NotPersistable
014 public final class UserMemento {
015
016 /**
017 * Creates a new user with the specified name and no roles.
018 */
019 public UserMemento(final String name) {
020 this(name, new RoleMemento[0]);
021 }
022
023 /**
024 * Creates a new user with the specified name and assigned roles.
025 */
026 public UserMemento(final String name, final RoleMemento... roles) {
027 this(name, Arrays.asList(roles));
028 }
029
030 /**
031 * Creates a new user with the specified name and assigned roles.
032 */
033 public UserMemento(final String name, final List<RoleMemento> roles) {
034 if (name == null) {
035 throw new IllegalArgumentException("Name not specified");
036 }
037 this.name = name;
038 this.roles.addAll(roles);
039 }
040
041
042 // {{ Identification: Title
043 public String title() {
044 return name;
045 }
046 // }}
047
048
049 // {{ (User) Name, isCurrentUser
050 private final String name;
051 /**
052 * The user's login name.
053 */
054 @MemberOrder(sequence="1.1")
055 public String getName() {
056 return name;
057 }
058
059
060 /**
061 * Determine if the specified user is this user. Returns true if the names match (is case sensitive).
062 */
063 public boolean isCurrentUser(final String user) {
064 if (user == null) {
065 throw new IllegalStateException("no user specified");
066 }
067 return name.equals(user);
068 }
069 // }}
070
071
072
073 // {{ Roles
074 private final List<RoleMemento> roles = new ArrayList<RoleMemento>();
075
076 /**
077 * The roles associated with this user.
078 */
079 @MemberOrder(sequence="1.1")
080 public List<RoleMemento> getRoles() {
081 return roles;
082 }
083
084 /**
085 * Determines if the user fulfills the specified role.
086 */
087 public boolean hasRole(final RoleMemento role) {
088 return hasRole(role.getName());
089 }
090
091 /**
092 * Determines if the user fulfills the specified role. Roles are compared lexically by role name.
093 */
094 public boolean hasRole(final String roleName) {
095 for(RoleMemento role: roles) {
096 if (role.getName().equals(roleName)) {
097 return true;
098 }
099 }
100 return false;
101 }
102 // }}
103
104 @Override
105 public String toString() {
106 StringBuilder buf = new StringBuilder();
107 for (RoleMemento role: roles) {
108 buf.append(role.getName()).append(" ");
109 }
110 return "User [name=" + getName() + ",roles=" + buf.toString() + "]";
111 }
112
113 }
114 // Copyright (c) Naked Objects Group Ltd.