public void onMessage(Message message) { if (message.getType() == MessageType.MSG && message.get(MessageProperty.ROOM).equals("#main")) { long userId = message.get(MessageProperty.USER_ID); String name = message.get(MessageProperty.NAME); UserCredentials userCredentials = null; if (needsFetchingConnectionData(userId)) { userCredentials = fetchConnectionDataForUser(name, userId); } if (userCredentials != null) { String id = userCredentials.getId(); Channel channel = connections.get(id.toLowerCase()); if (channel == null || !channel.isActive()) { try { channel = createConnection(id, userCredentials.getToken()); } catch (InterruptedException e) { logger.warn("", e); } } if (channel != null) { channel.attr(lastMessageAttrKey).set(System.currentTimeMillis()); channel.writeAndFlush( "PRIVMSG #" + this.channel + " :" + message.get(MessageProperty.TEXT) + "\r\n"); } } } }
@Override public void encodeAndSetPassword(UserCredentials userCredentials, String rawPassword) { boolean isNewPassword = StringUtils.isBlank(userCredentials.getPassword()) || !passwordManager.legacyOrCurrentMatches( rawPassword, userCredentials.getPassword(), userCredentials.getUsername()); if (isNewPassword) { userCredentials.setPasswordLastUpdated(new Date()); } userCredentials.setPassword(passwordManager.encode(rawPassword)); }
@Override public void assignDataSetToUserRole(DataSet dataSet) { User currentUser = currentUserService.getCurrentUser(); if (!currentUserService.currentUserIsSuper() && currentUser != null) { UserCredentials userCredentials = getUserCredentials(currentUser); for (UserAuthorityGroup userAuthorityGroup : userCredentials.getUserAuthorityGroups()) { userAuthorityGroup.getDataSets().add(dataSet); updateUserAuthorityGroup(userAuthorityGroup); } } }
@Override public boolean isLastSuperUser(UserCredentials userCredentials) { if (!userCredentials.isSuper()) { return false; // Cannot be last if not super user } Collection<UserCredentials> users = userCredentialsStore.getAll(); for (UserCredentials user : users) { if (user.isSuper() && !user.equals(userCredentials)) { return false; } } return true; }
@Override public boolean credentialsNonExpired(UserCredentials credentials) { int credentialsExpires = systemSettingManager.credentialsExpires(); if (credentialsExpires == 0) { return true; } int months = DateUtils.monthsBetween(credentials.getPasswordLastUpdated(), new Date()); return months < credentialsExpires; }
@Override public Set<DataElementCategoryOption> getCoDimensionConstraints(UserCredentials userCredentials) { Set<DataElementCategoryOption> options = null; Set<DataElementCategory> catConstraints = userCredentials.getCatDimensionConstraints(); if (catConstraints != null && !catConstraints.isEmpty()) { options = new HashSet<>(); for (DataElementCategory category : catConstraints) { options.addAll(categoryService.getDataElementCategoryOptions(category)); } } return options; }
@Override public Set<CategoryOptionGroup> getCogDimensionConstraints(UserCredentials userCredentials) { Set<CategoryOptionGroup> groups = null; Set<CategoryOptionGroupSet> cogsConstraints = userCredentials.getCogsDimensionConstraints(); if (cogsConstraints != null && !cogsConstraints.isEmpty()) { groups = new HashSet<>(); for (CategoryOptionGroupSet cogs : cogsConstraints) { groups.addAll(categoryService.getCategoryOptionGroups(cogs)); } } return groups; }
public void mergeFrom(Input input, UserToBitHandshake message) throws IOException { for (int number = input.readFieldNumber(this); ; number = input.readFieldNumber(this)) { switch (number) { case 0: return; case 1: message.channel = RpcChannel.valueOf(input.readEnum()); break; case 2: message.supportListening = input.readBool(); break; case 3: message.rpcVersion = input.readInt32(); break; case 4: message.credentials = input.mergeObject(message.credentials, UserCredentials.getSchema()); break; case 5: message.properties = input.mergeObject(message.properties, UserProperties.getSchema()); break; case 6: message.supportComplexTypes = input.readBool(); break; case 7: message.supportTimeout = input.readBool(); break; case 8: message.clientInfos = input.mergeObject(message.clientInfos, RpcEndpointInfos.getSchema()); break; default: input.handleUnknownField(number, this); } } }
public void writeTo(Output output, UserToBitHandshake message) throws IOException { if (message.channel != null) output.writeEnum(1, message.channel.number, false); if (message.supportListening != null) output.writeBool(2, message.supportListening, false); if (message.rpcVersion != 0) output.writeInt32(3, message.rpcVersion, false); if (message.credentials != null) output.writeObject(4, message.credentials, UserCredentials.getSchema(), false); if (message.properties != null) output.writeObject(5, message.properties, UserProperties.getSchema(), false); if (message.supportComplexTypes != null && message.supportComplexTypes != DEFAULT_SUPPORT_COMPLEX_TYPES) output.writeBool(6, message.supportComplexTypes, false); if (message.supportTimeout != null && message.supportTimeout != DEFAULT_SUPPORT_TIMEOUT) output.writeBool(7, message.supportTimeout, false); if (message.clientInfos != null) output.writeObject(8, message.clientInfos, RpcEndpointInfos.getSchema(), false); }
public String execute() throws Exception { UserCredentials currentUserCredentials = currentUserService.getCurrentUser() != null ? currentUserService.getCurrentUser().getUserCredentials() : null; // --------------------------------------------------------------------- // Prepare values // --------------------------------------------------------------------- if (email != null && email.trim().length() == 0) { email = null; } if (rawPassword != null && rawPassword.trim().length() == 0) { rawPassword = null; } // --------------------------------------------------------------------- // Update userCredentials and user // --------------------------------------------------------------------- Collection<OrganisationUnit> units = selectionTreeManager.getReloadedSelectedOrganisationUnits(); User user = userService.getUser(id); user.setSurname(surname); user.setFirstName(firstName); user.setEmail(email); user.setPhoneNumber(phoneNumber); user.updateOrganisationUnits(new HashSet<OrganisationUnit>(units)); UserCredentials userCredentials = userService.getUserCredentials(user); Set<UserAuthorityGroup> userAuthorityGroups = new HashSet<UserAuthorityGroup>(); for (String id : selectedList) { UserAuthorityGroup group = userService.getUserAuthorityGroup(Integer.parseInt(id)); if (currentUserCredentials != null && currentUserCredentials.canIssue(group)) { userAuthorityGroups.add(group); } } userCredentials.setUserAuthorityGroups(userAuthorityGroups); if (rawPassword != null) { userCredentials.setPassword( passwordManager.encodePassword(userCredentials.getUsername(), rawPassword)); } if (jsonAttributeValues != null) { AttributeUtils.updateAttributeValuesFromJson( user.getAttributeValues(), jsonAttributeValues, attributeService); } userService.updateUserCredentials(userCredentials); userService.updateUser(user); if (currentUserService.getCurrentUser() == user) { selectionManager.setRootOrganisationUnits(units); selectionManager.setSelectedOrganisationUnits(units); selectionTreeManager.setRootOrganisationUnits(units); selectionTreeManager.setSelectedOrganisationUnits(units); } if (units.size() > 0) { selectionManager.setSelectedOrganisationUnits(units); } return SUCCESS; }
@Override public void setLastLogin(String username) { UserCredentials credentials = getUserCredentialsByUsername(username); credentials.setLastLogin(new Date()); updateUserCredentials(credentials); }
/** * Generates an authorisation header in response to wwwAuthHeader. * * @param method method of the request being authenticated * @param uri digest-uri * @param requestBody the body of the request. * @param authHeader the challenge that we should respond to * @param userCredentials username and pass * @return an authorisation header in response to authHeader. * @throws OperationFailedException if auth header was malformated. */ private AuthorizationHeader getAuthorization( String method, String uri, String requestBody, WWWAuthenticateHeader authHeader, UserCredentials userCredentials) { String response = null; // JvB: authHeader.getQop() is a quoted _list_ of qop values // (e.g. "auth,auth-int") Client is supposed to pick one String qopList = authHeader.getQop(); String qop = (qopList != null) ? "auth" : null; String nc_value = "00000001"; String cnonce = "xyz"; response = MessageDigestAlgorithm.calculateResponse( authHeader.getAlgorithm(), userCredentials.getUserName(), authHeader.getRealm(), userCredentials.getPassword(), authHeader.getNonce(), nc_value, // JvB added cnonce, // JvB added method, uri, requestBody, qop, sipStack.getStackLogger()); // jvb changed AuthorizationHeader authorization = null; try { if (authHeader instanceof ProxyAuthenticateHeader) { authorization = headerFactory.createProxyAuthorizationHeader(authHeader.getScheme()); } else { authorization = headerFactory.createAuthorizationHeader(authHeader.getScheme()); } authorization.setUsername(userCredentials.getUserName()); authorization.setRealm(authHeader.getRealm()); authorization.setNonce(authHeader.getNonce()); authorization.setParameter("uri", uri); authorization.setResponse(response); if (authHeader.getAlgorithm() != null) { authorization.setAlgorithm(authHeader.getAlgorithm()); } if (authHeader.getOpaque() != null) { authorization.setOpaque(authHeader.getOpaque()); } // jvb added if (qop != null) { authorization.setQop(qop); authorization.setCNonce(cnonce); authorization.setNonceCount(Integer.parseInt(nc_value)); } authorization.setResponse(response); } catch (ParseException ex) { throw new RuntimeException("Failed to create an authorization header!"); } return authorization; }
/* * (non-Javadoc) * * @see gov.nist.javax.sip.clientauthutils.AuthenticationHelper#handleChallenge(javax.sip.message.Response, * javax.sip.ClientTransaction, javax.sip.SipProvider) */ public ClientTransaction handleChallenge( Response challenge, ClientTransaction challengedTransaction, SipProvider transactionCreator, int cacheTime) throws SipException, NullPointerException { try { if (sipStack.isLoggingEnabled()) { sipStack.getStackLogger().logDebug("handleChallenge: " + challenge); } SIPRequest challengedRequest = ((SIPRequest) challengedTransaction.getRequest()); Request reoriginatedRequest = null; /* * If the challenged request is part of a Dialog and the * Dialog is confirmed the re-originated request should be * generated as an in-Dialog request. */ if (challengedRequest.getToTag() != null || challengedTransaction.getDialog() == null || challengedTransaction.getDialog().getState() != DialogState.CONFIRMED) { reoriginatedRequest = (Request) challengedRequest.clone(); } else { /* * Re-originate the request by consulting the dialog. In particular * the route set could change between the original request and the * in-dialog challenge. */ reoriginatedRequest = challengedTransaction.getDialog().createRequest(challengedRequest.getMethod()); Iterator<String> headerNames = challengedRequest.getHeaderNames(); while (headerNames.hasNext()) { String headerName = headerNames.next(); if (reoriginatedRequest.getHeader(headerName) != null) { ListIterator<Header> iterator = reoriginatedRequest.getHeaders(headerName); while (iterator.hasNext()) { reoriginatedRequest.addHeader(iterator.next()); } } } } // remove the branch id so that we could use the request in a new // transaction removeBranchID(reoriginatedRequest); if (challenge == null || reoriginatedRequest == null) { throw new NullPointerException("A null argument was passed to handle challenge."); } ListIterator authHeaders = null; if (challenge.getStatusCode() == Response.UNAUTHORIZED) { authHeaders = challenge.getHeaders(WWWAuthenticateHeader.NAME); } else if (challenge.getStatusCode() == Response.PROXY_AUTHENTICATION_REQUIRED) { authHeaders = challenge.getHeaders(ProxyAuthenticateHeader.NAME); } else { throw new IllegalArgumentException("Unexpected status code "); } if (authHeaders == null) { throw new IllegalArgumentException( "Could not find WWWAuthenticate or ProxyAuthenticate headers"); } // Remove all authorization headers from the request (we'll re-add them // from cache) reoriginatedRequest.removeHeader(AuthorizationHeader.NAME); reoriginatedRequest.removeHeader(ProxyAuthorizationHeader.NAME); // rfc 3261 says that the cseq header should be augmented for the new // request. do it here so that the new dialog (created together with // the new client transaction) takes it into account. // Bug report - Fredrik Wickstrom CSeqHeader cSeq = (CSeqHeader) reoriginatedRequest.getHeader((CSeqHeader.NAME)); try { cSeq.setSeqNumber(cSeq.getSeqNumber() + 1l); } catch (InvalidArgumentException ex) { throw new SipException("Invalid CSeq -- could not increment : " + cSeq.getSeqNumber()); } /* Resolve this to the next hop based on the previous lookup. If we are not using * lose routing (RFC2543) then just attach hop as a maddr param. */ if (challengedRequest.getRouteHeaders() == null) { Hop hop = ((SIPClientTransaction) challengedTransaction).getNextHop(); SipURI sipUri = (SipURI) reoriginatedRequest.getRequestURI(); sipUri.setMAddrParam(hop.getHost()); if (hop.getPort() != -1) sipUri.setPort(hop.getPort()); } ClientTransaction retryTran = transactionCreator.getNewClientTransaction(reoriginatedRequest); WWWAuthenticateHeader authHeader = null; SipURI requestUri = (SipURI) challengedTransaction.getRequest().getRequestURI(); while (authHeaders.hasNext()) { authHeader = (WWWAuthenticateHeader) authHeaders.next(); String realm = authHeader.getRealm(); AuthorizationHeader authorization = null; String sipDomain; if (this.accountManager instanceof SecureAccountManager) { UserCredentialHash credHash = ((SecureAccountManager) this.accountManager) .getCredentialHash(challengedTransaction, realm); URI uri = reoriginatedRequest.getRequestURI(); sipDomain = credHash.getSipDomain(); authorization = this.getAuthorization( reoriginatedRequest.getMethod(), uri.toString(), (reoriginatedRequest.getContent() == null) ? "" : new String(reoriginatedRequest.getRawContent()), authHeader, credHash); } else { UserCredentials userCreds = ((AccountManager) this.accountManager).getCredentials(challengedTransaction, realm); sipDomain = userCreds.getSipDomain(); if (userCreds == null) throw new SipException("Cannot find user creds for the given user name and realm"); // we haven't yet authenticated this realm since we were // started. authorization = this.getAuthorization( reoriginatedRequest.getMethod(), reoriginatedRequest.getRequestURI().toString(), (reoriginatedRequest.getContent() == null) ? "" : new String(reoriginatedRequest.getRawContent()), authHeader, userCreds); } sipStack .getStackLogger() .logDebug("Created authorization header: " + authorization.toString()); if (cacheTime != 0) cachedCredentials.cacheAuthorizationHeader(sipDomain, authorization, cacheTime); reoriginatedRequest.addHeader(authorization); } if (sipStack.isLoggingEnabled()) { sipStack.getStackLogger().logDebug("Returning authorization transaction." + retryTran); } return retryTran; } catch (SipException ex) { throw ex; } catch (Exception ex) { sipStack.getStackLogger().logError("Unexpected exception ", ex); throw new SipException("Unexpected exception ", ex); } }