1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.jboss.as.quickstarts.tasksJsf;
18
19 import javax.enterprise.context.Conversation;
20 import javax.enterprise.context.RequestScoped;
21 import javax.enterprise.inject.Produces;
22 import javax.faces.application.FacesMessage;
23 import javax.faces.context.FacesContext;
24 import javax.inject.Inject;
25 import javax.inject.Named;
26
27
28
29
30
31
32
33
34 @Named
35 @RequestScoped
36 public class AuthController {
37
38 @Inject
39 private Authentication authentication;
40
41 @Inject
42 private UserDao userDao;
43
44 @Inject
45 private FacesContext facesContext;
46
47 @Inject
48 private Conversation conversation;
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65 @Produces
66 @Named
67 @CurrentUser
68 public User getCurrentUser() {
69 return authentication.getCurrentUser();
70 }
71
72
73
74
75
76
77
78
79
80
81
82
83 public void authenticate(String username) {
84 if (isLogged()) {
85 throw new IllegalStateException("User is logged and tries to authenticate again");
86 }
87
88 User user = userDao.getForUsername(username);
89 if (user == null) {
90 user = createUser(username);
91 }
92 authentication.setCurrentUser(user);
93 conversation.begin();
94 }
95
96
97
98
99 public void logout() {
100 authentication.setCurrentUser(null);
101 conversation.end();
102 }
103
104
105
106
107
108
109 public boolean isLogged() {
110 return authentication.getCurrentUser() != null;
111 }
112
113 private User createUser(String username) {
114 try {
115 User user = new User(username);
116 userDao.createUser(user);
117 facesContext.addMessage(null, new FacesMessage("User successfully created"));
118 return user;
119 } catch (Exception e) {
120 facesContext.addMessage(null, new FacesMessage("Failed to create user '" + username + "'", e.getMessage()));
121 return null;
122 }
123 }
124 }