Example usage for org.eclipse.jgit.util Base64 decode

List of usage examples for org.eclipse.jgit.util Base64 decode

Introduction

In this page you can find the example usage for org.eclipse.jgit.util Base64 decode.

Prototype

public static byte[] decode(String s) 

Source Link

Document

Decodes data from Base64 notation.

Usage

From source file:co.bledo.gitmin.servlet.Git.java

License:Apache License

@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    log.entry(req, res);//from   ww  w .  j  av a2  s  .c  o  m
    String authhead = req.getHeader("Authorization");
    if (authhead != null) {
        String usernpass = new String(Base64.decode(authhead.substring(6)));
        String username = usernpass.substring(0, usernpass.indexOf(":"));
        String password = usernpass.substring(usernpass.indexOf(":") + 1);

        try {
            User user = GitminStorage.userAuth(username, password);

            log.info("calling parent service(req, res)");
            super.service(req, res);
        } catch (NotFoundException e) {

            //***We weren't sent a valid username/password in the header, so ask for one***
            //res.getWriter().println("<html><body><h1>Access Denied</h1></body></html>");
            res.setHeader("WWW-Authenticate", "Basic realm=\"Authentication\"");
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "");
        } catch (DbException e) {
            throw log.throwing(new ServletException(e));
        }
    } else {
        //***We weren't sent a valid username/password in the header, so ask for one***
        res.setHeader("WWW-Authenticate", "Basic realm=\"Authentication\"");
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "");
        //res.getWriter().println("<html><body><h1>Access Denied</h1></body></html>");
    }
    log.exit();
}

From source file:com.gitblit.AccessRestrictionFilter.java

License:Apache License

/**
 * doFilter does the actual work of preprocessing the request to ensure that
 * the user may proceed./*from ww  w .j a  v  a2  s.c  om*/
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    // Wrap the HttpServletRequest with the AccessRestrictionRequest which
    // overrides the servlet container user principal methods.
    // JGit requires either:
    //
    // 1. servlet container authenticated user
    // 2. http.receivepack = true in each repository's config
    //
    // Gitblit must conditionally authenticate users per-repository so just
    // enabling http.receivepack is insufficient.

    AccessRestrictionRequest accessRequest = new AccessRestrictionRequest(httpRequest);

    String servletUrl = httpRequest.getContextPath() + httpRequest.getServletPath();
    String url = httpRequest.getRequestURI().substring(servletUrl.length());
    String params = httpRequest.getQueryString();
    if (url.length() > 0 && url.charAt(0) == '/') {
        url = url.substring(1);
    }
    String fullUrl = url + (StringUtils.isEmpty(params) ? "" : ("?" + params));

    String repository = extractRepositoryName(fullUrl);

    // Determine if the request URL is restricted
    String fullSuffix = fullUrl.substring(repository.length());
    String urlRequestType = getUrlRequestAction(fullSuffix);

    // Load the repository model
    RepositoryModel model = GitBlit.self().getRepositoryModel(repository);
    if (model == null) {
        // repository not found. send 404.
        logger.info("ARF: " + fullUrl + " (" + HttpServletResponse.SC_NOT_FOUND + ")");
        httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // BASIC authentication challenge and response processing
    if (!StringUtils.isEmpty(urlRequestType) && requiresAuthentication(model)) {
        // look for client authorization credentials in header
        final String authorization = httpRequest.getHeader("Authorization");
        if (authorization != null && authorization.startsWith(BASIC)) {
            // Authorization: Basic base64credentials
            String base64Credentials = authorization.substring(BASIC.length()).trim();
            String credentials = new String(Base64.decode(base64Credentials), Charset.forName("UTF-8"));
            // credentials = username:password
            final String[] values = credentials.split(":");

            if (values.length == 2) {
                String username = values[0];
                char[] password = values[1].toCharArray();
                UserModel user = GitBlit.self().authenticate(username, password);
                if (user != null) {
                    accessRequest.setUser(user);
                    if (user.canAdmin || canAccess(model, user, urlRequestType)) {
                        // authenticated request permitted.
                        // pass processing to the restricted servlet.
                        newSession(accessRequest, httpResponse);
                        logger.info(
                                "ARF: " + fullUrl + " (" + HttpServletResponse.SC_CONTINUE + ") authenticated");
                        chain.doFilter(accessRequest, httpResponse);
                        return;
                    }
                    // valid user, but not for requested access. send 403.
                    if (GitBlit.isDebugMode()) {
                        logger.info("ARF: " + fullUrl + " (" + HttpServletResponse.SC_FORBIDDEN + ")");
                        logger.info(
                                MessageFormat.format("AUTH: {0} forbidden to access {1}", user.username, url));
                    }
                    httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            }
            if (GitBlit.isDebugMode()) {
                logger.info(MessageFormat.format("AUTH: invalid credentials ({0})", credentials));
            }
        }

        // challenge client to provide credentials. send 401.
        if (GitBlit.isDebugMode()) {
            logger.info("ARF: " + fullUrl + " (" + HttpServletResponse.SC_UNAUTHORIZED + ")");
            logger.info("AUTH: Challenge " + CHALLENGE);
        }
        httpResponse.setHeader("WWW-Authenticate", CHALLENGE);
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    if (GitBlit.isDebugMode()) {
        logger.info("ARF: " + fullUrl + " (" + HttpServletResponse.SC_CONTINUE + ") unauthenticated");
    }
    // unauthenticated request permitted.
    // pass processing to the restricted servlet.
    chain.doFilter(accessRequest, httpResponse);
}

From source file:com.google.gerrit.acceptance.rest.config.ListCachesIT.java

License:Apache License

@Test
public void listCacheNamesTextList() throws Exception {
    RestResponse r = adminSession.get("/config/server/caches/?format=TEXT_LIST");
    assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    String result = new String(Base64.decode(r.getEntityContent()), UTF_8.name());
    List<String> list = Arrays.asList(result.split("\n"));
    assertThat(list).contains("accounts");
    assertThat(list).contains("projects");
    assertThat(Ordering.natural().isOrdered(list)).isTrue();
}

From source file:com.google.gerrit.httpd.auth.container.HttpAuthFilter.java

License:Apache License

String getRemoteUser(HttpServletRequest req) {
    if (AUTHORIZATION.equals(loginHeader)) {
        String user = emptyToNull(req.getRemoteUser());
        if (user != null) {
            // The container performed the authentication, and has the user
            // identity already decoded for us. Honor that as we have been
            // configured to honor HTTP authentication.
            return user;
        }/*  www  . j ava2s  . com*/

        // If the container didn't do the authentication we might
        // have done it in the front-end web server. Try to split
        // the identity out of the Authorization header and honor it.
        //
        String auth = emptyToNull(req.getHeader(AUTHORIZATION));
        if (auth == null) {
            return null;

        } else if (auth.startsWith("Basic ")) {
            auth = auth.substring("Basic ".length());
            auth = new String(Base64.decode(auth));
            final int c = auth.indexOf(':');
            return c > 0 ? auth.substring(0, c) : null;

        } else if (auth.startsWith("Digest ")) {
            final int u = auth.indexOf("username=\"");
            if (u <= 0) {
                return null;
            }
            auth = auth.substring(u + 10);
            final int e = auth.indexOf('"');
            return e > 0 ? auth.substring(0, e) : null;

        } else {
            return null;
        }
    } else {
        // Nonstandard HTTP header. We have been told to trust this
        // header blindly as-is.
        //
        return emptyToNull(req.getHeader(loginHeader));
    }
}

From source file:com.google.gerrit.httpd.auth.container.HttpLoginServlet.java

License:Apache License

private String getRemoteUser(final HttpServletRequest req) {
    if (AUTHORIZATION.equals(loginHeader)) {
        final String user = req.getRemoteUser();
        if (user != null && !"".equals(user)) {
            // The container performed the authentication, and has the user
            // identity already decoded for us. Honor that as we have been
            // configured to honor HTTP authentication.
            ///*from   w w  w . j  av a  2  s. c  o m*/
            return user;
        }

        // If the container didn't do the authentication we might
        // have done it in the front-end web server. Try to split
        // the identity out of the Authorization header and honor it.
        //
        String auth = req.getHeader(AUTHORIZATION);
        if (auth == null || "".equals(auth)) {
            return null;

        } else if (auth.startsWith("Basic ")) {
            auth = auth.substring("Basic ".length());
            auth = new String(Base64.decode(auth));
            final int c = auth.indexOf(':');
            return c > 0 ? auth.substring(0, c) : null;

        } else if (auth.startsWith("Digest ")) {
            final int u = auth.indexOf("username=\"");
            if (u <= 0) {
                return null;
            }
            auth = auth.substring(u + 10);
            final int e = auth.indexOf('"');
            return e > 0 ? auth.substring(0, auth.indexOf('"')) : null;

        } else {
            return null;
        }
    } else {
        // Nonstandard HTTP header. We have been told to trust this
        // header blindly as-is.
        //
        final String user = req.getHeader(loginHeader);
        return user != null && !"".equals(user) ? user : null;
    }
}

From source file:com.google.gerrit.httpd.RemoteUserUtil.java

License:Apache License

/**
 * Extracts username from an HTTP Basic or Digest authentication
 * header./*from   ww  w .  j a  va 2 s  .com*/
 *
 * @param auth header value which is used for extracting.
 * @return username if available or null.
 */
public static String extractUsername(String auth) {
    auth = emptyToNull(auth);

    if (auth == null) {
        return null;

    } else if (auth.startsWith("Basic ")) {
        auth = auth.substring("Basic ".length());
        auth = new String(Base64.decode(auth));
        final int c = auth.indexOf(':');
        return c > 0 ? auth.substring(0, c) : null;

    } else if (auth.startsWith("Digest ")) {
        final int u = auth.indexOf("username=\"");
        if (u <= 0) {
            return null;
        }
        auth = auth.substring(u + 10);
        final int e = auth.indexOf('"');
        return e > 0 ? auth.substring(0, e) : null;

    } else {
        return null;
    }
}

From source file:com.google.gerrit.httpd.rpc.account.AccountSecurityImpl.java

License:Apache License

public void validateEmail(final String token, final AsyncCallback<VoidResult> callback) {
    try {/*from  ww  w.j  a  v a 2 s  .c om*/
        final ValidToken t = authConfig.getEmailRegistrationToken().checkToken(token, null);
        if (t == null || t.getData() == null || "".equals(t.getData())) {
            callback.onFailure(new IllegalStateException("Invalid token"));
            return;
        }
        final String newEmail = new String(Base64.decode(t.getData()), "UTF-8");
        if (!newEmail.contains("@")) {
            callback.onFailure(new IllegalStateException("Invalid token"));
            return;
        }
        accountManager.link(user.get().getAccountId(), AuthRequest.forEmail(newEmail));
        callback.onSuccess(VoidResult.INSTANCE);
    } catch (XsrfException e) {
        callback.onFailure(e);
    } catch (UnsupportedEncodingException e) {
        callback.onFailure(e);
    } catch (AccountException e) {
        callback.onFailure(e);
    }
}

From source file:com.google.gerrit.httpd.SignedTokenRestTokenVerifier.java

License:Apache License

@Override
public void verify(Account.Id user, String url, String tokenString) throws InvalidTokenException {
    ValidToken token;/*from  w  ww . j  av  a2 s  .co m*/
    try {
        token = restToken.checkToken(tokenString, null);
    } catch (XsrfException err) {
        throw new InvalidTokenException(err);
    }
    if (token == null || token.getData() == null || token.getData().isEmpty()) {
        throw new InvalidTokenException();
    }

    String payload;
    try {
        payload = new String(Base64.decode(token.getData()), "UTF-8");
    } catch (UnsupportedEncodingException err) {
        throw new InvalidTokenException(err);
    }

    int colonPos = payload.indexOf(':');
    if (colonPos == -1) {
        throw new InvalidTokenException();
    }

    Account.Id tokenUser;
    try {
        tokenUser = Account.Id.parse(payload.substring(0, colonPos));
    } catch (IllegalArgumentException err) {
        throw new InvalidTokenException(err);
    }

    String tokenUrl = payload.substring(colonPos + 1);

    if (!tokenUser.equals(user) || !tokenUrl.equals(url)) {
        throw new InvalidTokenException();
    }
}

From source file:com.google.gerrit.server.mail.SignedTokenEmailTokenVerifier.java

License:Apache License

@Override
public ParsedToken decode(String tokenString) throws InvalidTokenException {
    ValidToken token;//from   w  ww.j  av a 2 s .  c  o  m
    try {
        token = emailRegistrationToken.checkToken(tokenString, null);
    } catch (XsrfException err) {
        throw new InvalidTokenException(err);
    }
    if (token == null || token.getData() == null || token.getData().isEmpty()) {
        throw new InvalidTokenException();
    }

    String payload;
    try {
        payload = new String(Base64.decode(token.getData()), "UTF-8");
    } catch (UnsupportedEncodingException err) {
        throw new InvalidTokenException(err);
    }

    Matcher matcher = Pattern.compile("^([0-9]+):(.+@.+)$").matcher(payload);
    if (!matcher.matches()) {
        throw new InvalidTokenException();
    }

    Account.Id id;
    try {
        id = Account.Id.parse(matcher.group(1));
    } catch (IllegalArgumentException err) {
        throw new InvalidTokenException(err);
    }

    String newEmail = matcher.group(2);
    return new ParsedToken(id, newEmail);
}

From source file:com.googlesource.gerrit.plugins.lfs.auth.LfsCipher.java

License:Apache License

public Optional<String> decrypt(String input) {
    if (Strings.isNullOrEmpty(input)) {
        return Optional.empty();
    }//w  w  w .  ja v a  2  s  .co  m

    byte[] bytes = Base64.decode(input);
    byte[] initVector = Arrays.copyOf(bytes, IV_LENGTH);
    try {
        Cipher cipher = cipher(initVector, Cipher.DECRYPT_MODE);
        return Optional
                .of(new String(cipher.doFinal(Arrays.copyOfRange(bytes, IV_LENGTH, bytes.length)), UTF_8));
    } catch (GeneralSecurityException e) {
        log.atSevere().withCause(e).log("Exception was thrown during token verification");
    }

    return Optional.empty();
}