1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.mycore.user2.login;
20
21 import java.util.HashMap;
22 import java.util.Map;
23
24 import org.apache.logging.log4j.LogManager;
25 import org.apache.logging.log4j.Logger;
26 import org.mycore.common.MCRSessionMgr;
27 import org.mycore.common.MCRUserInformation;
28 import org.mycore.frontend.servlets.MCRServlet;
29 import org.mycore.frontend.servlets.MCRServletJob;
30 import org.mycore.user2.MCRRealmFactory;
31 import org.mycore.user2.MCRUser;
32 import org.mycore.user2.MCRUserAttributeMapper;
33 import org.mycore.user2.MCRUserManager;
34
35 import jakarta.servlet.http.HttpServletRequest;
36 import jakarta.servlet.http.HttpServletResponse;
37
38
39
40
41
42 public class MCRShibbolethLoginServlet extends MCRServlet {
43
44 private static final long serialVersionUID = 1L;
45
46 private static Logger LOGGER = LogManager.getLogger(MCRShibbolethLoginServlet.class);
47
48 public void doGetPost(MCRServletJob job) throws Exception {
49 HttpServletRequest req = job.getRequest();
50 HttpServletResponse res = job.getResponse();
51
52 String msg = null;
53
54 String uid = (String) req.getAttribute("uid");
55 String userId = uid != null ? uid : req.getRemoteUser();
56
57 if (userId != null) {
58 final String realmId = userId.contains("@") ? userId.substring(userId.indexOf("@") + 1) : null;
59 if (realmId != null && MCRRealmFactory.getRealm(realmId) != null) {
60 userId = realmId != null ? userId.replace("@" + realmId, "") : userId;
61
62 final Map<String, Object> attributes = new HashMap<>();
63
64 final MCRUserAttributeMapper attributeMapper = MCRRealmFactory.getAttributeMapper(realmId);
65 for (final String key : attributeMapper.getAttributeNames()) {
66 final Object value = req.getAttribute(key);
67 if (value != null) {
68 LOGGER.info("received {}:{}", key, value);
69 attributes.put(key, value);
70 }
71 }
72
73 MCRUserInformation userinfo;
74
75 MCRUser user = MCRUserManager.getUser(userId, realmId);
76 if (user != null) {
77 LOGGER.debug("login existing user \"{}\"", user.getUserID());
78
79 attributeMapper.mapAttributes(user, attributes);
80 user.setLastLogin();
81 MCRUserManager.updateUser(user);
82
83 userinfo = user;
84 } else {
85 userinfo = new MCRShibbolethUserInformation(userId, realmId, attributes);
86 }
87
88 MCRSessionMgr.getCurrentSession().setUserInformation(userinfo);
89
90 req.changeSessionId();
91
92 res.sendRedirect(res.encodeRedirectURL(req.getParameter("url")));
93 return;
94 } else {
95 msg = "Login from realm \"" + realmId + "\" is not allowed.";
96 }
97 } else {
98 msg = "Principal could not be received from IDP.";
99 }
100
101 job.getResponse().sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
102 }
103 }