ServiceConnection.java

/*
 * Copyright (C) 2000 - 2025 Silverpeas
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * As a special exception to the terms and conditions of version 3.0 of
 * the GPL, you may redistribute this Program in connection with Free/Libre
 * Open Source Software ("FLOSS") applications as described in Silverpeas's
 * FLOSS exception. You should have received a copy of the text describing
 * the FLOSS exception, and it is also available here:
 * "https://www.silverpeas.org/legal/floss_exception.html"
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.silverpeas.mobile.server.services;

import jakarta.inject.Inject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import org.silverpeas.core.admin.domain.model.Domain;
import org.silverpeas.core.admin.service.AdminException;
import org.silverpeas.core.admin.service.Administration;
import org.silverpeas.core.admin.service.OrganizationController;
import org.silverpeas.core.admin.user.model.UserDetail;
import org.silverpeas.core.admin.user.model.UserFull;
import org.silverpeas.core.annotation.WebService;
import org.silverpeas.core.chat.ChatUsersRegistration;
import org.silverpeas.core.security.session.SessionInfo;
import org.silverpeas.core.security.session.SessionManagement;
import org.silverpeas.core.security.session.SessionManagementProvider;
import org.silverpeas.core.web.rs.UserPrivilegeValidation;
import org.silverpeas.mobile.server.dao.statistics.StatisticsDAO;
import org.silverpeas.mobile.server.helpers.DataURLHelper;
import org.silverpeas.mobile.server.services.helpers.UserHelper;
import org.silverpeas.mobile.shared.dto.DetailUserDTO;
import org.silverpeas.mobile.shared.dto.DomainDTO;
import ua_parser.Client;
import ua_parser.Parser;

import java.util.ArrayList;
import java.util.List;

/**
 * Service de gestion des connexions.
 * @author svuillet
 */
@WebService
@Path(ServiceConnection.PATH)
public class ServiceConnection extends AbstractRestWebService {

  @Inject
  private ChatUsersRegistration chatUsersRegistration;

  @Context
  HttpServletRequest request;

  @Inject
  private OrganizationController organizationController;

  @Inject
  private StatisticsDAO statisticsDAO;

  static final String PATH = "mobile/connection";

  private boolean isUserGUIMobileForTablets() {
    return getSettings().getBoolean("guiMobileForTablets", true);
  }

  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  @Path("login")
  public DetailUserDTO login() {
    SessionManagement sessionManagement = SessionManagementProvider.getSessionManagement();
    SessionInfo sessionInfo = sessionManagement.validateSession(request.getSession().getId());
    if (sessionInfo == null || sessionInfo.getSessionId() == null ||
            sessionInfo.getUserDetail() == null) {
      throw new NotAuthorizedException(getHttpServletResponse());
    }

    UserDetail userDetail = getUserDetail(sessionInfo.getUserDetail().getId());
    if (userDetail == null) {
      throw new NotAuthorizedException(getHttpServletResponse());
    }

    String userId = userDetail.getId();
    setUserInSession(userDetail);

    if (getMainSessionController() == null) {
      initSilverpeasSession(request);
    }

    DetailUserDTO userDTO = UserHelper.getInstance().populate(userDetail);

    String avatar = DataURLHelper.convertAvatarToUrlData(userDetail.getAvatarFileName(),
            getSettings().getString("big.avatar.size", "40x"));
    userDTO.setAvatar(avatar);
    try {
      userDTO.setStatus(new ServiceRSE().getStatus().getDescription());
    } catch (Exception e) {
      userDTO.setStatus("");
    }

    // chat init
    request.getSession().setAttribute("Silverpeas.Chat",
            chatUsersRegistration.isChatServiceEnabled() && !userDetail.isAnonymous() &&
                    !userDetail.isAccessGuest());

    // Add connexion in stats
    statisticsDAO.saveLoginEvent(Long.parseLong(userId), getPlatform(),
            getSettings().getString("version"), getOsVersion(), getClientIp(getHttpRequest()),
            getPreferredLanguage(getHttpRequest()), getDevice());

    return userDTO;
  }

  public String getPreferredLanguage(HttpServletRequest request) {
    String acceptLanguage = request.getHeader("Accept-Language");
    if (acceptLanguage == null || acceptLanguage.isEmpty()) {
      return null;
    }

    // Prend la première langue (ex: fr-FR)
    String firstLang = acceptLanguage.split(",")[0];

    // Garde uniquement les 2 premiers caractères
    return firstLang.substring(0, Math.min(2, firstLang.length())).toLowerCase();
  }

  private String getClientIp(HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("X-Real-IP");
    }
    if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }

    // Si X-Forwarded-For contient plusieurs IP séparées par des virgules, prendre la première
    if (ip != null && ip.contains(",")) {
      ip = ip.split(",")[0].trim();
    }
    return ip;
  }

  private short getPlatform() {
    HttpServletRequest request = this.getHttpRequest();
    String userAgent = request.getHeader("User-Agent");
    short platform = 0; // 1=ios, 2=android, 0=autre
    Parser parser = new Parser();
    Client client = parser.parse(userAgent);

    if (client.os.family.equalsIgnoreCase("android")) {
      platform = 2; // Android
    } else if (client.os.family.equalsIgnoreCase("ios")) {
      platform = 1; // iOS
    }

    return platform;
  }

  private String getOsVersion() {
    HttpServletRequest request = this.getHttpRequest();
    String userAgent = request.getHeader("User-Agent");
    Parser parser = new Parser();
    Client client = parser.parse(userAgent);

    return client.os.major + "." + client.os.minor;
  }

  private String getDevice() {
    HttpServletRequest request = this.getHttpRequest();
    String userAgent = request.getHeader("User-Agent");
    Parser parser = new Parser();
    Client client = parser.parse(userAgent);

    return client.device.family;
  }

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Path("userExist/{login}/{domainId}")
  public Boolean userExist(@PathParam("login") String login,
                           @PathParam("domainId") String domainId) {
    try {
      String id = getUserId(login, domainId);
      return id != null;
    } catch (Exception e) {
      return false;
    }
  }

  @PUT
  @Produces(MediaType.APPLICATION_JSON)
  @Path("setTabletMode")
  public Boolean setTabletMode() {
    if (!isUserGUIMobileForTablets()) {
      request.getSession().setAttribute("tablet", Boolean.TRUE);
      return true;
    }
    return false;
  }

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Path("domains")
  public List<DomainDTO> getDomains() {
    Domain[] allDomains = organizationController.getAllDomains();
    ArrayList<DomainDTO> domains = new ArrayList<>();
    for (Domain allDomain : allDomains) {
      domains.add(populate(allDomain));
    }
    return domains;
  }

  private String getUserId(String login, String domainId) throws AdminException {
    return Administration.get().getUserIdByLoginAndDomain(login, domainId);
  }

  private UserDetail getUserDetail(String userId) {
    return organizationController.getUserDetail(userId);
  }

  private DomainDTO populate(Domain domain) {
    DomainDTO dto = new DomainDTO();
    dto.setName(domain.getName());
    dto.setId(domain.getId());
    return dto;
  }

  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  @Path("changePwd/")
  public void changePwd(String newPwd) {
    if (getUserInSession() == null) {
      throw new NotAuthorizedException(getHttpServletResponse());
    }
    UserFull user;
    try {
      user = Administration.get().getUserFull(getUserInSession().getId());
      user.setPassword(newPwd);
      Administration.get().updateUserFull(user);
    } catch (AdminException e) {
      throw new WebApplicationException(e);
    }
  }

  @PUT
  @Produces(MediaType.APPLICATION_JSON)
  @Path("userAcceptsTermsOfService")
  public void userAcceptsTermsOfService() {
    try {
      Administration.get().userAcceptsTermsOfService(getUserInSession().getId());
    } catch (AdminException e) {
      throw new WebApplicationException(e);
    }
  }

  protected void setUserInSession(UserDetail user) {
    request.getSession().setAttribute(AbstractRestWebService.USER_ATTRIBUT_NAME, user);
  }

  protected UserDetail getUserInSession() {
    return (UserDetail) request.getSession()
            .getAttribute(AbstractRestWebService.USER_ATTRIBUT_NAME);
  }

  @Override
  protected String getResourceBasePath() {
    return PATH;
  }

  @Override
  public String getComponentId() {
    return null;
  }

  @Override
  public void validateUserAuthorization(final UserPrivilegeValidation validation) {
    // no need to validate the authorization
  }
}